{
 "manifest": {
  "schema": "CINT-MCP-MANIFEST-1",
  "mcp_edition": "MCP-P.1",
  "cint_version": "0.2.0",
  "release_date": "2026-10-11",
  "compiler_source_identity": "d6ebe30d604346afe4a7912c5d6f3ce2b9d401641d361772892b44b9292609ff",
  "editions": {
   "SPEC-00P.2": {
    "file": "SPEC-00P.2-OVERVIEW.md",
    "sha256": "178c5f24985cee295904b4f8e40de3901639a896d26a6e65c0a82c7039dc7bdc",
    "url": "/specifications/spec-00p/2/"
   },
   "SPEC-01P.2": {
    "file": "SPEC-01P.2-ENCODINGS.md",
    "sha256": "babdf9120505cfbbb407fea6f689f8633df8cb5d514c0668272aaf905411f9b5",
    "url": "/specifications/spec-01p/2/"
   },
   "SPEC-02P.1": {
    "file": "SPEC-02P.1-KERNELS.md",
    "sha256": "114e9eae0023795b813582acb5a4cf1c55498817b9450dc949e7ef98ecf6b934",
    "url": "/specifications/spec-02p/1/"
   },
   "SPEC-03P.1": {
    "file": "SPEC-03P.1-HOST-INTERFACE.md",
    "sha256": "f8557bdda83ee4c15aedec6e3b72daeb14780e5eaee61fb6394ce943e7b649b3",
    "url": "/specifications/spec-03p/1/"
   },
   "SPEC-04P.2": {
    "file": "SPEC-04P.2-LANGUAGE.md",
    "sha256": "9e9b252252c9c30c7db2b5a0e9abcd9300298f313f2fa80f4c0abc01198e58fd",
    "url": "/specifications/spec-04p/2/"
   },
   "SPEC-06P.1": {
    "file": "SPEC-06P.1-TOOLS.md",
    "sha256": "5ef9afe19d507a4a189909de09a70fbc912625c4cefdbad2439b323aff142908",
    "url": "/specifications/spec-06p/1/"
   },
   "SPEC-09P.1": {
    "file": "SPEC-09P.1-TOOLCHAIN.md",
    "sha256": "8f617fe3054287e48a809e59096cc1e228cce1d5206241146c335304628f8ddc",
    "url": "/specifications/spec-09p/1/"
   },
   "GLOSSARY-P.2": {
    "file": "GLOSSARY-P.2.md",
    "sha256": "da375611c36fbdef30fd10589be16b405d6a00af7fa6548360cd87d38083fc1b",
    "url": "/specifications/glossary-p/2/"
   },
   "REFERENCES-P.2": {
    "file": "REFERENCES-P.2.md",
    "sha256": "dad23c2919e7dadaf5fd405c9bfc8fc576fafff126d0e6fe455c9c18b0a7d501",
    "url": "/specifications/references-p/2/"
   },
   "ERRATA": {
    "file": "ERRATA.md",
    "sha256": "25c52c4c920cde074678465bd870f81eb3ecdc6437dc90971a3e523612cd9676",
    "url": "/specifications/errata/"
   }
  },
  "courses": [
   "CU-000.2",
   "CU-101.2",
   "CU-201.2",
   "CU-301.1",
   "CU-401.2"
  ],
  "instructions": "cint 0.2.0 (MCP-P.1): deterministic, capability-free integer programming language. No floating point (use scaled integers or muldiv(R, a, b, c, mode)), no implicit type promotions (use `x as T`), conditions require parentheses and Bool type (`if (x != 0) { ... }`), scalar variables require initializers (`I64 x = 0;`), and entry programs use `void main() { ... }`. Read `cint://cheat-sheet` or call `cint_get_recipe` before writing `.ci` code."
 },
 "tools": [
  {
   "name": "cint_search_docs",
   "description": "Search the frozen cint 0.2.0 public specifications (SPEC-00P.2 to SPEC-09P.1, GLOSSARY-P.2, ERRATA) and cint university lessons (CU-000.2 to CU-401.2).",
   "inputSchema": {
    "type": "object",
    "properties": {
     "query": {
      "type": "string",
      "description": "Keywords, clause ID (e.g. IM-63, LS-193), or topic"
     },
     "limit": {
      "type": "integer",
      "description": "Maximum results (1 to 10, default 5)"
     }
    },
    "required": [
     "query"
    ]
   }
  },
  {
   "name": "cint_get_doc",
   "description": "Retrieve a self-contained specification or cint university chunk by chunk_id.",
   "inputSchema": {
    "type": "object",
    "properties": {
     "chunk_id": {
      "type": "string",
      "description": "Chunk ID returned by cint_search_docs"
     }
    },
    "required": [
     "chunk_id"
    ]
   }
  },
  {
   "name": "cint_lookup_diagnostic",
   "description": "Explain a cint compiler diagnostic (C1001 to C9102) or runtime fault code (E_OVERFLOW to E_ASSERT) with before/after fixes.",
   "inputSchema": {
    "type": "object",
    "properties": {
     "code": {
      "type": "string",
      "description": "Diagnostic or fault code (e.g. C2001, C9102, E_OVERFLOW)"
     }
    },
    "required": [
     "code"
    ]
   }
  },
  {
   "name": "cint_get_recipe",
   "description": "Fetch a verified cint 0.2.0 .ci recipe (fixed-point-trig, fixed-point-ln-sqrt, wide-i1024-scaling, svg-generator, fnv1a-digest, money-ledger, kernel-double-buffer).",
   "inputSchema": {
    "type": "object",
    "properties": {
     "topic": {
      "type": "string",
      "description": "Recipe ID or topic keyword"
     }
    },
    "required": [
     "topic"
    ]
   }
  },
  {
   "name": "cint_list_curriculum",
   "description": "List all cint university courses and lessons (CU-000.2 to CU-401.2).",
   "inputSchema": {
    "type": "object",
    "properties": {}
   }
  }
 ],
 "resources_meta": [
  {
   "uri": "cint://manifest",
   "name": "cint 0.2.0 Edition & Toolchain Manifest",
   "mimeType": "application/json"
  },
  {
   "uri": "cint://from-c",
   "name": "cint for C Programmers (CU-000.2)",
   "mimeType": "text/markdown"
  },
  {
   "uri": "cint://from-python",
   "name": "cint for Python and NumPy Programmers (CU-000.2)",
   "mimeType": "text/markdown"
  },
  {
   "uri": "cint://cheat-sheet",
   "name": "cint 0.2.0 Language & Built-in Cheat Sheet",
   "mimeType": "text/markdown"
  },
  {
   "uri": "cint://refusals",
   "name": "cint 0.2.0 Compiler Refusals (SPEC-09P.1 Clause 12)",
   "mimeType": "text/markdown"
  }
 ],
 "resources": {
  "cint://manifest": "{\n  \"schema\": \"CINT-MCP-MANIFEST-1\",\n  \"mcp_edition\": \"MCP-P.1\",\n  \"cint_version\": \"0.2.0\",\n  \"release_date\": \"2026-10-11\",\n  \"compiler_source_identity\": \"d6ebe30d604346afe4a7912c5d6f3ce2b9d401641d361772892b44b9292609ff\",\n  \"editions\": {\n    \"SPEC-00P.2\": {\n      \"file\": \"SPEC-00P.2-OVERVIEW.md\",\n      \"sha256\": \"178c5f24985cee295904b4f8e40de3901639a896d26a6e65c0a82c7039dc7bdc\",\n      \"url\": \"/specifications/spec-00p/2/\"\n    },\n    \"SPEC-01P.2\": {\n      \"file\": \"SPEC-01P.2-ENCODINGS.md\",\n      \"sha256\": \"babdf9120505cfbbb407fea6f689f8633df8cb5d514c0668272aaf905411f9b5\",\n      \"url\": \"/specifications/spec-01p/2/\"\n    },\n    \"SPEC-02P.1\": {\n      \"file\": \"SPEC-02P.1-KERNELS.md\",\n      \"sha256\": \"114e9eae0023795b813582acb5a4cf1c55498817b9450dc949e7ef98ecf6b934\",\n      \"url\": \"/specifications/spec-02p/1/\"\n    },\n    \"SPEC-03P.1\": {\n      \"file\": \"SPEC-03P.1-HOST-INTERFACE.md\",\n      \"sha256\": \"f8557bdda83ee4c15aedec6e3b72daeb14780e5eaee61fb6394ce943e7b649b3\",\n      \"url\": \"/specifications/spec-03p/1/\"\n    },\n    \"SPEC-04P.2\": {\n      \"file\": \"SPEC-04P.2-LANGUAGE.md\",\n      \"sha256\": \"9e9b252252c9c30c7db2b5a0e9abcd9300298f313f2fa80f4c0abc01198e58fd\",\n      \"url\": \"/specifications/spec-04p/2/\"\n    },\n    \"SPEC-06P.1\": {\n      \"file\": \"SPEC-06P.1-TOOLS.md\",\n      \"sha256\": \"5ef9afe19d507a4a189909de09a70fbc912625c4cefdbad2439b323aff142908\",\n      \"url\": \"/specifications/spec-06p/1/\"\n    },\n    \"SPEC-09P.1\": {\n      \"file\": \"SPEC-09P.1-TOOLCHAIN.md\",\n      \"sha256\": \"8f617fe3054287e48a809e59096cc1e228cce1d5206241146c335304628f8ddc\",\n      \"url\": \"/specifications/spec-09p/1/\"\n    },\n    \"GLOSSARY-P.2\": {\n      \"file\": \"GLOSSARY-P.2.md\",\n      \"sha256\": \"da375611c36fbdef30fd10589be16b405d6a00af7fa6548360cd87d38083fc1b\",\n      \"url\": \"/specifications/glossary-p/2/\"\n    },\n    \"REFERENCES-P.2\": {\n      \"file\": \"REFERENCES-P.2.md\",\n      \"sha256\": \"dad23c2919e7dadaf5fd405c9bfc8fc576fafff126d0e6fe455c9c18b0a7d501\",\n      \"url\": \"/specifications/references-p/2/\"\n    },\n    \"ERRATA\": {\n      \"file\": \"ERRATA.md\",\n      \"sha256\": \"25c52c4c920cde074678465bd870f81eb3ecdc6437dc90971a3e523612cd9676\",\n      \"url\": \"/specifications/errata/\"\n    }\n  },\n  \"courses\": [\n    \"CU-000.2\",\n    \"CU-101.2\",\n    \"CU-201.2\",\n    \"CU-301.1\",\n    \"CU-401.2\"\n  ],\n  \"instructions\": \"cint 0.2.0 (MCP-P.1): deterministic, capability-free integer programming language. No floating point (use scaled integers or muldiv(R, a, b, c, mode)), no implicit type promotions (use `x as T`), conditions require parentheses and Bool type (`if (x != 0) { ... }`), scalar variables require initializers (`I64 x = 0;`), and entry programs use `void main() { ... }`. Read `cint://cheat-sheet` or call `cint_get_recipe` before writing `.ci` code.\"\n}",
  "cint://from-c": "# cint for C programmers\n\n<a id=\"from-c\"></a>This page is part of CU-000.2, checked against cint 0.2.0.\n\n*Read this before [201](201/README.md) if you know C. It lists what carries over, what changes and the lesson that shows each change running.*\n\n## what carries over\n\nMuch of cint reads like C. Functions are declared with the return type first, statements end with a semicolon and blocks are in braces. `if`, `else`, `while`, `break`, `continue` and `return` keep their meaning, and so does the C form of `for`. `switch` looks the same and differs in the ways listed below. Comments are written with `//`. Integer types say their width in the name: `I8` to `I1024` are signed and `U8` to `U512` are unsigned. `I32` is C's `int32_t` and `U8` is `uint8_t`. cint compiles a program to C17, and [201-00](201/00-start-here.md) shows the C it makes.\n\n## what changes\n\n| In C | In cint | Shown in |\n|---|---|---|\n| Signed overflow is undefined behavior. | Every plain operator is checked. A result that does not fit stops the program with a fault that names the operation, the operands and the exact result. | [201-01](201/01-numbers-that-hold.md) |\n| Unsigned arithmetic wraps without a sign of it. | Plain unsigned operators are checked too. Wrapping is written as an operator of its own, such as `+%`, and saturating as `+|`. | [201-03](201/03-operators-at-the-edge.md) |\n| A shift by the width of the type or more is undefined. | A shift that loses bits faults. | [201-03](201/03-operators-at-the-edge.md) |\n| Integer promotion and implicit conversions happen everywhere. | No conversion happens on its own, not even to a wider type. `as` converts and faults if the value does not fit. `as%` keeps the low bits and `as?` hands the failure to the program. | [201-02](201/02-types-and-conversions.md) |\n| `/` rounds toward zero, and `%` takes the sign of the dividend. | `/` rounds toward negative infinity, and `%` takes the sign of the divisor, as in Python. `div_trunc` and `rem_trunc` give C's results. | [201-04](201/04-division-and-rounding.md) |\n| A rounding rule is set somewhere else, or implied. | Each rounded division names its rule, such as `div_round(a, b, half_even)`. | [201-04](201/04-division-and-rounding.md) |\n| An array index is not checked. | Every index is checked, and one past the end faults with `E_BOUNDS`. | [101-12](101/12-lists.md) |\n| A function takes a pointer and a length. | A function takes a view of an array, `in I64[n]` to read it or `inout I64[n]` to change it, and the length travels with it. | [201-07](201/07-debugging-by-comparison.md), [201-09](201/09-functions.md) |\n| A deep recursion can crash when the stack runs out, unless the compiler turns it into a loop. The depth depends on the machine. | At most 256 calls can be in progress at once, counting `main`, and one more faults with `E_DEPTH` on every machine. | [201-09](201/09-functions.md) |\n| A `case` without `break` falls into the next. | A case ends at the next `case`. Falling through is written as `fallthrough;`. | [201-08](201/08-control-flow.md) |\n| `if (x = 5)` assigns and tests. | An assignment is a statement, so this is error C1041. | [201-08](201/08-control-flow.md) |\n| Braces around a body of one statement are optional. | Every body needs its braces. | [201-08](201/08-control-flow.md) |\n| `i++` is an expression with a value. | `i++` is a statement, and it is checked. | [201-08](201/08-control-flow.md) |\n| C uses `#include` and `#define`. | There is no preprocessor. `const` names a constant. | [401-02](401/02-hunting-an-overflow.md) |\n| C has `float` and `double`. | There is no floating-point type. Every value in these courses is an integer. | |\n\n## the same program on every compiler\n\nA C program that overflows can print one thing at `-O0` and another at `-O2`, and [301-01](301/01-when-64-bits-are-not-enough.md) shows one doing exactly that. A cint program prints the same bytes on GCC, Clang, MSVC and Apple Clang. When it faults, it prints the same fault record on each of them, field for field. So one saved output checks a run on any of those compilers, as [201-05](201/05-tests-and-goldens.md) shows.\n\n## where to start\n\nStart with [201-00](201/00-start-here.md). It sets up cint and shows the four commands and the C that a small program becomes.\n",
  "cint://from-python": "# cint for Python and NumPy programmers\n\n<a id=\"from-python\"></a>This page is part of CU-000.2, checked against cint 0.2.0.\n\n*Read this before [201](201/README.md) if you know Python. It lists what carries over, what changes and the lesson that shows each change running.*\n\n## what carries over\n\n`for i in 0..n` counts from 0 to n - 1, as `for i in range(n)` does. `/` on integers rounds toward negative infinity and `%` takes the sign of the divisor, which is Python's rule for `//` and `%`. A string with `{name}` inside prints the value of `name`, much as an f-string does. Tests can live in the same file as the code, and `cint test` runs them.\n\n## what changes\n\n| In Python or NumPy | In cint | Shown in |\n|---|---|---|\n| `int` grows to any size. | Every integer has a fixed width, from `I8` to `I1024`. A result that does not fit stops the program with a fault that names the operation, the operands and the exact result. | [201-01](201/01-numbers-that-hold.md), [301-01](301/01-when-64-bits-are-not-enough.md) |\n| A NumPy `int64` array wraps without a warning, and an `int64` scalar warns and carries on with the wrapped value. | Arrays and single values are checked the same way. Wrapping is written as an operator of its own, such as `+%`. | [201-01](201/01-numbers-that-hold.md), [201-03](201/03-operators-at-the-edge.md) |\n| `astype(np.int16)` keeps the low bits of a value that does not fit. | `as I16` faults when the value does not fit. `as% I16` keeps the low bits when that is the intent. | [201-02](201/02-types-and-conversions.md) |\n| A variable takes whatever type is assigned to it. | Each variable is declared with its type, and no value changes type on its own. | [201-02](201/02-types-and-conversions.md) |\n| `round` rounds ties to even, without saying so at the call. | Each rounded division names its rule, such as `div_round(a, b, half_even)`. | [201-04](201/04-division-and-rounding.md) |\n| `float` is the default for fractions. | There is no floating-point type. Every value in these courses is an integer. | |\n| Indentation marks a block. | Braces mark a block, and every body needs them. | [201-08](201/08-control-flow.md) |\n| A deep recursion stops with `RecursionError`. | At most 256 calls can be in progress at once, counting `main`, and one more faults with `E_DEPTH`. | [201-09](201/09-functions.md) |\n| A list grows and shrinks. | An array has a fixed length, and every index is checked. | [101-12](101/12-lists.md) |\n| A function can change a list it is given. | A function says what it may do with an array: `in` to read it, `inout` to change it. | [201-09](201/09-functions.md) |\n| The interpreter runs the source. | cint compiles the program to C and runs it, or runs it in an interpreter for debugging. For every program in these courses, both print the same bytes. | [201-00](201/00-start-here.md), [201-06](201/06-workbench.md) |\n\n## why the fixed widths\n\nPython's integers never run out of room, so a sum or product of them is never cut short. A fixed width matches the data that sensors, files, images and network packets carry. In NumPy the price of a fixed width is a wrong answer when a value outgrows it, with a warning for a single value and none for an array. In cint the price is a fault at the exact operation, with the numbers that caused it. When a program needs more room, a wider type such as `I128` or `I1024` holds it. It needs an `as` wherever it meets a narrower value, as [301-04](301/04-big-exact-numbers.md) shows with 100 factorial.\n\n## the same output on every compiler\n\nA cint program prints the same bytes on every compiler cint supports, and a fault prints the same record on each of them. [201-05](201/05-tests-and-goldens.md) builds a way of testing on this: save a program's output once and compare every run after it against the saved copy.\n\n## where to start\n\nStart with [201-00](201/00-start-here.md). It sets up cint and shows its four commands.\n",
  "cint://cheat-sheet": "# cint 0.2.0 Cheat Sheet (SPEC-04P.2, SPEC-06P.1, SPEC-09P.1)\n\n## 1. File & Program Structure\n- File extension is `.ci` (never `.cint`, C1001). File stem must be a valid identifier `[A-Za-z_][A-Za-z0-9_]*` (no leading digits or hyphens, C3030).\n- Put entry code inside `void main() { ... }` (or `MyError!void main()`). Top-level statements make a file a script whose variables are invisible to functions and tests (C3004) and where top-level arrays/structs are refused (C9102).\n- Inside any block, place array declarations (`I64[4] buf;`) before scalar declarations (`I64 x = 0;`) and statements.\n\n## 2. Types (Zero Floating Point, Zero Implicit Promotion)\n- Signed integers: `I8`, `I16`, `I32`, `I64`, `I128`, `I256`, `I512`, `I1024`.\n- Unsigned integers: `U8`, `U16`, `U32`, `U64` (`U128`, `U256`, `U512` are refused in 0.2.0 with C9102; `U1024` does not exist).\n- Boolean: `Bool` (`true`, `false`). Conditions in `if (cond)` and `while (cond)` must be `Bool` (C2002) and must have parentheses (C1043).\n- Every scalar variable requires an initializer (`I64 x = 0;`, C2050). Arrays zero-initialize (`I64[16] buf;`).\n- Constants require a type: `const I64 SCALE = 1_000_000;`.\n\n## 3. Operators & Conversions\n- Checked (default): `+`, `-`, `*`, `/`, `%`, `<<`, `>>`, `as T`. Faults on overflow (`E_OVERFLOW`), div-by-zero (`E_DIV_ZERO`), invalid shift count (`E_SHIFT`), or out-of-range cast (`E_NARROW`).\n- Wrapping: `+%`, `-%`, `*%`, `<<%`, `as% T`. Never faults on overflow.\n- Saturating: `+|`, `-|`, `*|`, `as| T`. Clamps to `[T.min, T.max]`.\n- Signed `/` and `%` use floor division (`-7 / 2 == -4`, `-7 % 2 == 1`). Use `div_trunc(a, b)` and `rem_trunc(a, b)` for C truncation toward zero.\n- Logical operators: `&&`, `||`, `!` (no `and`/`or`). Chained comparisons `0 <= i < n` are C2102; write `0 <= i && i < n`.\n- `++` and `--` are statements (`i += 1;` or `i++;`), never expressions (C1042).\n\n## 4. Built-in Exact Arithmetic\n- `muldiv(R, a, b, c, mode)`: Exact `(a * b) / c` in a double-width intermediate, rounded once by `mode` (`half_even`, `floor`, `ceil`, `zero`, `away`, `half_up`, `half_down`, `pass`). In `cint 0.2.0`, `a`, `b`, `c`, and `R` must have the same type (widen operands first with `as R`).\n- `mul_full(a, b)`: Exact product in double width (`I64 * I64 -> I128`, up to `I512 * I512 -> I1024`).\n- `div_round(a, b, mode)`, `isqrt(x)`, `isqrt_round(x, mode)`, `abs(x)`, `uabs(x)`, `min(a, b)`, `max(a, b)`, `clamp(x, lo, hi)`, `rotl(x, k)`, `rotr(x, k)`.\n- Reductions: `sum(R, xs)`, `dot(R, a, b)`, `count(bs)`.\n\n## 5. Arrays, Structs, Functions, and Error Unions\n- Generic array views: `I64 total[n](in I64[n] xs)` (read-only) or `void scale_in_place[n](inout I64[n] xs, I64 k)`.\n- 2D indexing uses a comma: `grid[y, x]`, slicing `grid[y, 0..w]`.\n- Structs: `struct Pair { I64 a; I64 b; }` constructed positionally `Pair(1, 2)`.\n- Error unions: `error MathErr { bad_input }` -> `MathErr!I64 compute(I64 x)` -> `return .bad_input;` -> caller uses `try compute(x)` or `compute(x) catch 0`.\n- Printing: Bare string statement `\"value={x} dollars={cents:/100} hex={u:#x}\\n\";` (no `print()` function).\n",
  "cint://refusals": "## 12 Refusals of the cint tools in 0.2.0\n\nThis clause is informative. It lists the constructs that the reference runs and that a tool of cint 0.2.0 refuses, by construct, with the tool and the diagnostic, and the limits of the tools that are below the minimums of SPEC-04P.2. A refused program is not run with another meaning (8.2), and on an implementation that runs it, its outcome is the one SPEC-04P.2 specifies. The interpreter runs the SIR text that `cint` writes, so a construct that `cint` refuses does not reach it.\n\n1. The `cint` command (`cint run`, `cint build`, `cint test` and `cint emit-c`) refuses these constructs with the diagnostic C9102, or the one that the row names, at the position shown:\n\n| Construct | Example | Position |\n| --- | --- | --- |\n| Fixed-point types `Q<i>.<f>` and fraction literals | `Q16.16 a = 1.5;`, `Q8.8 x = 0.25;` | the type |\n| `as?` from a wide type | `I64 r = v as? I64 catch -1;` with `I128 v` | the operand |\n| A result form on a wide type | `I128 r = add_result(a, b) catch 0;` | the call |\n| `switch` on a wide value | `switch (v)` with `I256 v` | the scrutinee |\n| `rotl` and `rotr` by a count of a wide type | `rotl(a, n)` with `U64 a`, `I128 n` | the call |\n| `muldiv` of narrow operands into a wide result type | `muldiv(I128, a, b, c, floor)` with `I64` operands | the call |\n| An exported function with a parameter or a result of a wide integer type or a fixed-point type | `export I64 low(I128 x)` | the parameter's name, or the result type |\n| An array declared at the top level of a script | `I64[3] a = [1, 2, 3];` | the array literal, or the declaration when it has none |\n| A struct type declared in a script | `struct P { I64 x; I64 y; }` before top-level statements | the struct's name |\n| An array literal of structs | `P[2] ps = [P(1, 2), P(3, 4)];` | the `[` of the literal |\n| A view variable over an array of structs | `in P[_] v = ps;` | the variable's name |\n| Named arguments in a call of a user function | `diff(b = 1, a = 10)` | the first name |\n| A step `by` in a range `for` loop | `for i in 0..10 by 3 { ... }` | the step |\n| A selected import | `import geo.vec.{V2, dot2};` | the `import` |\n| `catch` on a call of a function of an imported module | `parse.digit(c) catch -1` with `import lib.parse;` | the function's name |\n| A `catch` expression as the operand of another operator | `(f(1) catch 0) + 1` | the `catch` |\n| The wrapping negation `-%` | `I8 n = -%m;` | the operator |\n| `len` of a string literal | `len(\"abc\")` | the string literal |\n| The format conversions `!bits` and `!lanes(T)` in a print statement | `\"{x!bits}\\n\";`, `\"{w!lanes(U8)}\\n\";` | the print statement |\n| The format kind `c` | `\"{c:c}\\n\";` | the value of the hole |\n| An array, or a slice of one, as the value of a hole | `\"{a}\\n\";`, `\"{a[1..]}\\n\";` with `I32[3] a` | the value of the hole, or the `[` of the slice |\n| An empty struct type | `struct Empty { }` | the struct's name |\n| An array literal as an argument of a struct constructor | `Vec3([1, 2, 3])` | the `[` of the literal |\n| An array literal as the right operand of an assignment, to an array or a slice | `a = [3, 4];`, `a[0..2] = [3, 4];` | the `[` of the literal |\n| A module-level array whose extent is the name of a constant or a constant expression | `I64[N] table;`, `I64[N * 2] table;` | the name, or the operator of the expression |\n| An array of handles | `Handle(I64)[3] hs;` | the type |\n| An exported arena | `export Arena(I64, 4) store;` | the type |\n| An array element as the scalar `out` argument of a kernel | `total(a, r[0]);` | the `[` of the element |\n| A local `Arena(T)` or `Pool(T)` initialized from a module-level name | `Arena(I64) s = scratch;` | the local's name |\n| Arena storage, or a view variable over it, passed to a view parameter | `total(scratch[h])` | the call |\n| A slice of arena storage, or of a view variable over it | `scratch[h][2..4]`, `v[2..5]` | the `[` of the slice |\n| A dispatch of a kernel of an imported module, called after the module's name or alias | `dbl.twice(a, b);` with `import kmod.dbl;` | the kernel's name, with the diagnostic C3005 |\n\n2. A program whose entry is a function `main`, rather than top-level statements, may declare struct types: the row of a struct declared in a script applies to scripts only. The `cint` command also reports C9102 for `==` between two arrays, which the reference rejects with the diagnostic C2013 at the same position, so both reject such a program. It reports C9102 for a fraction literal given to an integer type, as in `I64 x = 1.5;`, which the reference rejects with the diagnostic C2004 at the same position. In the same way it reports C9102, at the print statement, for the conversion `!ratio` of an integer, as in `\"{x!ratio}\\n\";` with `I64 x`. SPEC-04P.2 7.5.4 makes that conversion C1037, and the reference reports C1037 at the value of the hole. The C3005 of a kernel called after a module's name is not a refusal in the sense of SPEC-04P.2 4, paragraph 4, whose codes begin with `C9`: the `cint` command rejects that conforming program as it rejects an undefined name.\n3. In one case the direction is reversed, and the reference refuses a run that the `cint` command carries out. For `clamp(x, lo, hi)` with `lo` greater than `hi` at run time, `cint run` faults `E_DOMAIN` with the operation `clamp.checked.<t>`, such as `clamp.checked.i64`, and the operands `x`, `lo` and `hi`, with no exact result and no limit, as SPEC-04P.2 7.2.1 states. The reference reports the outcome `refused` for that run.\n4. A `gpu-cuda` build refuses a kernel whose body needs a capability that the `gpu-cuda` table lists as unsupported, with `E_UNSUPPORTED`, naming the kernel, the capability, the SIR node and the position (5.5). The `cpu-c17` build of the same program runs it.\n\n| Capability | Construct in a kernel body | Example |\n| --- | --- | --- |\n| `sat` | the saturating operators `+\\|`, `-\\|` and `*\\|` | `b[i] = a[i] +\\| a[i];` |\n| `div` | `/` and `%` | `b[i] = a[i] / 2;` |\n| `shift` | `<<` and `>>`, wrapping or checked | `b[i] = a[i] << 1;` |\n| `bits` | `&`, `\\|`, `^`, `~` and `!` | `b[i] = a[i] & 3;` |\n| `neg` | unary `-` | `b[i] = -a[i];` |\n| `as.wrap` | the wrapping conversion `as%` | `(a[i] as% I32) as I64` |\n| `builtin` | every built-in function except `div_round` | `b[i] = min(a[i], 2);` |\n| `switch` | `switch` | `switch (a[i]) { ... }` |\n| `store.narrow` | a store into a view of 8-bit, 16-bit or `Bool` elements | `out U8[n] b` |\n| `array` | a local array | `I64[2] t;` |\n| `wide` | any value of `I128` to `I1024` | `in I128[n] a` |\n\n5. Three limits of the tools of cint 0.2.0 are below the minimums that SPEC-04P.2 5.3 states. A program beyond any of them is stopped, and the reference runs it:\n\n| Quantity | Minimum in SPEC-04P.2 5.3 | Limit of the tools | Beyond the limit |\n| --- | --- | --- | --- |\n| Size of one source file | 16,777,216 bytes | 4,194,304 bytes, in `cint run`, `cint build`, `cint test` and `cint emit-c` | For the file it is given, the command stops with a tool error and exit status 5; an imported module of that size is the diagnostic C3009. The reference runs a file of 5,242,880 bytes. |\n| Call-depth limit accepted as a semantic input | 4,096 active calls | 1,024 active calls, the constant `CINT_RT_MAX_DEPTH` of the runtime (7.10) | An entry whose depth limit is larger faults `E_UNSUPPORTED` at `call.enter` before it runs, with the limit 1,024. The reference runs a recursion 4,000 calls deep under a depth limit of 4,096. |\n| Size of an imported module, against the size of the root module | 16,777,216 bytes, as for every source file | A bound that grows with the size of the root module, in `cint run`, `cint build`, `cint test` and `cint emit-c`: 745,090 bytes for a root module of 34 bytes | The command stops with the diagnostic C9001 at line 0 of the root module, position `0:0`, though the imported module is under 4,194,304 bytes; SPEC-04P.2 5.3 places a C9001 that concerns a whole file at line 1. Under a root module of 34 bytes, an imported module of 745,091 bytes is C9001. Under a root module of 341 bytes, an imported module of 4,000,000 bytes runs, and so does a root module of 4,000,000 bytes that holds the same function. The reference runs the program. |\n\n<a id=\"future-directions\"></a>"
 },
 "prompts": [
  {
   "name": "write-cint-program",
   "description": "Guided workflow for writing and verifying a deterministic cint 0.2.0 program.",
   "arguments": [
    {
     "name": "task",
     "description": "What the cint program should compute or generate",
     "required": true
    }
   ]
  },
  {
   "name": "port-to-cint",
   "description": "Workflow for porting C, Python, or floating-point code to exact fixed-point cint.",
   "arguments": [
    {
     "name": "source_lang",
     "description": "Source language (C, Python, JS)",
     "required": false
    }
   ]
  },
  {
   "name": "diagnose-fault",
   "description": "Workflow for diagnosing a compile error (Cxxxx) or runtime fault (E_*) in cint.",
   "arguments": [
    {
     "name": "code",
     "description": "Diagnostic or fault code",
     "required": true
    }
   ]
  }
 ],
 "diagnostics": [
  {
   "code": "C1001",
   "kind": "diagnostic",
   "meaning": "a source file named with the extension `.cint`",
   "spec": "SPEC-04P.2 5.1.1",
   "ai_cause": "Used `.cint` file extension instead of `.ci`.",
   "bad_example": "cint run demo.cint",
   "good_example": "cint run demo.ci"
  },
  {
   "code": "C1002",
   "kind": "diagnostic",
   "meaning": "a byte-order mark, invalid UTF-8 or the byte 0x00",
   "spec": "SPEC-04P.2 6.4.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.1: a byte-order mark, invalid UTF-8 or the byte 0x00.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1003",
   "kind": "diagnostic",
   "meaning": "a forbidden invisible or bidirectional character",
   "spec": "SPEC-04P.2 6.4.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.1: a forbidden invisible or bidirectional character.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1004",
   "kind": "diagnostic",
   "meaning": "a control character, or a CR not followed by LF",
   "spec": "SPEC-04P.2 6.4.1, 6.4.2",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.1, 6.4.2: a control character, or a CR not followed by LF.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1005",
   "kind": "diagnostic",
   "meaning": "an unterminated block comment",
   "spec": "SPEC-04P.2 6.4.3",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.3: an unterminated block comment.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1010",
   "kind": "diagnostic",
   "meaning": "a declared name that is `I`, `U`, `Q` or `T` followed only by digits",
   "spec": "SPEC-04P.2 6.4.4",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.4: a declared name that is `I`, `U`, `Q` or `T` followed only by digits.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1011",
   "kind": "diagnostic",
   "meaning": "an unknown fault name after `expect_fault`",
   "spec": "SPEC-04P.2 6.4.4",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.4: an unknown fault name after `expect_fault`.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1012",
   "kind": "diagnostic",
   "meaning": "an identifier over 255 bytes",
   "spec": "SPEC-04P.2 6.4.4",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.4: an identifier over 255 bytes.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1013",
   "kind": "diagnostic",
   "meaning": "a non-ASCII character outside a literal or a comment",
   "spec": "SPEC-04P.2 6.4.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.1: a non-ASCII character outside a literal or a comment.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1020",
   "kind": "diagnostic",
   "meaning": "an uppercase radix prefix, such as `0X`",
   "spec": "SPEC-04P.2 6.4.5",
   "ai_cause": "Used uppercase radix prefix `0X`, `0B`, or `0O`.",
   "bad_example": "U64 mask = 0XFF;",
   "good_example": "U64 mask = 0xff;"
  },
  {
   "code": "C1021",
   "kind": "diagnostic",
   "meaning": "a misplaced digit separator `_`",
   "spec": "SPEC-04P.2 6.4.5",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.5: a misplaced digit separator `_`.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1022",
   "kind": "diagnostic",
   "meaning": "a decimal literal of two or more digits that begins with `0`",
   "spec": "SPEC-04P.2 6.4.5",
   "ai_cause": "Wrote a multi-digit decimal literal with a leading zero (octal uses `0o`).",
   "bad_example": "I64 x = 007;",
   "good_example": "I64 x = 7; // or 0o7 for octal"
  },
  {
   "code": "C1023",
   "kind": "diagnostic",
   "meaning": "a literal over 4,096 bits of magnitude",
   "spec": "SPEC-04P.2 6.4.5",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.5: a literal over 4,096 bits of magnitude.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1024",
   "kind": "diagnostic",
   "meaning": "a radix prefix or a point with no digit after it, or a digit outside the radix",
   "spec": "SPEC-04P.2 6.4.5",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.5: a radix prefix or a point with no digit after it, or a digit outside the radix.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1030",
   "kind": "diagnostic",
   "meaning": "a character literal that is empty or holds more than one character",
   "spec": "SPEC-04P.2 6.4.7",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.7: a character literal that is empty or holds more than one character.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1031",
   "kind": "diagnostic",
   "meaning": "an escape that is not a Unicode scalar value",
   "spec": "SPEC-04P.2 6.4.7, 6.4.8",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.7, 6.4.8: an escape that is not a Unicode scalar value.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1032",
   "kind": "diagnostic",
   "meaning": "an unknown escape, or `\\x` above 7F",
   "spec": "SPEC-04P.2 6.4.7, 6.4.8",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.7, 6.4.8: an unknown escape, or `\\x` above 7F.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1033",
   "kind": "diagnostic",
   "meaning": "a hole outside a print statement or an `assert` message",
   "spec": "SPEC-04P.2 6.4.8, 7.5.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.8, 7.5.1: a hole outside a print statement or an `assert` message.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1034",
   "kind": "diagnostic",
   "meaning": "a line break in a string literal",
   "spec": "SPEC-04P.2 6.4.8",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.8: a line break in a string literal.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1035",
   "kind": "diagnostic",
   "meaning": "an invalid hole: empty, unterminated, holding a string literal or an unparenthesized conditional expression, or naming an unknown conversion",
   "spec": "SPEC-04P.2 7.5.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 7.5.1: an invalid hole: empty, unterminated, holding a string literal or an unparenthesized conditional expression, or naming an unknown conversion.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1036",
   "kind": "diagnostic",
   "meaning": "a precision together with a scale",
   "spec": "SPEC-04P.2 7.5.3",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 7.5.3: a precision together with a scale.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1037",
   "kind": "diagnostic",
   "meaning": "a format specification that does not match the syntax or does not apply to the value",
   "spec": "SPEC-04P.2 7.5.3, 7.5.4",
   "ai_cause": "Used a C printf or Python float format specifier (`%.2f`, `%d`), or wrote `_` inside a `/scale` divisor (scale after `:/` takes plain digits only).",
   "bad_example": "\"{cents:.2f} {u:/1_000_000}\\n\";",
   "good_example": "\"{cents:/100} {u:/1000000}\\n\"; // exact decimal scaling with plain digits"
  },
  {
   "code": "C1038",
   "kind": "diagnostic",
   "meaning": "an unterminated string or character literal",
   "spec": "SPEC-04P.2 6.4.7, 6.4.8",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.7, 6.4.8: an unterminated string or character literal.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1039",
   "kind": "diagnostic",
   "meaning": "a single `}` in a string literal",
   "spec": "SPEC-04P.2 6.4.8",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.8: a single `}` in a string literal.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1040",
   "kind": "diagnostic",
   "meaning": "an empty statement",
   "spec": "SPEC-04P.2 6.10.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.10.1: an empty statement.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C1041",
   "kind": "diagnostic",
   "meaning": "an assignment in a condition",
   "spec": "SPEC-04P.2 6.10.2",
   "ai_cause": "Used `=` assignment inside an `if` or `while` condition.",
   "bad_example": "if (x = 5) { }",
   "good_example": "if (x == 5) { }"
  },
  {
   "code": "C1042",
   "kind": "diagnostic",
   "meaning": "`++` or `--` used as an expression",
   "spec": "SPEC-04P.2 6.7.14",
   "ai_cause": "Used `i++` or `i--` inside an expression (in cint, `++` and `--` are statements only).",
   "bad_example": "a[i++] = 1;",
   "good_example": "a[i] = 1;\ni += 1;"
  },
  {
   "code": "C1043",
   "kind": "diagnostic",
   "meaning": "a condition without parentheses, or a body without braces",
   "spec": "SPEC-04P.2 6.10.2 to 6.10.4",
   "ai_cause": "Omitted parentheses around an `if`/`while`/`switch` condition, or omitted `{ }` braces around a body.",
   "bad_example": "if x < 10 {\n    x += 1;\n}",
   "good_example": "if (x < 10) {\n    x += 1;\n}"
  },
  {
   "code": "C1050",
   "kind": "diagnostic",
   "meaning": "a syntax error: an expected token or construct is missing",
   "spec": "SPEC-04P.2 Annex A",
   "ai_cause": "Syntax error: check for `fn`/`def`/`let` keywords (not in cint), kernel parameters missing explicit `in`/`out`/`inout` mode, `catch` block missing `(err)` binding (`catch (err) { ... }` or `catch fallback_expr`), or Python `and`/`or` (use `&&`/`||`).",
   "bad_example": "kernel scale[n](in I64[n] a, I64 k, out I64[n] b) over [i: n] { b[i] = a[i] * k; }",
   "good_example": "kernel scale[n](in I64[n] a, in I64 k, out I64[n] b) over [i: n] { b[i] = a[i] * k; }"
  },
  {
   "code": "C2001",
   "kind": "diagnostic",
   "meaning": "a type mismatch",
   "spec": "SPEC-04P.2 6.5, 6.7",
   "ai_cause": "Mixed two integer widths or signedness without an explicit conversion (`cint` has zero implicit promotions).",
   "bad_example": "I64 a = 10;\nI32 b = 20;\nI64 c = a + b;",
   "good_example": "I64 a = 10;\nI32 b = 20;\nI64 c = a + (b as I64);"
  },
  {
   "code": "C2002",
   "kind": "diagnostic",
   "meaning": "a condition, or an operand of `!`, that is not `Bool`",
   "spec": "SPEC-04P.2 6.3.3, 6.10",
   "ai_cause": "Used an integer expression as a condition or with `!` (`if (x)` is rejected; conditions must be `Bool`).",
   "bad_example": "if (count) { }",
   "good_example": "if (count != 0) { }"
  },
  {
   "code": "C2003",
   "kind": "diagnostic",
   "meaning": "a literal or constant that does not fit its type",
   "spec": "SPEC-04P.2 6.4.5, 6.5",
   "ai_cause": "Wrote a literal or constant outside the range of its target type.",
   "bad_example": "I8 x = 200;",
   "good_example": "U8 x = 200; // or I16 x = 200;"
  },
  {
   "code": "C2004",
   "kind": "diagnostic",
   "meaning": "a fraction literal given an integer type",
   "spec": "SPEC-04P.2 6.4.6",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.4.6: a fraction literal given an integer type.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2005",
   "kind": "diagnostic",
   "meaning": "a fixed-point type spelling that names no format",
   "spec": "SPEC-04P.2 6.3.2",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.3.2: a fixed-point type spelling that names no format.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2006",
   "kind": "diagnostic",
   "meaning": "a fraction literal off its type's grid without a `round` clause",
   "spec": "SPEC-04P.2 6.5",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.5: a fraction literal off its type's grid without a `round` clause.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2007",
   "kind": "diagnostic",
   "meaning": "an error value `.name` without an error-set context",
   "spec": "SPEC-04P.2 6.5",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.5: an error value `.name` without an error-set context.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2008",
   "kind": "diagnostic",
   "meaning": "a conversion between two types that have none",
   "spec": "SPEC-04P.2 6.6",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.6: a conversion between two types that have none.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2009",
   "kind": "diagnostic",
   "meaning": "a `round` clause on a conversion that does not round",
   "spec": "SPEC-04P.2 6.6, 6.7.15",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.6, 6.7.15: a `round` clause on a conversion that does not round.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2010",
   "kind": "diagnostic",
   "meaning": "a partial index indexed again, where `m[i, j]` is meant",
   "spec": "SPEC-04P.2 6.12.2",
   "ai_cause": "Indexed a multi-dimensional array with `a[i][j]` instead of `a[i, j]`.",
   "bad_example": "I64 v = grid[y][x];",
   "good_example": "I64 v = grid[y, x];"
  },
  {
   "code": "C2011",
   "kind": "diagnostic",
   "meaning": "an array literal with the wrong number of elements",
   "spec": "SPEC-04P.2 6.12.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.12.1: an array literal with the wrong number of elements.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2012",
   "kind": "diagnostic",
   "meaning": "extents, known during translation, that differ",
   "spec": "SPEC-04P.2 6.12.5, 7.4",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.12.5, 7.4: extents, known during translation, that differ.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2013",
   "kind": "diagnostic",
   "meaning": "arrays compared with a comparison operator",
   "spec": "SPEC-04P.2 6.12.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.12.1: arrays compared with a comparison operator.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2014",
   "kind": "diagnostic",
   "meaning": "`len` of an array of rank 2 or more",
   "spec": "SPEC-04P.2 7.4",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 7.4: `len` of an array of rank 2 or more.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2015",
   "kind": "diagnostic",
   "meaning": "a negative constant extent",
   "spec": "SPEC-04P.2 6.12.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.12.1: a negative constant extent.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2020",
   "kind": "diagnostic",
   "meaning": "a struct field not supplied",
   "spec": "SPEC-04P.2 6.9.6",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.9.6: a struct field not supplied.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2022",
   "kind": "diagnostic",
   "meaning": "the wrong number of arguments or fields",
   "spec": "SPEC-04P.2 6.9.5, 7.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.9.5, 7.1: the wrong number of arguments or fields.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2031",
   "kind": "diagnostic",
   "meaning": "an error set with a signed underlying type, or with more values than its underlying type holds",
   "spec": "SPEC-04P.2 6.9.7",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.9.7: an error set with a signed underlying type, or with more values than its underlying type holds.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2040",
   "kind": "diagnostic",
   "meaning": "an error union not consumed by `try`, `catch` or `_ =`",
   "spec": "SPEC-04P.2 6.11",
   "ai_cause": "Ignored an error-union return value without `try`, `catch`, or `_ =`.",
   "bad_example": "apply_entry(bal, e);",
   "good_example": "bal = try apply_entry(bal, e);"
  },
  {
   "code": "C2042",
   "kind": "diagnostic",
   "meaning": "an error value that the function's error set does not hold",
   "spec": "SPEC-04P.2 6.11",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.11: an error value that the function's error set does not hold.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2043",
   "kind": "diagnostic",
   "meaning": "`try` applied to a value that is not an error union",
   "spec": "SPEC-04P.2 6.11",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.11: `try` applied to a value that is not an error union.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2044",
   "kind": "diagnostic",
   "meaning": "an error value name held by several member sets of a combined set",
   "spec": "SPEC-04P.2 6.3.7",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.3.7: an error value name held by several member sets of a combined set.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2050",
   "kind": "diagnostic",
   "meaning": "a scalar variable without an initializer",
   "spec": "SPEC-04P.2 6.9.1",
   "ai_cause": "Declared a scalar variable without an initializer (`I64 x;` is forbidden; only arrays zero-initialize automatically).",
   "bad_example": "I64 total;",
   "good_example": "I64 total = 0;"
  },
  {
   "code": "C2051",
   "kind": "diagnostic",
   "meaning": "an arena or pool stored in a struct field or an array element",
   "spec": "SPEC-04P.2 6.3.6, 6.14",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.3.6, 6.14: an arena or pool stored in a struct field or an array element.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2052",
   "kind": "diagnostic",
   "meaning": "an assignment to a loop variable",
   "spec": "SPEC-04P.2 6.10.4",
   "ai_cause": "Assigned to a `for` loop variable inside the loop body.",
   "bad_example": "for i in 0..10 {\n    i += 1;\n}",
   "good_example": "for i in 0..10 {\n    I64 step = i + 1;\n}"
  },
  {
   "code": "C2053",
   "kind": "diagnostic",
   "meaning": "a step `by` that is not a nonzero constant",
   "spec": "SPEC-04P.2 6.10.4, 6.12.3",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.10.4, 6.12.3: a step `by` that is not a nonzero constant.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2054",
   "kind": "diagnostic",
   "meaning": "a declaration without an initializer that would fill an error-set value with zero",
   "spec": "SPEC-04P.2 6.3.7",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.3.7: a declaration without an initializer that would fill an error-set value with zero.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2055",
   "kind": "diagnostic",
   "meaning": "a struct that contains itself",
   "spec": "SPEC-04P.2 6.9.6",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.9.6: a struct that contains itself.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2056",
   "kind": "diagnostic",
   "meaning": "an integer used as `Bool`",
   "spec": "SPEC-04P.2 6.6",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.6: an integer used as `Bool`.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2058",
   "kind": "diagnostic",
   "meaning": "an assignment to a constant or to something that is not a place",
   "spec": "SPEC-04P.2 6.7.14",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.7.14: an assignment to a constant or to something that is not a place.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2060",
   "kind": "diagnostic",
   "meaning": "an assignment to a parameter",
   "spec": "SPEC-04P.2 6.9.5",
   "ai_cause": "Assigned to an `in` parameter (parameters are read-only unless declared `inout` on an array/struct).",
   "bad_example": "void bump(I64 x) { x += 1; }",
   "good_example": "I64 bump(I64 x) { return x + 1; }"
  },
  {
   "code": "C2062",
   "kind": "diagnostic",
   "meaning": "a parameter given more than one argument",
   "spec": "SPEC-04P.2 6.9.5",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.9.5: a parameter given more than one argument.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2063",
   "kind": "diagnostic",
   "meaning": "an unknown named argument, or a named argument to a built-in operation",
   "spec": "SPEC-04P.2 6.9.5, 7.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.9.5, 7.1: an unknown named argument, or a named argument to a built-in operation.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2064",
   "kind": "diagnostic",
   "meaning": "an `inout` parameter of a scalar type",
   "spec": "SPEC-04P.2 6.9.5",
   "ai_cause": "Declared a scalar parameter as `inout` (`inout` is only for arrays and structs; return scalar values instead).",
   "bad_example": "void add_one(inout I64 x) { }",
   "good_example": "I64 add_one(I64 x) { return x + 1; }"
  },
  {
   "code": "C2065",
   "kind": "diagnostic",
   "meaning": "a size parameter bound by no array or view parameter",
   "spec": "SPEC-04P.2 6.9.4, 6.13.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.9.4, 6.13.1: a size parameter bound by no array or view parameter.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2066",
   "kind": "diagnostic",
   "meaning": "a `return` value missing or not allowed",
   "spec": "SPEC-04P.2 6.10.8",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.10.8: a `return` value missing or not allowed.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2067",
   "kind": "diagnostic",
   "meaning": "an argument or destination that is not writable",
   "spec": "SPEC-04P.2 6.9.5, 7.4",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.9.5, 7.4: an argument or destination that is not writable.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2069",
   "kind": "diagnostic",
   "meaning": "a positional argument after a named one",
   "spec": "SPEC-04P.2 6.9.5",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.9.5: a positional argument after a named one.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C2101",
   "kind": "diagnostic",
   "meaning": "parentheses required",
   "spec": "SPEC-04P.2 6.7.2",
   "ai_cause": "Mixed operators whose relative precedence requires explicit parentheses (such as bitwise and shift or logical operators).",
   "bad_example": "Bool ok = a && b || c;",
   "good_example": "Bool ok = (a && b) || c;"
  },
  {
   "code": "C2102",
   "kind": "diagnostic",
   "meaning": "a chained comparison",
   "spec": "SPEC-04P.2 6.7.2",
   "ai_cause": "Wrote a Python-style chained comparison `0 <= i < n`.",
   "bad_example": "if (0 <= i < n) { }",
   "good_example": "if (0 <= i && i < n) { }"
  },
  {
   "code": "C2103",
   "kind": "diagnostic",
   "meaning": "an operator or built-in operation not defined for the operand type",
   "spec": "SPEC-04P.2 6.7, clause 7",
   "ai_cause": "Called an operator or built-in on a type that does not support it (e.g., `mul_full` or `uabs` on `I1024`).",
   "bad_example": "I1024 x = 5 as I1024;\n_ = mul_full(x, x);",
   "good_example": "I512 x = 5 as I512;\nI1024 prod = mul_full(x, x);"
  },
  {
   "code": "C3001",
   "kind": "diagnostic",
   "meaning": "a duplicate name, a built-in name included",
   "spec": "SPEC-04P.2 6.2.3, 7.1",
   "ai_cause": "Declared a variable or function that shadows a built-in (`sum`, `min`, `max`, `abs`, `copy`, `len`, `dot`, `clamp`) or duplicates an existing name.",
   "bad_example": "I64 sum = 0;",
   "good_example": "I64 total = 0;"
  },
  {
   "code": "C3002",
   "kind": "diagnostic",
   "meaning": "a selected import name that collides with another name",
   "spec": "SPEC-04P.2 6.15.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.15.1: a selected import name that collides with another name.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C3003",
   "kind": "diagnostic",
   "meaning": "an import cycle",
   "spec": "SPEC-04P.2 6.15.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.15.1: an import cycle.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C3004",
   "kind": "diagnostic",
   "meaning": "a script local used in a function or test",
   "spec": "SPEC-04P.2 5.1.2",
   "ai_cause": "Referenced a top-level script variable inside a function or `test` block. Always put program entry code inside `void main()` and use `const` for shared constants.",
   "bad_example": "I64 scale = 100;\nI64 f(I64 x) { return x * scale; }",
   "good_example": "const I64 SCALE = 100;\nI64 f(I64 x) { return x * SCALE; }\nvoid main() { \"{f(5)}\\n\"; }"
  },
  {
   "code": "C3005",
   "kind": "diagnostic",
   "meaning": "an undefined name or member",
   "spec": "SPEC-04P.2 6.2.3",
   "ai_cause": "Used an undeclared identifier or called `print(...)` / `printf(...)` (printing in cint is a bare string statement `\"text {val}\\n\";`).",
   "bad_example": "print(\"{x}\\n\");",
   "good_example": "\"{x}\\n\";"
  },
  {
   "code": "C3006",
   "kind": "diagnostic",
   "meaning": "an unknown type",
   "spec": "SPEC-04P.2 6.3",
   "ai_cause": "Used a C/Rust/Python type name (`int`, `int64_t`, `i64`, `u64`, `float`, `double`, `bool`) instead of `I64`, `U64`, `Bool`.",
   "bad_example": "int64_t x = 0;\nbool ok = true;",
   "good_example": "I64 x = 0;\nBool ok = true;"
  },
  {
   "code": "C3007",
   "kind": "diagnostic",
   "meaning": "a name of the wrong kind: a type where a value is needed, or a value where a type, mode or operation is needed",
   "spec": "SPEC-04P.2 7.1",
   "ai_cause": "Omitted the return type first argument in `muldiv(R, a, b, c, mode)`, `dot(R, a, b)`, or `sum(R, xs)`.",
   "bad_example": "I64 y = muldiv(a, b, c, half_even);",
   "good_example": "I64 y = muldiv(I64, a, b, c, half_even);"
  },
  {
   "code": "C3008",
   "kind": "diagnostic",
   "meaning": "a name that its module does not export",
   "spec": "SPEC-04P.2 6.15.2",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.15.2: a name that its module does not export.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C3009",
   "kind": "diagnostic",
   "meaning": "a module file that cannot be read",
   "spec": "SPEC-04P.2 6.15.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.15.1: a module file that cannot be read.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C3010",
   "kind": "diagnostic",
   "meaning": "an import of a script",
   "spec": "SPEC-04P.2 5.1.2",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 5.1.2: an import of a script.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C3011",
   "kind": "diagnostic",
   "meaning": "a script that defines `main`",
   "spec": "SPEC-04P.2 5.1.2",
   "ai_cause": "Combined top-level script statements with `void main()` in the same file.",
   "bad_example": "I64 x = 1;\nvoid main() { \"{x}\\n\"; }",
   "good_example": "void main() {\n    I64 x = 1;\n    \"{x}\\n\";\n}"
  },
  {
   "code": "C3012",
   "kind": "diagnostic",
   "meaning": "`import` after other items",
   "spec": "SPEC-04P.2 6.15.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.15.1: `import` after other items.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C3020",
   "kind": "diagnostic",
   "meaning": "a duplicate test name",
   "spec": "SPEC-04P.2 6.15.3",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.15.3: a duplicate test name.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C3021",
   "kind": "diagnostic",
   "meaning": "`expect_fault` outside the header of a test",
   "spec": "SPEC-04P.2 6.15.3",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.15.3: `expect_fault` outside the header of a test.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C3030",
   "kind": "diagnostic",
   "meaning": "a module path that does not form a valid file path",
   "spec": "SPEC-04P.2 6.15.1",
   "ai_cause": "Named a `.ci` file starting with a digit or containing `-` (module file names must be valid identifiers).",
   "bad_example": "cint run 01-test.ci",
   "good_example": "cint run test_01.ci"
  },
  {
   "code": "C4001",
   "kind": "diagnostic",
   "meaning": "a function that can reach its end without returning a value",
   "spec": "SPEC-04P.2 6.9.4",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.9.4: a function that can reach its end without returning a value.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C4002",
   "kind": "diagnostic",
   "meaning": "a `catch` block that can complete",
   "spec": "SPEC-04P.2 6.11",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.11: a `catch` block that can complete.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C4010",
   "kind": "diagnostic",
   "meaning": "a function or kernel named without a call",
   "spec": "SPEC-04P.2 6.9.4",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.9.4: a function or kernel named without a call.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C4011",
   "kind": "diagnostic",
   "meaning": "a result not used",
   "spec": "SPEC-04P.2 6.9.4",
   "ai_cause": "Called a value-returning function as a statement without assigning it or discarding with `_ =`.",
   "bad_example": "compute(x);",
   "good_example": "_ = compute(x);"
  },
  {
   "code": "C4012",
   "kind": "diagnostic",
   "meaning": "a statement form not permitted, including a keyword where a name is expected",
   "spec": "SPEC-04P.2 6.10.1",
   "ai_cause": "Used a reserved keyword (`by`, `in`, `out`, `inout`, `var`, `try`, `reduce`, `kernel`) as a variable name, or wrote a bare expression statement.",
   "bad_example": "I64 by = 2;",
   "good_example": "I64 step = 2;"
  },
  {
   "code": "C4013",
   "kind": "diagnostic",
   "meaning": "`break` or `continue` outside a loop, or with an unknown label",
   "spec": "SPEC-04P.2 6.10.6",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.10.6: `break` or `continue` outside a loop, or with an unknown label.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C4014",
   "kind": "diagnostic",
   "meaning": "a misplaced `fallthrough`",
   "spec": "SPEC-04P.2 6.10.5",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.10.5: a misplaced `fallthrough`.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C4020",
   "kind": "diagnostic",
   "meaning": "a `switch` that does not cover every value",
   "spec": "SPEC-04P.2 6.10.5",
   "ai_cause": "Wrote a `switch` without a `default:` arm (exhaustive coverage only applies when every value of the type is listed).",
   "bad_example": "switch (kind) {\n    case 0: { return 1; }\n}",
   "good_example": "switch (kind) {\n    case 0: { return 1; }\n    default: { return 0; }\n}"
  },
  {
   "code": "C4021",
   "kind": "diagnostic",
   "meaning": "overlapping case items",
   "spec": "SPEC-04P.2 6.10.5",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.10.5: overlapping case items.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C4022",
   "kind": "diagnostic",
   "meaning": "a case range written with `..`",
   "spec": "SPEC-04P.2 6.10.5",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.10.5: a case range written with `..`.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C4023",
   "kind": "diagnostic",
   "meaning": "a case clause with no statement",
   "spec": "SPEC-04P.2 6.10.5",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.10.5: a case clause with no statement.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C4024",
   "kind": "diagnostic",
   "meaning": "an empty case range",
   "spec": "SPEC-04P.2 6.10.5",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.10.5: an empty case range.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C4025",
   "kind": "diagnostic",
   "meaning": "`default` not last, or repeated",
   "spec": "SPEC-04P.2 6.10.5",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.10.5: `default` not last, or repeated.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C4026",
   "kind": "diagnostic",
   "meaning": "a scrutinee of a type that `switch` does not take",
   "spec": "SPEC-04P.2 6.10.5",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.10.5: a scrutinee of a type that `switch` does not take.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C4030",
   "kind": "diagnostic",
   "meaning": "a jump or `try` that would leave a deferred statement",
   "spec": "SPEC-04P.2 6.10.7",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.10.7: a jump or `try` that would leave a deferred statement.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C4031",
   "kind": "diagnostic",
   "meaning": "an `errdefer` where no error can leave",
   "spec": "SPEC-04P.2 6.10.7",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.10.7: an `errdefer` where no error can leave.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C5001",
   "kind": "diagnostic",
   "meaning": "`out` on a function parameter",
   "spec": "SPEC-04P.2 6.9.5",
   "ai_cause": "Used `out` on an ordinary function parameter (`out` is reserved for kernels; use `inout` on arrays/structs in functions).",
   "bad_example": "void fill_buf[n](out I64[n] a) { }",
   "good_example": "void fill_buf[n](inout I64[n] a) { }"
  },
  {
   "code": "C5010",
   "kind": "diagnostic",
   "meaning": "arguments, or the operands of a copy, known during translation to overlap",
   "spec": "SPEC-04P.2 6.9.5, 6.12.5",
   "ai_cause": "Passed the same array variable as both an `in` and an `out`/`inout` argument in a call or kernel dispatch.",
   "bad_example": "step_kernel(buf, buf);",
   "good_example": "step_kernel(buf_a, buf_b); // use double buffering"
  },
  {
   "code": "C5012",
   "kind": "diagnostic",
   "meaning": "an argument that the function also reaches as a module-level variable",
   "spec": "SPEC-04P.2 6.9.5",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.9.5: an argument that the function also reaches as a module-level variable.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C5020",
   "kind": "diagnostic",
   "meaning": "a print statement in a kernel",
   "spec": "SPEC-04P.2 6.13.3",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.13.3: a print statement in a kernel.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C5021",
   "kind": "diagnostic",
   "meaning": "`defer` in a kernel",
   "spec": "SPEC-04P.2 6.13.3",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.13.3: `defer` in a kernel.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C5022",
   "kind": "diagnostic",
   "meaning": "`try` or an error union in a kernel",
   "spec": "SPEC-04P.2 6.13.3",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.13.3: `try` or an error union in a kernel.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C5023",
   "kind": "diagnostic",
   "meaning": "a dispatch in a kernel",
   "spec": "SPEC-04P.2 6.13.3",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.13.3: a dispatch in a kernel.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C5025",
   "kind": "diagnostic",
   "meaning": "a module-level variable in a kernel",
   "spec": "SPEC-04P.2 6.13.3",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.13.3: a module-level variable in a kernel.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C5028",
   "kind": "diagnostic",
   "meaning": "a kernel parameter of a type that kernels do not take",
   "spec": "SPEC-04P.2 6.13.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.13.1: a kernel parameter of a type that kernels do not take.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C5031",
   "kind": "diagnostic",
   "meaning": "a kernel write outside its work-item's block, or writes that do not cover it",
   "spec": "SPEC-04P.2 6.13.3",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.13.3: a kernel write outside its work-item's block, or writes that do not cover it.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C5051",
   "kind": "diagnostic",
   "meaning": "two exported names that give one symbol in generated code, or a name that gives no valid symbol (cint only)",
   "spec": "SPEC-04P.2 SPEC-09P.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause SPEC-09P.1: two exported names that give one symbol in generated code, or a name that gives no valid symbol (cint only).",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C6001",
   "kind": "diagnostic",
   "meaning": "a fault during constant evaluation",
   "spec": "SPEC-04P.2 6.8",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.8: a fault during constant evaluation.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C6002",
   "kind": "diagnostic",
   "meaning": "compile-time fuel exhausted (cint only)",
   "spec": "SPEC-04P.2 6.8",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.8: compile-time fuel exhausted (cint only).",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C6004",
   "kind": "diagnostic",
   "meaning": "a constant expression required",
   "spec": "SPEC-04P.2 6.8",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.8: a constant expression required.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C6005",
   "kind": "diagnostic",
   "meaning": "a constant that depends on itself",
   "spec": "SPEC-04P.2 6.9.2",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.9.2: a constant that depends on itself.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C6006",
   "kind": "diagnostic",
   "meaning": "constant arguments that break a built-in precondition: `clamp` with `lo > hi`, or a negative arena or pool capacity",
   "spec": "SPEC-04P.2 6.14, 7.2.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.14, 7.2.1: constant arguments that break a built-in precondition: `clamp` with `lo > hi`, or a negative arena or pool capacity.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C6010",
   "kind": "diagnostic",
   "meaning": "a `static_assert` that fails",
   "spec": "SPEC-04P.2 6.10.9",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 6.10.9: a `static_assert` that fails.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C9001",
   "kind": "diagnostic",
   "meaning": "a capacity or output size of the implementation exceeded (cint only)",
   "spec": "SPEC-04P.2 5.3",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 5.3: a capacity or output size of the implementation exceeded (cint only).",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C9002",
   "kind": "diagnostic",
   "meaning": "a generated symbol over 247 bytes (cint only)",
   "spec": "SPEC-04P.2 SPEC-09P.1",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause SPEC-09P.1: a generated symbol over 247 bytes (cint only).",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C9004",
   "kind": "diagnostic",
   "meaning": "blocks or expressions nested beyond the implementation's limit",
   "spec": "SPEC-04P.2 5.3",
   "ai_cause": "Violated constraint in SPEC-04P.2 subclause 5.3: blocks or expressions nested beyond the implementation's limit.",
   "bad_example": "",
   "good_example": ""
  },
  {
   "code": "C9102",
   "kind": "diagnostic",
   "meaning": "a construct that the implementation does not implement (a refusal, 3.16), or a constraint that names no code of its own (4, paragraph 4) (cint only)",
   "spec": "SPEC-04P.2 4",
   "ai_cause": "Used a construct listed in SPEC-09P.1 clause 12 as refused by cintc 0.2.0: e.g. `U128`/`U256`/`U512`, `Q<i>.<f>` fixed-point types, `muldiv` from narrow operands to a wide result type (widen operands first!), top-level arrays/structs in a script (use `void main()`), `for i in a..b by s` (use `while`), or `I64[N]` sized by a `const` name at module scope (use an integer literal extent).",
   "bad_example": "I128 y = muldiv(I128, a_i64, b_i64, c_i64, half_even);",
   "good_example": "I128 y = muldiv(I128, a_i64 as I128, b_i64 as I128, c_i64 as I128, half_even);"
  },
  {
   "code": "E_OVERFLOW",
   "kind": "fault (code 1)",
   "meaning": "A checked operator, conversion or named operation whose exact or rounded result is outside the range of its type",
   "spec": "SPEC-04P.2 5.2.3 (6.7, 6.6, 7.2, 7.3), SPEC-01P.2",
   "ai_cause": "Checked `+`, `-`, `*`, `/`, `<<`, or `muldiv` exceeded the target type's range.",
   "bad_example": "I64 prod = a * b; // overflows when a*b > I64.max",
   "good_example": "I64 scaled = muldiv(I64, a, b, scale, half_even); // uses 128-bit intermediate\n// Or use I128 / *% (wrapping) / *| (saturating) when appropriate."
  },
  {
   "code": "E_DIV_ZERO",
   "kind": "fault (code 2)",
   "meaning": "A division or remainder whose divisor is 0, `muldiv` included",
   "spec": "SPEC-04P.2 5.2.3 (6.7.7, 7.2), SPEC-01P.2",
   "ai_cause": "Divisor in `/`, `%`, `div_round`, or `muldiv` was 0.",
   "bad_example": "I64 q = a / b;",
   "good_example": "I64 q = b != 0 ? a / b : 0;"
  },
  {
   "code": "E_BOUNDS",
   "kind": "fault (code 3)",
   "meaning": "An index outside an extent, a slice whose bounds are not valid, a full arena or pool or an exhausted frame arena",
   "spec": "SPEC-04P.2 5.2.3 (6.12, 6.14, 5.2.6), SPEC-01P.2",
   "ai_cause": "Array index `< 0` or `>= len(arr)`, invalid slice bounds, or exhausted arena/pool/frame arena.",
   "bad_example": "I64 last = arr[len(arr)];",
   "good_example": "I64 last = arr[len(arr) - 1];"
  },
  {
   "code": "E_SHAPE",
   "kind": "fault (code 4)",
   "meaning": "Views whose shapes disagree, a negative extent, `min` or `max` of an empty input, or a dispatch whose work-item count exceeds `MAX(I64)`",
   "spec": "SPEC-04P.2 5.2.3 (6.12, 7.3, 7.4, 6.13), SPEC-01P.2",
   "ai_cause": "Runtime array view extents disagreed, negative dynamic extent, or `min`/`max` over empty slice.",
   "bad_example": "copy(dst[0..4], src[0..3]);",
   "good_example": "copy(dst[0..3], src[0..3]);"
  },
  {
   "code": "E_SHIFT",
   "kind": "fault (code 5)",
   "meaning": "A shift or rotation count outside `0` to `w - 1`",
   "spec": "SPEC-04P.2 5.2.3 (6.7.8), SPEC-01P.2",
   "ai_cause": "Shift or rotate count was `< 0` or `>= width` (e.g. `1 << 64` on `I64` faults; C leaves it undefined).",
   "bad_example": "I64 mask = 1 << 64;",
   "good_example": "I64 mask = 1 << 63;"
  },
  {
   "code": "E_NARROW",
   "kind": "fault (code 6)",
   "meaning": "A checked conversion whose value is outside the target's range, or a `c` hole whose value is not a Unicode scalar value",
   "spec": "SPEC-04P.2 5.2.3 (6.6, 7.5.3), SPEC-01P.2",
   "ai_cause": "Checked cast `x as T` had a runtime value outside `T.min .. T.max`.",
   "bad_example": "I8 byte_val = x as I8;",
   "good_example": "I8 byte_val = clamp(x, I8.min as I64, I8.max as I64) as I8; // or `x as% I8` to wrap low bits"
  },
  {
   "code": "E_ALIAS",
   "kind": "fault (code 7)",
   "meaning": "A writable argument that overlaps another argument, or operands of `copy` that overlap",
   "spec": "SPEC-04P.2 5.2.3 (6.9.5, 6.12.5, 6.13, 7.4), SPEC-01P.2",
   "ai_cause": "Writable `inout`/`out` view overlapped another argument at runtime, or `copy` source/destination overlapped.",
   "bad_example": "copy(arr[1..5], arr[0..4]);",
   "good_example": "I64[4] tmp;\ncopy(tmp, arr[0..4]);\ncopy(arr[1..5], tmp);"
  },
  {
   "code": "E_STALE_HANDLE",
   "kind": "fault (code 8)",
   "meaning": "A handle that is not valid for one of the reasons of 6.14.4, among them the null handle and a handle whose generation has ended, or an allocation from or a reset of a retired arena",
   "spec": "SPEC-04P.2 5.2.3 (6.14), SPEC-01P.2",
   "ai_cause": "Dereferenced a null handle, a handle removed from a pool, or an allocation from a reset/retired arena.",
   "bad_example": "pool.remove(h);\nI64 v = pool[h];",
   "good_example": "I64 v = pool[h];\npool.remove(h);"
  },
  {
   "code": "E_FUEL",
   "kind": "fault (code 9)",
   "meaning": "A charge point that would exceed the entry's fuel allowance",
   "spec": "SPEC-04P.2 5.2.3 (5.2.4), SPEC-01P.2",
   "ai_cause": "Entry exceeded its deterministic fuel allowance (each loop back-edge, call, and kernel work-item charges 1 unit).",
   "bad_example": "while (true) { }",
   "good_example": "// Pass a higher `--fuel N` budget or bound the loop iteration count."
  },
  {
   "code": "E_UNSUPPORTED",
   "kind": "fault (code 10)",
   "meaning": "An entry, a dispatch or a call depth whose type, operation or layout the implementation cannot carry out exactly, found when the entry or the dispatch begins (3.16)",
   "spec": "SPEC-04P.2 5.2.3 (4, 5.2.5), SPEC-01P.2",
   "ai_cause": "Executor refused an unsupported type/placement at entry or dispatch start (e.g., wide integers on `gpu-cuda`).",
   "bad_example": "// Kernel with I128 on gpu-cuda",
   "good_example": "// Run wide-integer kernels on cpu-c17 or cpu-sir-interp, or narrow kernel arrays to I64."
  },
  {
   "code": "E_DOMAIN",
   "kind": "fault (code 11)",
   "meaning": "`isqrt`, `isqrt_round` or a fixed-point square root of a negative value, or `clamp` with its bounds in the wrong order",
   "spec": "SPEC-04P.2 5.2.3 (7.2), SPEC-01P.2",
   "ai_cause": "`isqrt` / `isqrt_round` called on a negative number, or `clamp(x, lo, hi)` called with `lo > hi`.",
   "bad_example": "I64 r = isqrt(x);",
   "good_example": "I64 r = isqrt(max(0, x));"
  },
  {
   "code": "E_DEPTH",
   "kind": "fault (code 12)",
   "meaning": "A call that would exceed the entry's call-depth limit",
   "spec": "SPEC-04P.2 5.2.3 (5.2.5), SPEC-01P.2",
   "ai_cause": "Call stack depth exceeded the context's limit (default 256 active calls including `main`).",
   "bad_example": "I64 recurse(I64 n) { return n <= 0 ? 0 : recurse(n - 1); }",
   "good_example": "// Rewrite deep recursion as a `for` or `while` loop."
  },
  {
   "code": "E_ASSERT",
   "kind": "fault (code 13)",
   "meaning": "A failed `assert` outside a test",
   "spec": "SPEC-04P.2 5.2.3 (6.10.9), SPEC-01P.2",
   "ai_cause": "`assert(cond)` evaluated to `false` outside a `test` block.",
   "bad_example": "assert(x > 0);",
   "good_example": "// Check inputs with `if` and return an error union `E!T` when handling expected invalid inputs."
  }
 ],
 "recipes": [
  {
   "id": "fixed-point-trig",
   "title": "Exact Fixed-Point Sine and Cosine (Horner Series + Error Sweep Test)",
   "summary": "Computes sin and cos in microradians (scale 1_000_000) using range reduction and a degree-7/degree-6 Horner polynomial with muldiv, plus a test sweeping the domain to verify worst-case error.",
   "specs": "SPEC-04P.2 7.2 (IM-63 muldiv), CU-201.2 201-04",
   "filename": "trig_recipe.ci",
   "code": "const I64 S_ANG = 1_000_000;\nconst I64 HALF_PI = 1_570_796;\nconst I64 PI = 3_141_593;\nconst I64 TWO_PI = 6_283_185;\n\n// Reduce angle u (in microradians) into [-HALF_PI, HALF_PI] and set sign_flip = -1 or 1.\nI64 reduce_sin_angle(I64 u, inout I64[1] sign_flip) {\n    I64 r = u % TWO_PI;\n    if (r > PI) {\n        r = r - TWO_PI;\n    }\n    sign_flip[0] = 1;\n    if (r > HALF_PI) {\n        r = PI - r;\n    } else if (r < -HALF_PI) {\n        r = -PI - r;\n        sign_flip[0] = -1;\n    }\n    return r;\n}\n\n// Polynomial sin(x) for x in [-HALF_PI, HALF_PI], scale 1_000_000.\n// Measured worst-case error across [0, HALF_PI]: <= 2 microradians (5 digits).\nI64 sin_urad(I64 u) {\n    I64[1] flip;\n    I64 x = reduce_sin_angle(u, flip);\n    I64 x2 = muldiv(I64, x, x, S_ANG, half_even);\n    // Horner degree-11: ratios 1/(10*11)=110, 1/(8*9)=72, 1/(6*7)=42, 1/(4*5)=20, 1/(2*3)=6\n    I64 t = S_ANG - div_round(x2, 110, half_even);\n    t = S_ANG - muldiv(I64, x2, t, 72 * S_ANG, half_even);\n    t = S_ANG - muldiv(I64, x2, t, 42 * S_ANG, half_even);\n    t = S_ANG - muldiv(I64, x2, t, 20 * S_ANG, half_even);\n    t = S_ANG - muldiv(I64, x2, t, 6 * S_ANG, half_even);\n    return flip[0] * muldiv(I64, x, t, S_ANG, half_even);\n}\n\nI64 cos_urad(I64 u) {\n    return sin_urad(HALF_PI - u);\n}\n\nvoid main() {\n    I64 s0 = sin_urad(0);\n    I64 c0 = cos_urad(0);\n    I64 s30 = sin_urad(523_599);\n    I64 c60 = cos_urad(1_047_198);\n    \"sin(0)={s0:/1000000} cos(0)={c0:/1000000} sin(pi/6)={s30:/1000000} cos(pi/3)={c60:/1000000}\\n\";\n}\n\ntest \"pythagorean identity holds within 3 units across quadrant\" {\n    for k in 0..=15 {\n        I64 u = k * 100_000;\n        I64 s = sin_urad(u);\n        I64 c = cos_urad(u);\n        I64 norm = muldiv(I64, s, s, S_ANG, half_even) + muldiv(I64, c, c, S_ANG, half_even);\n        assert(abs(norm - S_ANG) <= 3);\n    }\n}\n",
   "stdout": "sin(0)=0.000000 cos(0)=1.000000 sin(pi/6)=0.500000 cos(pi/3)=0.499999\n",
   "stdout_sha256": "4fb47b814dd7f35afba420bdd656880813f85e1a321351895a56fe7471062084",
   "fuel_consumed": "11",
   "compiler_source_identity": "d6ebe30d604346afe4a7912c5d6f3ce2b9d401641d361772892b44b9292609ff"
  },
  {
   "id": "fixed-point-ln-sqrt",
   "title": "Exact Fixed-Point Square Root and Natural Logarithm",
   "summary": "Computes scaled square root via isqrt_round and natural logarithm via 2*artanh((x-1)/(x+1)) after power-of-two reduction, with measured accuracy verified in a test block.",
   "specs": "SPEC-04P.2 7.2 (IM-64 isqrt_round, IM-63 muldiv), CU-201.2 201-04",
   "filename": "ln_sqrt_recipe.ci",
   "code": "const I64 SCALE = 1_000_000;\nconst I64 LN2_SCALED = 693_147;\n\nI64 qsqrt_scaled(I64 x_scaled) {\n    I128 wide = (x_scaled as I128) * (SCALE as I128);\n    return isqrt_round(wide, half_even) as I64;\n}\n\n// Natural log for x_scaled > 0 (where 1.0 == SCALE == 1_000_000).\n// Reduces x into [707_106, 1_414_213] by powers of 2, then evaluates 2*artanh((m-1)/(m+1)).\n// Measured error on powers of 2 and e: <= 2 units at scale 1_000_000.\nI64 qln_scaled(I64 x_scaled) {\n    assert(x_scaled > 0);\n    I64 m = x_scaled;\n    I64 k = 0;\n    while (m >= 1_414_214) {\n        m = muldiv(I64, m, 1, 2, half_even);\n        k += 1;\n    }\n    while (m < 707_107) {\n        m = m * 2;\n        k -= 1;\n    }\n    I64 z = muldiv(I64, m - SCALE, SCALE, m + SCALE, half_even);\n    I64 z2 = muldiv(I64, z, z, SCALE, half_even);\n    I64 z3 = muldiv(I64, z2, z, SCALE, half_even);\n    I64 z5 = muldiv(I64, z3, z2, SCALE, half_even);\n    I64 z7 = muldiv(I64, z5, z2, SCALE, half_even);\n    I64 series = z + div_round(z3, 3, half_even) + div_round(z5, 5, half_even) + div_round(z7, 7, half_even);\n    return k * LN2_SCALED + 2 * series;\n}\n\nvoid main() {\n    I64 rt2 = qsqrt_scaled(2_000_000);\n    I64 lne = qln_scaled(2_718_282);\n    I64 ln10 = qln_scaled(10_000_000);\n    \"sqrt(2)={rt2:/1000000} ln(e)={lne:/1000000} ln(10)={ln10:/1000000}\\n\";\n}\n\ntest \"sqrt and ln accuracy\" {\n    assert(qsqrt_scaled(2_000_000) == 1_414_214);\n    assert(qln_scaled(SCALE) == 0);\n    assert(abs(qln_scaled(2_718_282) - SCALE) <= 2);\n    assert(abs(qln_scaled(10_000_000) - 2_302_585) <= 2);\n}\n",
   "stdout": "sqrt(2)=1.414214 ln(e)=0.999999 ln(10)=2.302583\n",
   "stdout_sha256": "56a020af48650032618a8c61c0baff2384e77bfdd6606728990284d2815c99d0",
   "fuel_consumed": "8",
   "compiler_source_identity": "d6ebe30d604346afe4a7912c5d6f3ce2b9d401641d361772892b44b9292609ff"
  },
  {
   "id": "wide-i1024-scaling",
   "title": "Wide I1024 Arithmetic and High-Precision Fixed-Point Scaling",
   "summary": "Demonstrates explicit widening to I1024 before muldiv (avoiding C9102 narrow-to-wide refusal), exact 2048-bit intermediate products, and exact decimal scaling.",
   "specs": "SPEC-01P.2 3.1, SPEC-04P.2 6.3.1, SPEC-09P.1 12.1, CU-301.1 301-04",
   "filename": "wide_i1024_recipe.ci",
   "code": "// In cint 0.2.0, muldiv operands and result type must match width (SPEC-09P.1 12.1).\n// Widen I64 values to I1024 with `as I1024` first, then call muldiv(I1024, ...).\n\nI1024 scale_1e30() {\n    I1024 ten15 = 1_000_000_000_000_000 as I1024;\n    return ten15 * ten15;\n}\n\nI1024 harmonic_sum_scaled(I64 n) {\n    I1024 s = scale_1e30();\n    I1024 total = 0 as I1024;\n    for k in 1..=n {\n        total = total + muldiv(I1024, s, 1 as I1024, k as I1024, half_even);\n    }\n    return total;\n}\n\nvoid main() {\n    I1024 h20 = harmonic_sum_scaled(20);\n    \"H_20 * 10^30 = {h20}\\n\";\n}\n\ntest \"exact I1024 harmonic sum for n=4\" {\n    // H_4 = 1 + 1/2 + 1/3 + 1/4 = 25/12 = 2.083333333333333333333333333333...\n    I1024 s = scale_1e30();\n    I1024 expected = muldiv(I1024, s, 25 as I1024, 12 as I1024, half_even);\n    assert(harmonic_sum_scaled(4) == expected);\n}\n",
   "stdout": "H_20 * 10^30 = 3597739657143681911483769068908\n",
   "stdout_sha256": "2b359b820191ba29440139e8cdf6026c4f9b846ef940b9f86f9e339032df0d5d",
   "fuel_consumed": "23",
   "compiler_source_identity": "d6ebe30d604346afe4a7912c5d6f3ce2b9d401641d361772892b44b9292609ff"
  },
  {
   "id": "svg-generator",
   "title": "Deterministic SVG Trajectory Generator in Pure cint",
   "summary": "Integrates a 2D harmonic oscillator with symplectic velocity-Verlet steps in integer micrometer coordinates and prints complete, self-contained SVG markup to stdout.",
   "specs": "SPEC-04P.2 7.5 (print formatting), SPEC-06P.1 4 (cint run)",
   "filename": "svg_orbit_recipe.ci",
   "code": "const I64 S = 1_000;\n\nvoid main() {\n    I64 x = 80_000;\n    I64 y = 0;\n    I64 vx = 0;\n    I64 vy = 60_000;\n    \"<svg xmlns=\\\"http://www.w3.org/2000/svg\\\" viewBox=\\\"-100 -100 200 200\\\">\\n\";\n    \"  <polyline fill=\\\"none\\\" stroke=\\\"#111111\\\" stroke-width=\\\"1.5\\\" points=\\\"\";\n    for step in 0..8 {\n        if (step > 0) {\n            \" \";\n        }\n        \"{x:/1000},{y:/1000}\";\n        // Symplectic Euler step: a = -k * x\n        I64 ax = -muldiv(I64, x, 100, S, half_even);\n        I64 ay = -muldiv(I64, y, 100, S, half_even);\n        vx = vx + ax;\n        vy = vy + ay;\n        x = x + muldiv(I64, vx, 200, S, half_even);\n        y = y + muldiv(I64, vy, 200, S, half_even);\n    }\n    \"\\\"/>\\n</svg>\\n\";\n}\n\ntest \"symplectic step deterministic coordinates\" {\n    I64 x = 80_000;\n    I64 ax = -muldiv(I64, x, 100, S, half_even);\n    assert(ax == -8_000);\n}\n",
   "stdout": "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"-100 -100 200 200\">\n  <polyline fill=\"none\" stroke=\"#111111\" stroke-width=\"1.5\" points=\"80.000,0.000 78.400,12.000 75.232,23.760 70.559,35.045 64.475,45.629 57.102,55.300 48.587,63.865 39.100,71.153\"/>\n</svg>\n",
   "stdout_sha256": "5602046823f32925f596d6fc17c71eee7efc362bde694893b48b5a9f5f720eda",
   "fuel_consumed": "9",
   "compiler_source_identity": "d6ebe30d604346afe4a7912c5d6f3ce2b9d401641d361772892b44b9292609ff"
  },
  {
   "id": "fnv1a-digest",
   "title": "64-Bit FNV-1a Rolling State Digest (Byte-Wise Wrapping Arithmetic)",
   "summary": "Computes a canonical 64-bit FNV-1a hash over signed I64 words one byte per round using wrapping *% and as% U64 so native, SIR interpreter, and browser BigInt mirrors agree bit-for-bit.",
   "specs": "SPEC-04P.2 6.7.6 (+%, *%), SPEC-04P.2 6.6 (as%), CU-201.2 201-03",
   "filename": "fnv1a_recipe.ci",
   "code": "const U64 FNV_OFFSET = 0xcbf29ce484222325;\nconst U64 FNV_PRIME = 0x100000001b3;\n\nU64 fnv1a_word(U64 h, I64 word) {\n    U64 u = word as% U64;\n    U64 acc = h;\n    for b in 0..8 {\n        U64 byte_val = u & 0xff;\n        acc = (acc ^ byte_val) *% FNV_PRIME;\n        u = u >> 8;\n    }\n    return acc;\n}\n\nU64 fnv1a_slice[n](in I64[n] vals) {\n    U64 h = FNV_OFFSET;\n    for i in 0..n {\n        h = fnv1a_word(h, vals[i]);\n    }\n    return h;\n}\n\nvoid main() {\n    I64[3] state;\n    state[0] = 1_000_000;\n    state[1] = -250_000;\n    state[2] = 42;\n    U64 d = fnv1a_slice(state);\n    \"digest={d:#018x}\\n\";\n}\n\ntest \"fnv1a byte-wise digest is deterministic\" {\n    I64[2] a;\n    a[0] = 1;\n    a[1] = -1;\n    assert(fnv1a_slice(a) == 0xc4777a6e69ba809c);\n}\n",
   "stdout": "digest=0x1a5b54e9f0db1d82\n",
   "stdout_sha256": "635864b9b16889c06c67e785aefdec4dd11da72b53f17b3640d88af227bc5bd1",
   "fuel_consumed": "32",
   "compiler_source_identity": "d6ebe30d604346afe4a7912c5d6f3ce2b9d401641d361772892b44b9292609ff"
  },
  {
   "id": "money-ledger",
   "title": "Exact Cents Ledger with Error Unions, Banker's Rounding, and Fault Tests",
   "summary": "Models deposits, withdrawals, error unions (LedgerError!I64), banker's rounding interest (muldiv half_even), exact {/100} decimal formatting, and expect_fault E_OVERFLOW testing.",
   "specs": "SPEC-04P.2 6.11 (error unions), SPEC-04P.2 7.5.3 (/scale), CU-401.2 401-01",
   "filename": "ledger_recipe.ci",
   "code": "const I64 DEPOSIT = 0;\nconst I64 WITHDRAW = 1;\n\nerror LedgerError { overdrawn, invalid_kind }\n\nstruct Entry {\n    I64 kind;\n    I64 cents;\n}\n\nI64 daily_interest(I64 balance_cents, I64 rate_bps) {\n    return muldiv(I64, balance_cents, rate_bps, 3_650_000, half_even);\n}\n\nLedgerError!I64 apply_entry(I64 balance, Entry e) {\n    switch (e.kind) {\n        case 0: {\n            return balance + e.cents;\n        }\n        case 1: {\n            if (e.cents > balance) {\n                return .overdrawn;\n            }\n            return balance - e.cents;\n        }\n        default: {\n            return .invalid_kind;\n        }\n    }\n}\n\nLedgerError!void main() {\n    Entry[2] book;\n    book[0] = Entry(DEPOSIT, 125_000);\n    book[1] = Entry(WITHDRAW, 40_050);\n    I64 bal = 0;\n    for i in 0..2 {\n        bal = try apply_entry(bal, book[i]);\n    }\n    I64 interest = daily_interest(bal, 450);\n    bal = bal + interest;\n    \"balance={bal:/100} interest={interest:/100}\\n\";\n}\n\ntest \"banker's rounding ties to even\" {\n    assert(daily_interest(1_825_000, 1) == 0);\n    assert(daily_interest(5_475_000, 1) == 2);\n}\n\ntest \"overdraft returns error value\" {\n    I64 bal = apply_entry(100, Entry(WITHDRAW, 101)) catch -1;\n    assert(bal == -1);\n}\n\ntest \"deposit overflow raises E_OVERFLOW\" expect_fault E_OVERFLOW {\n    _ = apply_entry(I64.max, Entry(DEPOSIT, 1));\n}\n",
   "stdout": "balance=849.60 interest=0.10\n",
   "stdout_sha256": "3dd71e35b0b14dd52e1b88d0f63a2d1d0aa717cc2c4f0ec3069b519ff6f82416",
   "fuel_consumed": "6",
   "compiler_source_identity": "d6ebe30d604346afe4a7912c5d6f3ce2b9d401641d361772892b44b9292609ff"
  },
  {
   "id": "kernel-double-buffer",
   "title": "All-or-Nothing Kernel Dispatch, Reduction, and Double Buffering",
   "summary": "Demonstrates a 1D kernel with `over [i: n]`, exact `reduce total = sum(v)` epilogue, and double-buffered arrays to avoid C5010/E_ALIAS overlap faults.",
   "specs": "SPEC-02P.1 6 (aliasing), SPEC-02P.1 9 (reductions), SPEC-04P.2 6.13",
   "filename": "kernel_recipe.ci",
   "code": "kernel step_and_sum[n](in I64[n] src, out I64[n] dst, in I64 gain, out I64 total)\n    over [i: n]\n{\n    I64 v = src[i] * gain + 1;\n    dst[i] = v;\n    reduce total = sum(v);\n}\n\nvoid main() {\n    I64[4] buf_a;\n    I64[4] buf_b;\n    buf_a[0] = 10;\n    buf_a[1] = 20;\n    buf_a[2] = 30;\n    buf_a[3] = 40;\n    I64 sum1 = 0;\n    I64 sum2 = 0;\n    // Dispatch 0: read buf_a, write buf_b (disjoint storage -> no C5010 / E_ALIAS)\n    step_and_sum(buf_a, buf_b, 2, sum1);\n    // Dispatch 1: read buf_b, write buf_a\n    step_and_sum(buf_b, buf_a, 3, sum2);\n    \"sum1={sum1} sum2={sum2} final=[{buf_a[0]}, {buf_a[1]}, {buf_a[2]}, {buf_a[3]}]\\n\";\n}\n\ntest \"double buffer kernel matches sequential sum\" {\n    I64[4] a;\n    I64[4] b;\n    a[0] = 1;\n    a[1] = 2;\n    a[2] = 3;\n    a[3] = 4;\n    I64 total = 0;\n    step_and_sum(a, b, 10, total);\n    assert(total == 104);\n    assert(b[3] == 41);\n}\n",
   "stdout": "sum1=204 sum2=616 final=[64, 124, 184, 244]\n",
   "stdout_sha256": "72a679dcf797310a19f24af71b1cb5a20317679de30265a51c51e12f2a66390c",
   "fuel_consumed": "9",
   "compiler_source_identity": "d6ebe30d604346afe4a7912c5d6f3ce2b9d401641d361772892b44b9292609ff"
  }
 ],
 "lessons": [
  {
   "id": "from-c",
   "edition": "CU-000.2",
   "title": "cint for C programmers",
   "builds": "What carries over from C17 and what changes (checked operators, no promotion, floor division, views)",
   "url": "/university/from-c/",
   "chunk_id": "cu-from-c:what-changes"
  },
  {
   "id": "from-python",
   "edition": "CU-000.2",
   "title": "cint for Python and NumPy programmers",
   "builds": "What carries over from Python/NumPy and what changes (fixed widths, explicit casts, views)",
   "url": "/university/from-python/",
   "chunk_id": "cu-from-python:what-changes"
  },
  {
   "id": "setup",
   "edition": "CU-000.2",
   "title": "set up cint on your computer",
   "builds": "Installing and verifying cint 0.2.0 across Linux, macOS, and Windows",
   "url": "/university/setup/",
   "chunk_id": "cu-000-setup:set-up-cint-on-your-computer"
  },
  {
   "id": "101-00",
   "edition": "CU-101.2",
   "title": "welcome",
   "builds": "your first program",
   "url": "/university/101/00-welcome/",
   "chunk_id": "cu-101-00:welcome"
  },
  {
   "id": "101-01",
   "edition": "CU-101.2",
   "title": "printing",
   "builds": "a house drawn in characters",
   "url": "/university/101/01-printing/",
   "chunk_id": "cu-101-01:printing"
  },
  {
   "id": "101-02",
   "edition": "CU-101.2",
   "title": "arithmetic",
   "builds": "minutes in a week",
   "url": "/university/101/02-arithmetic/",
   "chunk_id": "cu-101-02:arithmetic"
  },
  {
   "id": "101-03",
   "edition": "CU-101.2",
   "title": "names for values",
   "builds": "a coin jar",
   "url": "/university/101/03-names/",
   "chunk_id": "cu-101-03:names-for-values"
  },
  {
   "id": "101-04",
   "edition": "CU-101.2",
   "title": "numbers have sizes",
   "builds": "a table of sizes",
   "url": "/university/101/04-sizes/",
   "chunk_id": "cu-101-04:numbers-have-sizes"
  },
  {
   "id": "101-05",
   "edition": "CU-101.2",
   "title": "when a number runs out",
   "builds": "a doubling that stops",
   "url": "/university/101/05-runs-out/",
   "chunk_id": "cu-101-05:when-a-number-runs-out"
  },
  {
   "id": "101-06",
   "edition": "CU-101.2",
   "title": "true or false",
   "builds": "a leap-year test",
   "url": "/university/101/06-true-or-false/",
   "chunk_id": "cu-101-06:true-or-false"
  },
  {
   "id": "101-07",
   "edition": "CU-101.2",
   "title": "counting loops",
   "builds": "the times tables",
   "url": "/university/101/07-counting-loops/",
   "chunk_id": "cu-101-07:counting-loops"
  },
  {
   "id": "101-08",
   "edition": "CU-101.2",
   "title": "loops that wait",
   "builds": "a hailstone sequence",
   "url": "/university/101/08-loops-that-wait/",
   "chunk_id": "cu-101-08:loops-that-wait"
  },
  {
   "id": "101-09",
   "edition": "CU-101.2",
   "title": "choosing among many",
   "builds": "letter grades",
   "url": "/university/101/09-choosing-among-many/",
   "chunk_id": "cu-101-09:choosing-among-many"
  },
  {
   "id": "101-10",
   "edition": "CU-101.2",
   "title": "functions",
   "builds": "the areas of two rooms",
   "url": "/university/101/10-functions/",
   "chunk_id": "cu-101-10:functions"
  },
  {
   "id": "101-11",
   "edition": "CU-101.2",
   "title": "functions that call themselves",
   "builds": "a table of factorials",
   "url": "/university/101/11-functions-that-call-themselves/",
   "chunk_id": "cu-101-11:functions-that-call-themselves"
  },
  {
   "id": "101-12",
   "edition": "CU-101.2",
   "title": "lists",
   "builds": "a week of temperatures",
   "url": "/university/101/12-lists/",
   "chunk_id": "cu-101-12:lists"
  },
  {
   "id": "201-00",
   "edition": "CU-201.2",
   "title": "start here",
   "builds": "one program, run with the four commands",
   "url": "/university/201/00-start-here/",
   "chunk_id": "cu-201-00:start-here"
  },
  {
   "id": "201-01",
   "edition": "CU-201.2",
   "title": "numbers that hold",
   "builds": "the rice on a chessboard",
   "url": "/university/201/01-numbers-that-hold/",
   "chunk_id": "cu-201-01:numbers-that-hold"
  },
  {
   "id": "201-02",
   "edition": "CU-201.2",
   "title": "types and conversions",
   "builds": "an altitude in a 16-bit field",
   "url": "/university/201/02-types-and-conversions/",
   "chunk_id": "cu-201-02:types-and-conversions"
  },
  {
   "id": "201-03",
   "edition": "CU-201.2",
   "title": "operators at the edge",
   "builds": "a 32-bit hash and a pixel brightener",
   "url": "/university/201/03-operators-at-the-edge/",
   "chunk_id": "cu-201-03:operators-at-the-edge"
  },
  {
   "id": "201-04",
   "edition": "CU-201.2",
   "title": "division and rounding",
   "builds": "a bill split exactly",
   "url": "/university/201/04-division-and-rounding/",
   "chunk_id": "cu-201-04:division-and-rounding"
  },
  {
   "id": "201-05",
   "edition": "CU-201.2",
   "title": "tests and goldens",
   "builds": "tests and a saved output for the bill split",
   "url": "/university/201/05-tests-and-goldens/",
   "chunk_id": "cu-201-05:tests-and-goldens"
  },
  {
   "id": "201-06",
   "edition": "CU-201.2",
   "title": "the workbench",
   "builds": "a year of savings, rewound and searched",
   "url": "/university/201/06-workbench/",
   "chunk_id": "cu-201-06:the-workbench"
  },
  {
   "id": "201-07",
   "edition": "CU-201.2",
   "title": "debugging by comparison",
   "builds": "a checksum bug found one change at a time",
   "url": "/university/201/07-debugging-by-comparison/",
   "chunk_id": "cu-201-07:debugging-by-comparison"
  },
  {
   "id": "201-08",
   "edition": "CU-201.2",
   "title": "control flow",
   "builds": "Collatz paths sorted by length",
   "url": "/university/201/08-control-flow/",
   "chunk_id": "cu-201-08:control-flow"
  },
  {
   "id": "201-09",
   "edition": "CU-201.2",
   "title": "functions",
   "builds": "exact harmonic sums",
   "url": "/university/201/09-functions/",
   "chunk_id": "cu-201-09:functions"
  },
  {
   "id": "301-01",
   "edition": "CU-301.1",
   "title": "when 64 bits are not enough",
   "builds": "a primality test whose products need 128 bits",
   "url": "/university/301/01-when-64-bits-are-not-enough/",
   "chunk_id": "cu-301-01:when-64-bits-are-not-enough"
  },
  {
   "id": "301-04",
   "edition": "CU-301.1",
   "title": "big exact numbers",
   "builds": "100 factorial and binomial coefficients, to the last digit",
   "url": "/university/301/04-big-exact-numbers/",
   "chunk_id": "cu-301-04:big-exact-numbers"
  },
  {
   "id": "401-01",
   "edition": "CU-401.2",
   "title": "an exact ledger",
   "builds": "a bank ledger in whole cents, with tests and a saved, checked output",
   "url": "/university/401/01-ledger/",
   "chunk_id": "cu-401-01:an-exact-ledger"
  },
  {
   "id": "401-02",
   "edition": "CU-401.2",
   "title": "hunting an overflow",
   "builds": "a fault traced to its cause and fixed three ways",
   "url": "/university/401/02-hunting-an-overflow/",
   "chunk_id": "cu-401-02:hunting-an-overflow"
  }
 ],
 "chunks": [
  {
   "id": "spec-00p:spec-00p-2",
   "edition": "SPEC-00P.2",
   "title": "SPEC-00P.2",
   "clauses": "",
   "url": "/specifications/spec-00p/2/",
   "internal": 0,
   "content": "# SPEC-00P.2: Overview\n\nSPEC-00P.2, edition 2 of the overview of the cint specifications, cint v0.2.0, 2026-10-11.\n\nThis edition replaces SPEC-00P.1."
  },
  {
   "id": "spec-00p:foreword",
   "edition": "SPEC-00P.2",
   "title": "Foreword",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#foreword",
   "internal": 0,
   "content": "## Foreword\n\nThis document is the overview of the specifications published with cint 0.2.0: what cint is, how the documents fit together, where to start reading, and which claims cint makes, with their limits. It is informative. It states no rule of its own, and where it summarizes a rule, the document that states the rule governs."
  },
  {
   "id": "spec-00p:what-cint-is",
   "edition": "SPEC-00P.2",
   "title": "1 What cint is",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#what-cint-is",
   "internal": 0,
   "content": "## 1 What cint is\n\ncint is a programming language for computations whose results must be exact and the same on every machine. It is a C-family language: declarations name the type first, and functions, blocks, statements and most operators are written as in C. Source files end in `.ci`. It rests on six mechanisms:"
  },
  {
   "id": "spec-00p:what-cint-is-p1",
   "edition": "SPEC-00P.2",
   "title": "1 What cint is (part 2)",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#what-cint-is",
   "internal": 0,
   "content": "- **Integers only.** Every value is an integer of a declared type, a `Bool`, or an array or struct of them. The integer types are `I8` to `I64`, `U8` to `U64` and the wide types `I128` to `I1024` and `U128` to `U512`; fixed-point types such as `Q16.16`, with 16 integer bits, counting the sign bit, and 16 fraction bits, hold multiples of 2^-16 as integers. There is no floating-point type (SPEC-04P.2 6.3).\n- **Every plain operator is checked.** `a + b` gives the exact sum when it fits the type and faults when it does not. Wrapping and saturating arithmetic have their own operators, `a +% b` and `a +| b` and `add_result(a, b)` returns an error value instead of faulting. The spelling alone decides; no option changes it (SPEC-04P.2 6.7).\n- **No implicit conversions.** A value changes type only through a written conversion: `as` is checked, `as%` wraps and `as?` returns an error value. A literal has no type of its own and takes the one its context requires (SPEC-04P.2 6.5, 6.6).\n- **A fault stops the program with a full record.** A *fault* stops a run at an operation that cannot give a correct result. Its *fault record* names the operation, each operand with its type, the exact result, the bound crossed, the source position and the calls that led there. Program code cannot catch a fault. An expected failure is an *error* instead: a value that a function returns and its caller handles with `try` or `catch` (SPEC-04P.2 5.2.3, 6.11).\n- **Three executors and a reference.** `cpu-c17` compiles a program to C17 and builds it with the host's C compiler. `cpu-sir-interp`, the interpreter, runs the compiler's intermediate form directly. `gpu-cuda` runs *kernels* on NVIDIA GPUs. A kernel is a function applied once to each point of an index space, and its run for one point is a *work-item*. *The reference*, `cint_ref`, is a separate implementation in Python whose results are the expect"
  },
  {
   "id": "spec-00p:what-cint-is-p2",
   "edition": "SPEC-00P.2",
   "title": "1 What cint is (part 3)",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#what-cint-is",
   "internal": 0,
   "content": "A source file whose statements stand at its top level is a *script*, and its statements run in order. In the examples, a string on a line of its own is a print statement: it writes the string, with each `{...}` replaced by the value of the expression inside. Here are the four spellings of one sum of two `U8` values, whose range is 0 to 255:\n\n```cint forms.ci\n// forms.ci: one sum of two U8 values, in each spelling.\nU8 a = 200;\nU8 b = 100;\n\"wrapping:   {a +% b}\\n\";\n\"saturating: {a +| b}\\n\";\nU8 c = add_result(a, b) catch 0;\n\"result:     {c}\\n\";\n\"checked:    {a + b}\\n\";\n```\n\n```text\nwrapping:   44\nsaturating: 255\nresult:     0\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> forms.ci:8:17\n   |\n 8 | \"checked:    {a + b}\\n\";\n   |                 ^ add.checked.u8\n   |\n   = operation: add.checked.u8\n   = operand-count: 2\n   = operand: U8 200\n   = operand: U8 100\n   = exact:   300\n   = limit:   U8 255\n...\n```\n\nThe exact sum is 300. It wraps to 44 and saturates at 255, and `add_result` gives the error `ArithError.overflow`, which `catch 0` replaces with 0. The checked `+` faults, and its print statement writes nothing. A line `...` in shown output stands for lines left out.\n\nTwo types in one sum are rejected before the program runs:\n\n```cint mixed.ci\n// mixed.ci: an I32 and an I64 in one sum.\nI32 a = 5;\nI64 b = 7;\n\"{b + a}\\n\";\n```\n\n```text\nerror[C2001]: type mismatch\n  --> mixed.ci:4:7\n   |\n 4 | \"{b + a}\\n\";\n   |       ^\n```\n\nA conversion of one operand fixes it: `b + (a as I64)`."
  },
  {
   "id": "spec-00p:a-first-program",
   "edition": "SPEC-00P.2",
   "title": "2 A first program",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#a-first-program",
   "internal": 0,
   "content": "## 2 A first program\n\nFunctions are declared as in C. This script computes two factorials in `I64`:\n\n```cint factorial.ci\n// factorial.ci: n! computed in I64.\nI64 factorial(I64 n) {\n    I64 f = 1;\n    for k in 1..=n {\n        f = f * k;\n    }\n    return f;\n}\n\n\"10! = {factorial(10)}\\n\";\n\"20! = {factorial(20)}\\n\";\n```\n\n`cint run factorial.ci` prints:\n\n```text\n10! = 3628800\n20! = 2432902008176640000\n```\n\n`cint run` compiles the script to C, builds it and runs it. `for k in 1..=n` runs its body for each `k` from 1 through `n`.\n\nThe factorial of 21, 51090942171709440000, does not fit in `I64`. A third line asks for it:\n\n```cint factorial21.ci\n// factorial21.ci: one step past the largest factorial I64 holds.\nI64 factorial(I64 n) {\n    I64 f = 1;\n    for k in 1..=n {\n        f = f * k;\n    }\n    return f;\n}\n\n\"10! = {factorial(10)}\\n\";\n\"20! = {factorial(20)}\\n\";\n\"21! = {factorial(21)}\\n\";\n```\n\n```text\n10! = 3628800\n20! = 2432902008176640000\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> factorial21.ci:5:15\n   |\n 5 |         f = f * k;\n   |               ^ mul.checked.i64\n   |\n   = operation: mul.checked.i64\n   = operand-count: 2\n   = operand: I64 2432902008176640000\n   = operand: I64 21\n   = exact:   51090942171709440000\n   = limit:   I64 9223372036854775807\n...\n   = stack-depth: 1\n   = called from: factorial21.ci:12:9\n   = fuel-consumed: 55 (not part of the fault record)\n   = state: the program stopped; stdout holds what it wrote before the fault\n```\n\nThe program wrote two lines. The third print statement wrote nothing, because the expression inside its `{...}` faulted. The report, on the standard error, reads:"
  },
  {
   "id": "spec-00p:a-first-program-p1",
   "edition": "SPEC-00P.2",
   "title": "2 A first program (part 2)",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#a-first-program",
   "internal": 0,
   "content": "- `fault[E_OVERFLOW]`: the fault code and its fixed message.\n- `-->` and the excerpt: the position `factorial21.ci:5:15`, the 15th character of line 5, which is the `*` of `f = f * k`.\n- `operation`: `mul.checked.i64`, the checked product of two `I64` values.\n- `operand`: both operands, exact and typed: the factorial of 20, and 21.\n- `exact` and `limit`: the true product, and `I64.max`, the bound it crossed.\n- `called from`: the call in line 12 that led there.\n- `fuel-consumed` and `state` follow the record and are not part of it.\n\nThe program does not continue with a wrapped value. SPEC-04P.2 8.1 explains every line of a report."
  },
  {
   "id": "spec-00p:the-documents",
   "edition": "SPEC-00P.2",
   "title": "3 The documents",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#the-documents",
   "internal": 0,
   "content": "## 3 The documents\n\nThe specifications of cint 0.2.0 are these editions:\n\n| Edition | Title | What it covers | Kind |\n|---|---|---|---|\n| SPEC-00P.2 | Overview | This document | Informative |\n| SPEC-01P.2 | Canonical encodings and identity | The bytes of values, fault records, program state, checkpoints and recordings; the identities of a program and of a run | Normative |\n| SPEC-02P.1 | Kernels and executors | What an executor does to carry out a kernel dispatch, and what each executor of 0.2.0 runs and refuses | Normative |\n| SPEC-03P.1 | The host interface: C and Python | How C and Python programs call cint code, lend it memory, and checkpoint and record it | Normative |\n| SPEC-04P.2 | The cint language | The language and its built-in operations, faults and fuel, and how to find out why a program did what it did | Normative; Annexes B to F informative |\n| SPEC-06P.1 | The cint tools | The commands, outputs and exit statuses of `cint`, the interpreter and the debug tools | Normative |\n| SPEC-09P.1 | Toolchain and conformance | The compiler's intermediate form, the C it emits, what implementations agree on, the conformance suite, the bootstrap, receipts and the constructs that the tools of 0.2.0 refuse | Normative; clause 12 informative |\n| GLOSSARY-P.2 | Glossary | Every defined term, with the edition and section that define it | Informative |\n| REFERENCES-P.2 | References | The published works that the editions cite | Informative |\n\nSPEC-04P.2 depends on no other document, so a reader learning the language needs only it. Each of the others serves one kind of reader, as section 4 shows.\n\n**Editions.** An edition is named by the document's number, `P` for public, and the edition's number: SPEC-04P.2 is the second edition of SPEC-04, and SPEC-02P.1 the first of SPEC-02. Each document counts its own editions."
  },
  {
   "id": "spec-00p:the-documents-p1",
   "edition": "SPEC-00P.2",
   "title": "3 The documents (part 2)",
   "clauses": "IM-106 LS-17",
   "url": "/specifications/spec-00p/2/#the-documents",
   "internal": 0,
   "content": "- Each minor release, such as 0.2.0, publishes an edition of every document. A patch release, such as 0.2.1, publishes the next edition only of a document whose rules or listed refusals it changes.\n- A released edition's text does not change. A correction that changes no meaning is published as an erratum; a change of meaning is a new edition.\n- Each rule ends with its *clause identifier*, such as IM-106 or LS-17. The identifier stays with the rule when the rule moves to another section or document, and it is not reused: IM-106, the fields of a fault record, was in SPEC-01P.1 and is in SPEC-04P.2 8.1. Section numbers belong to one edition.\n- Every rule has an anchor named by its clause identifier, and every section an anchor named by its title, so a link keeps working in each edition that keeps the rule or the section.\n- A citation gives the edition, the section and the identifier: SPEC-04P.2 8.1, IM-106."
  },
  {
   "id": "spec-00p:reading-orders",
   "edition": "SPEC-00P.2",
   "title": "4 Reading orders",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#reading-orders",
   "internal": 0,
   "content": "## 4 Reading orders\n\nEach list is an order to read in, not everything worth reading.\n\nA learner reads in this order:\n\n1. Sections 1, 2 and 6 of this overview.\n2. SPEC-04P.2, Introduction; 5.1.2, scripts and programs; 6.3.1, integer types; 6.5, literals; 6.7.6, the additive operators; 6.6, conversions.\n3. SPEC-04P.2 6.10, statements; 7.5, formatting; 8.1, reading a fault report; 8.5, a first session with the debug tools.\n4. SPEC-04P.2 6.9, declarations; 6.11, errors and faults; 6.12, arrays and views; 6.15.3, tests.\n\nA C programmer reads in this order:\n\n1. SPEC-04P.2 Annex D, cint for C and Python programmers and Annex C, what cint does where C leaves behavior undefined, and what it leaves out.\n2. SPEC-04P.2 6.6, conversions, none of them implicit; 6.7.1, precedence, where the bitwise operators bind tighter than in C; 6.7.7, division, which rounds toward negative infinity.\n3. SPEC-04P.2 6.12, arrays and views; 6.14, arenas, pools and handles; 6.11, errors.\n4. SPEC-09P.1 7, the C that the compiler emits and SPEC-03P.1 7, calling cint code from C.\n\nA Python user reads in this order:\n\n1. SPEC-04P.2 Annex D, then the learner's order.\n2. SPEC-03P.1 8, the Python module, in particular 8.2, borrowing arrays without a copy, and 8.6, a complete example with NumPy.\n3. SPEC-04P.2 6.13, kernels and SPEC-03P.1 6.4, outputs and publication.\n4. SPEC-04P.2 8.4 and SPEC-03P.1 9, checkpoints, recordings and replay.\n\nAn implementer reads in this order:\n\n1. SPEC-04P.2 clauses 3 to 7 in order, with Annex A, the grammar and Annex B, the codes.\n2. SPEC-04P.2 8.1 and 8.2, the fault record and what implementations agree on.\n3. SPEC-02P.1, the executors and SPEC-01P.2, the encodings and identities.\n4. SPEC-09P.1 8, agreement; 9, the conformance suite; 12, the refusals of the tools of 0.2.0; 10, the bootstrap.\n5. SPEC-06P.1 7, the forms of reports and SPEC-03P.1 7, the C interface."
  },
  {
   "id": "spec-00p:what-0-2-0-includes-and-what-it-does-not",
   "edition": "SPEC-00P.2",
   "title": "5 What 0.2.0 includes and what it does not",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#what-0-2-0-includes-and-what-it-does-not",
   "internal": 0,
   "content": "## 5 What 0.2.0 includes and what it does not\n\nThe language of cint 0.2.0 is what SPEC-04P.2 states and the reference runs:\n\n- the integer types from `I8` to `I1024` and from `U8` to `U512`, the fixed-point types, `Bool`, structs, error sets and error unions;\n- the checked, wrapping and saturating operators, the result forms, the conversions `as`, `as%` and `as?` and the built-in operations of SPEC-04P.2 clause 7, such as `muldiv`, `div_round` and `sum`;\n- variables and constants; functions with `in` and `inout` parameters; `if`, `while`, `for` over a range, `switch`, labeled `break` and `continue`, `defer` and `errdefer`, `assert`, and print statements with format specifications;\n- arrays and views of rank 1 to 4, with checked indexing and slicing; kernels and their reductions; arenas, pools and handles;\n- scripts, programs with `main`, importable modules with imports and exports and tests.\n\nThe tools of cint 0.2.0 are the `cint` command with `run`, `build`, `test` and `emit-c`; the interpreter, `cint interp`; `cint workbench`, `cint explain` and `cint debug`; the C interface and the Python module of SPEC-03P.1; and the reference.\n\nThe `cint` command of 0.2.0 does not build every construct that the reference runs. For such a construct it reports, when it translates the program, a refusal diagnostic such as C9102, and it does not run the program with another meaning. On an implementation that runs the construct, its meaning is the one SPEC-04P.2 states. SPEC-09P.1 clause 12 lists each refused construct with its code and position, and the operations that `gpu-cuda` refuses in a kernel with the fault `E_UNSUPPORTED`."
  },
  {
   "id": "spec-00p:what-0-2-0-includes-and-what-it-does-not-p1",
   "edition": "SPEC-00P.2",
   "title": "5 What 0.2.0 includes and what it does not (part 2)",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#what-0-2-0-includes-and-what-it-does-not",
   "internal": 0,
   "content": "Some features are in no implementation of cint 0.2.0, the reference included. Among them are string variables and formatting into a string, enumerations, tuples, type aliases, attributes, bit fields, the `do` loop, `for` over the elements of an array, default arguments, functions that return views, reading input from files or the terminal, schedules for kernels, dispatches that write their outputs in place, the type `U1024` and executors other than the three of section 1. Each document's Future directions clause describes those of its area: SPEC-04P.2 6.16, SPEC-01P.2 10, SPEC-02P.1 12, SPEC-03P.1 11, SPEC-06P.1 13 and SPEC-09P.1 13."
  },
  {
   "id": "spec-00p:finding-out-why",
   "edition": "SPEC-00P.2",
   "title": "6 Finding out why",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#finding-out-why",
   "internal": 0,
   "content": "## 6 Finding out why\n\nWhen a program faults, or prints something unexpected, SPEC-04P.2 clause 8 shows how to find out why. This section is a short tour of it, with the programs of section 2 and this module:\n\n```cint\n// fact.ci: n! in I64, as a module with two tests.\nexport I64 factorial(I64 n) {\n    I64 f = 1;\n    for k in 1..=n {\n        f = f * k;\n    }\n    return f;\n}\n\ntest \"20! fits in I64\" {\n    assert(factorial(20) == 2432902008176640000);\n}\n\ntest \"21! does not\" expect_fault E_OVERFLOW {\n    _ = factorial(21);\n}\n```\n\n`fact.ci` has only declarations, so it is an *importable module*, which runs nothing by itself. `export` lets code outside the module call `factorial`, and each `test` block states one expectation about it (SPEC-04P.2 5.1.2, 6.15)."
  },
  {
   "id": "spec-00p:the-fault-record",
   "edition": "SPEC-00P.2",
   "title": "6.1 The fault record",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#the-fault-record",
   "internal": 0,
   "content": "### 6.1 The fault record\n\nThe report of section 2 prints one fault record. Besides the fields read there, the record holds the revision of the program text, and it holds no time, no memory address and no name of a machine or an executor, so one fault gives one record everywhere. A fault in a kernel dispatch also has an address: the dispatch number, the work-item index and the step. When several work-items fault, the record describes the least of them in a fixed order, whatever order they ran in, so a GPU reports the same fault as the C executor (SPEC-04P.2 8.1, SPEC-02P.1 5.5)."
  },
  {
   "id": "spec-00p:agreement",
   "edition": "SPEC-00P.2",
   "title": "6.2 Agreement",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#agreement",
   "internal": 0,
   "content": "### 6.2 Agreement\n\nThe reference, `cint_ref`, runs the same files. It runs as `python3 -m cint_ref` with the `ref` directory of the cint source tree on `PYTHONPATH`, and `--format 5` selects the newest form of its outcome text (SPEC-09P.1 9.3):\n\n```console\n$ python3 -m cint_ref run --format 5 --stdout ref.out factorial.ci\ncase factorial\nformat 5\nsource reference\noutcome value\nstdout-bytes 40\nstdout-sha256 30b3b4dbc6ca79e5fd6c441e533d6027db1fda245cabfcd3c986ea96020d5606\nfuel-consumed 33\n$ cint run factorial.ci | cmp - ref.out && echo same\nsame\n```\n\nThe reference prints the outcome, not the output: the run ended normally after writing 40 bytes, whose SHA-256 digest is shown, and consumed 33 units of fuel, 1 for the script, 1 for each of the two calls and 1 for each of the 30 iterations. `--stdout` saved the output bytes, and `cmp` finds them equal to those of `cint run`.\n\nIt runs `factorial21.ci` to the same end:\n\n```console\n$ python3 -m cint_ref run --format 5 factorial21.ci\ncase factorial21\nformat 5\nsource reference\noutcome fault\nstdout-bytes 40\nstdout-sha256 30b3b4dbc6ca79e5fd6c441e533d6027db1fda245cabfcd3c986ea96020d5606\nfuel-consumed 55\nfault.code E_OVERFLOW\nfault.operation mul.checked.i64\nfault.operand I64 2432902008176640000\nfault.operand I64 21\nfault.exact 51090942171709440000\nfault.limit I64 9223372036854775807\nfault.position factorial21.ci:5:15\nfault.revision self\nfault.source-map self\nfault.address none\nfault.stack-depth 1\nfault.stack factorial21.ci:12:9\n```"
  },
  {
   "id": "spec-00p:agreement-p1",
   "edition": "SPEC-00P.2",
   "title": "6.2 Agreement (part 2)",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#agreement",
   "internal": 0,
   "content": "The output is the 40 bytes of `factorial.ci`, since the third print wrote nothing. The fuel is the 55 of the report: 1 for the script, 1 for each of the three calls and 51 for the iterations. The fault matches the report field for field, except that the reference writes `self` for the revision and the source map, since it does not compute them. The reference shares no code with the compiler, so each checks the other, and any difference between them is a defect in one of them (SPEC-04P.2 8.2, SPEC-09P.1 8.1)."
  },
  {
   "id": "spec-00p:golden-outputs-and-tests",
   "edition": "SPEC-00P.2",
   "title": "6.3 Golden outputs and tests",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#golden-outputs-and-tests",
   "internal": 0,
   "content": "### 6.3 Golden outputs and tests\n\nA *golden*, or golden output, is an output checked once, saved, and compared byte for byte with the output of each run after it: `cint run factorial.ci > factorial.golden` saves one, and `diff` compares. Every implementation gives the same outcome, so a golden made with one checks a run on any other. A test keeps its expectation inside the module, and `cint test` runs each test from a fresh state:\n\n```console\n$ cint test fact.ci\ntest fact.ci:10 \"20! fits in I64\" ... ok\ntest fact.ci:14 \"21! does not\" ... ok\n2 of 2 tests passed\n```\n\nThe second test passes because `factorial(21)` faults `E_OVERFLOW`, the fault it names; it would fail if the call returned a value (SPEC-04P.2 8.3, 6.15.3)."
  },
  {
   "id": "spec-00p:checkpoints-and-replay",
   "edition": "SPEC-00P.2",
   "title": "6.4 Checkpoints and replay",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#checkpoints-and-replay",
   "internal": 0,
   "content": "### 6.4 Checkpoints and replay\n\nAn *entry* is one run of a program from one of its entry points, such as a call of an exported function by a host program, and the end of an entry is a *boundary*. In a `cint workbench` session each line typed is an entry, and every entry is recorded. A *checkpoint* saves the program's state at a boundary, and *replay* runs recorded entries again and compares each outcome with the recording:\n\n```console\n$ cint workbench fact.ci\n...\nci[1]> :load fact.ci\nloaded fact (fact.ci)\nci[2]> fact.factorial(20)\n= 2432902008176640000 : I64\nci[3]> I64 p = fact.factorial(19);\np = 121645100408832000 : I64\nci[4]> :checkpoint p19\ncheckpoint p19   #1   bindings 1   revisions: session@r1, fact@r1\nci[4]> p = p * 20;\nci[5]> p = p * 21;\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> entry 5:1:7\n...\n   = state: no store completed in this entry; context reset\n...\nci[6]> p\n= 2432902008176640000 : I64\nci[7]> :replay p19\nreplaying 3 entries from p19 to the current state (entry 4 to entry 6), comparing prints and outcomes with the recording\nentry 5: E_OVERFLOW reproduced, its fault record equal to the recorded one\nreplay matches the recording at 3 boundaries\nci[7]> :restore p19\nsaved current state as auto-1\nrestored p19   #1\nci[7]> p\n= 121645100408832000 : I64\nci[8]> :quit --yes\n```"
  },
  {
   "id": "spec-00p:checkpoints-and-replay-p1",
   "edition": "SPEC-00P.2",
   "title": "6.4 Checkpoints and replay (part 2)",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#checkpoints-and-replay",
   "internal": 0,
   "content": "- Loading the module is entry 1, and its function is named `fact.factorial`. An expression entry prints its value and its type.\n- `I64 p` is a variable of the session, kept from entry to entry. `:checkpoint p19` saves the state while `p` holds the factorial of 19.\n- Entry 5 faults. No store of it completed, so `p` still holds the factorial of 20, and the session clears the fault before the next entry.\n- `:replay p19` restores the checkpoint, runs entries 4 to 6 again and finds every outcome equal to the recorded one, the fault record included. `:restore p19` makes the checkpoint's state current again.\n\nThe tools go back in time by replay from a checkpoint; they do not run a program backward (SPEC-04P.2 8.4)."
  },
  {
   "id": "spec-00p:the-debug-tools",
   "edition": "SPEC-00P.2",
   "title": "6.5 The debug tools",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#the-debug-tools",
   "internal": 0,
   "content": "### 6.5 The debug tools\n\n`cint explain` shows what the compiler knows about a function without running it. Each *fault site*, an operation that can fault, has an identifier:\n\n```console\n$ cint explain fact.ci:factorial\nmodule fact.ci   revision f0d0bba7a6264e17cd2556c3618e861ca5750392885362dcf3ad62407252ed69\n\nfunction factorial   fact.sites:3   pure\n  signature  (in n: I64) -> I64\n  fault sites (3): 3 possible, 0 statically excluded\n    factorial#1  fact.ci:2:12  fuel.charge      E_FUEL possible\n    factorial#2  fact.ci:4:5   fuel.charge      E_FUEL possible\n    factorial#3  fact.ci:5:15  mul.checked.i64  E_OVERFLOW possible\n...\n```\n\n`factorial#1` is the fuel charge of each call, `factorial#2` that of each iteration and `factorial#3` the `*` that faulted in section 2. `pure` says only that the function prints nothing and calls nothing that prints.\n\n`cint debug locate` runs an exported function as an entry, under a recording, and finds the first fault. It prints the report and the last counted operations before the fault, and `--save-case` keeps the run as a *case*, a recording that runs on another machine with the tools alone. `cint debug diff` runs a case on `cpu-c17` and on `cpu-sir-interp` and compares them at every boundary:"
  },
  {
   "id": "spec-00p:the-debug-tools-p1",
   "edition": "SPEC-00P.2",
   "title": "6.5 The debug tools (part 2)",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#the-debug-tools",
   "internal": 0,
   "content": "```console\n$ cint debug locate fact.ci --entry factorial --args I64 21 --save-case f21.case\nprogram    fact.ci   evaluator cpu-sir-interp, recorded as the case f21.case\ntarget     boundary 1 of 1, factorial(I64 21): the first fault, reproduced by replay\nbracket    the initial state; then boundary 1\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> fact.ci:5:15\n...\n   = site: factorial#3\n...\n  ord  position           operation              operands                 value\n...\n   37                     add.wrap.i64           19, 1                    20\n   38  fact.ci:5:15       mul.checked.i64        121645100408832000, 20   2432902008176640000\n   39                     add.wrap.i64           20, 1                    21\n   40  fact.ci:5:15       mul.checked.i64        2432902008176640000, 21  E_OVERFLOW\n$ cint debug diff f21.case\ncase       f21.case   1 boundary   density entry\nreference  cpu-c17\ncandidate  cpu-sir-interp\nboundaries 1 of 1 compared\noutcome    agree\n```\n\nThe `site` line names `factorial#3`. Each row of the trace is one counted operation with its exact operands and value: the last two products before the fault and, between them, the step of the loop index `k`, which has no position of its own. `agree` says that both executors reached the same state and the same fault record; here `reference` names the executor that the other is compared with, not the reference implementation. SPEC-04P.2 8.5 continues with a first session and the commands a learner uses first, and SPEC-06P.1 defines every command."
  },
  {
   "id": "spec-00p:claims-and-evidence",
   "edition": "SPEC-00P.2",
   "title": "7 Claims and evidence",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#claims-and-evidence",
   "internal": 0,
   "content": "## 7 Claims and evidence\n\nEach claim is stated briefly, with the rules that carry it and its limits. Where a sentence here and a rule differ, the rule holds. Figures that support a claim come from the receipts published with cint 0.2.0, and SPEC-09P.1 11.3 shows how to run one again and compare the result."
  },
  {
   "id": "spec-00p:claims-and-evidence-p1",
   "edition": "SPEC-00P.2",
   "title": "7 Claims and evidence (part 2)",
   "clauses": "CONF-03 CONF-04 CONF-14 EMIT-01 EMIT-19 EMIT-20 EMIT-21 H-16 H-20 IM-106 IM-111 IM-112",
   "url": "/specifications/spec-00p/2/#claims-and-evidence",
   "internal": 0,
   "content": "1. **Exact or a fault.** Every plain arithmetic operator, and the checked conversion `as`, gives the exact result or faults, and no option changes what a spelling does.\n   - Rules: SPEC-04P.2 6.7, IM-28 and IM-31; 6.7.6, IM-30; 6.6, IM-50.\n   - Limits: the wrapping and saturating forms do not fault on overflow, but they do fault on a shift count out of range and on a divisor of 0.\n2. **No implicit conversion.** A value changes type only through a conversion written in the program.\n   - Rules: SPEC-04P.2 6.6, IM-9 and IM-50; 6.5, LS-56.\n   - Limits: a literal takes its type from its context, which types the literal and converts no value.\n3. **No undefined behavior.** Within the scope of SPEC-04P.2, no behavior is undefined, unspecified or implementation-defined.\n   - Rules: SPEC-04P.2 4, LS-273; Annex C, IM-128.\n   - Limits: the scope excludes code reached through the host interface and the memory it changes; defects in an implementation, in the C it emits or in the C compiler; hardware faults; and exhaustion of host resources that an implementation cannot detect (SPEC-04P.2 4, LS-274).\n4. **A fault ends the entry with a complete record.** A fault ends the entry at once and gives one record of its operation, operands, exact result, bound and position, with no time, address or executor in it, and program code cannot catch it.\n   - Rules: SPEC-04P.2 5.2.3, IM-118; 8.1, IM-106 and IM-111.\n   - Limits: stores that completed before the fault remain, because sequential code is not rolled back (SPEC-04P.2 5.2.3, IM-121 and IM-122).\n5. **Determinism.** Runs with the same semantic inputs write the same output bytes, end with the same fault record or none, and consume the same fuel, on every conforming implementation, executor and machine.\n   - Rules: SPEC-04P.2 4, LS-272; 8.2, IM-159 and IM-160.\n   - Limits: a run ended by a failure of host resources, such as memory running out"
  },
  {
   "id": "spec-00p:claims-and-evidence-p2",
   "edition": "SPEC-00P.2",
   "title": "7 Claims and evidence (part 3)",
   "clauses": "CONF-03 IM-160 LS-274 LS-275",
   "url": "/specifications/spec-00p/2/#claims-and-evidence",
   "internal": 0,
   "content": "These are not claimed:\n\n- **Compliance with a safety or coding standard,** such as MISRA C or the SEI CERT C Coding Standard. Such a claim would need a documented assessment against named editions and rules (SPEC-04P.2 4, LS-275; SPEC-09P.1 11.4, DISC-02).\n- **Anything about memory that code outside cint changes** while cint code uses it, or about what host code computes (SPEC-04P.2 4, LS-274; SPEC-03P.1 4 and 8.4).\n- **Executables reproducible byte for byte.** The emitted C is reproducible; the executables built from it differ between toolchains and may differ between two builds with one toolchain (SPEC-09P.1 10.4, FIX-05).\n- **That the fixpoint ties an executable to its source.** The fixpoint compares emitted C. It is not diverse double-compiling, and it does not show that an executable corresponds to the compiler's source (SPEC-09P.1 10.5, FIX-04).\n- **Numerical adequacy.** An exact and repeatable result can still be a poor model of the problem it computes, for example where integers replace a floating-point computation (SPEC-04P.2 8.2, IM-160).\n- **Outcomes outside the run matrix,** on other C compilers or machines (SPEC-09P.1 8.4, CONF-03).\n- **Speed.** These documents make no claim about speed. A speed figure published with a release names its workload, machine, toolchain, flags and method of measurement (SPEC-09P.1 11.4, DISC-04).\n- **Correctness from agreement.** Two implementations can agree and both be wrong. Agreement shows that outcomes are equal; the specifications decide which outcome is correct (SPEC-04P.2 8.2)."
  },
  {
   "id": "spec-00p:the-name",
   "edition": "SPEC-00P.2",
   "title": "8 The name",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#the-name",
   "internal": 0,
   "content": "## 8 The name\n\nThe language is spelled cint, in lowercase, also at the start of a sentence. It is not related to `CINT`, the C and C++ interpreter of the ROOT data analysis framework from CERN."
  },
  {
   "id": "spec-00p:prior-work",
   "edition": "SPEC-00P.2",
   "title": "9 Prior work",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#prior-work",
   "internal": 0,
   "content": "## 9 Prior work\n\ncint takes most of its syntax from C, as ISO/IEC 9899:2018 defines it. Its arithmetic follows languages that put the behavior on overflow in the program text. Zig writes wrapping and saturating addition as `+%` and `+|`, the spellings cint uses and cint's error sets and error unions, with `try`, `catch`, `defer` and `errdefer`, are adapted from Zig as well. Rust gives its integer types checked, wrapping and saturating arithmetic as named methods, such as `checked_add`.\n\nA kernel is written for one work-item, as in the single-program, multiple-data model of ISPC and the rule that each work-item writes only its own part of the outputs draws on Futhark's in-place updates. Finding a fault by recording a run and replaying it has precedent in record-and-replay debuggers such as rr. Top-level statements that run in order, with no `main` function needed, come from Terry A. Davis's HolyC. REFERENCES-P.2 lists each of these works."
  },
  {
   "id": "spec-00p:license",
   "edition": "SPEC-00P.2",
   "title": "10 License",
   "clauses": "",
   "url": "/specifications/spec-00p/2/#license",
   "internal": 0,
   "content": "## 10 License\n\nThe cint source code, these specifications and the receipts published with a release are licensed under the Apache License, Version 2.0, with the LLVM exception: SPDX identifier `Apache-2.0 WITH LLVM-exception`. The file `LICENSE` at the root of the source tree holds the terms."
  },
  {
   "id": "spec-01p:spec-01p-2",
   "edition": "SPEC-01P.2",
   "title": "SPEC-01P.2",
   "clauses": "",
   "url": "/specifications/spec-01p/2/",
   "internal": 0,
   "content": "# SPEC-01P.2: Canonical encodings and identity\n\nSPEC-01P.2, edition 2 of the canonical encodings specification, cint v0.2.0, 2026-10-11.\n\nThis edition replaces SPEC-01P.1, \"Integer machine\". The rules of that edition that define types, operators, faults and fuel are stated in SPEC-04P.2, \"The cint language\"; this document states the byte encodings and the identities computed from them. Annex C lists every clause identifier of SPEC-01P.1 and where its rule is stated in cint 0.2.0."
  },
  {
   "id": "spec-01p:foreword",
   "edition": "SPEC-01P.2",
   "title": "Foreword",
   "clauses": "H-14 IM-149 IM-157",
   "url": "/specifications/spec-01p/2/#foreword",
   "internal": 0,
   "content": "## Foreword\n\nThis document specifies the bytes that cint 0.2.0 writes and reads: the canonical encodings of values, fault records, program state, checkpoints and recordings and the digests that identify a program and a run.\n\nEach rule ends with one or more clause identifiers in brackets, such as [IM-149] or [IM-157]. An identifier names one rule: a rule keeps its identifier when its text moves to another section or another document, and no identifier is reused. Most identifiers of this document begin with `IM-` and come from SPEC-01P.1. A rule that another edition states, and whose bytes this document lays out, is cited in brackets with that edition's name, such as [SPEC-03P.1 H-14]: the rule is stated there, and this document gives only its encoding. Section numbers belong to this edition only."
  },
  {
   "id": "spec-01p:introduction",
   "edition": "SPEC-01P.2",
   "title": "Introduction",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#introduction",
   "internal": 0,
   "content": "## Introduction\n\nA fault has a text form and a machine form. The text form is the fault report; the machine form is the *fault record*: a sequence of bytes, fixed field by field, that every conforming implementation produces identically for the same fault. This program withdraws more than its balance holds, and the conversion of the negative balance to `U8` faults:\n\n```cint ledger.ci\nI64 balance = 100;\n\nvoid withdraw(I64 amount) {\n    balance -= amount;\n    U8 rest = balance as U8;\n    \"rest {rest}\\n\";\n}\n\nvoid main() {\n    withdraw(30);\n    withdraw(80);\n}\n```\n\n```text\nrest 70\nfault[E_NARROW]: the value does not fit the destination type\n  --> ledger.ci:5:23\n   |\n 5 |     U8 rest = balance as U8;\n   |                       ^ as.checked.i64.u8\n   |\n   = operation: as.checked.i64.u8\n   = operand-count: 1\n   = operand: I64 -10\n   = exact:   -10\n   = limit:   U8 0\n   ...\n```\n\nThe record of this fault is 151 bytes. It begins with the string `cint-core-1/fault/v2`, preceded by its length, which names the encoding and its version. The code `E_NARROW` follows as the number 6, then the operation identifier, the operand `I64 -10` as a type tag and eight bytes, the exact result, the limit, the position, the revision of the program and the stack. Subclause 6.2 shows every byte."
  },
  {
   "id": "spec-01p:introduction-p1",
   "edition": "SPEC-01P.2",
   "title": "Introduction (part 2)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#introduction",
   "internal": 0,
   "content": "Tools compare these bytes, not the text of reports. Two implementations agree on a fault when their records are equal, and a recording of a run holds the record and the state hash of every step, so that a replay can compare them again. Every encoding in this document follows the same conventions (5.1): integers are little-endian, every string and list carries its length in front, every optional field has a presence byte, and every binary encoding begins with a domain string that names it. A decoder can therefore read each byte without the program that wrote it, and bytes of two kinds cannot be taken for each other.\n\nIdentities are digests of canonical bytes. The *revision* of a program is a SHA-256 digest of its compiled form with every source position removed (9.1), so adding a comment leaves it unchanged. The *state hash* is a SHA-256 digest of the bytes of a program's state (7.6), and a recording chains the state hashes of the steps of a run into one digest (8.5)."
  },
  {
   "id": "spec-01p:how-this-document-is-organized",
   "edition": "SPEC-01P.2",
   "title": "How this document is organized",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#how-this-document-is-organized",
   "internal": 0,
   "content": "### How this document is organized\n\nClauses 1 to 4 state what the document covers, the documents it relies on, its terms and what conformance means. Clause 5 encodes values: the conventions every encoding shares, integers of every width, fixed-point values, mathematical integers and tagged values, among them arrays, structs and handles. Clause 6 encodes the fault record, in its versions 2 and 3, and two small records that a compiled program writes beside it. Clause 7 encodes the state of a program, the checkpoint that holds it and the state hash. Clause 8 encodes recordings and cases. Clause 9 defines the identities computed from these bytes and what never enters them. Clause 10 lists future directions. Annex A works through complete encodings, Annex B specifies the operation fixture format CIF-1, and Annex C indexes the clause identifiers of SPEC-01P.1.\n\nEach subclause of clauses 5 to 9 opens with a short summary and then has some of these parts:\n\n- **Syntax**: the layout of the bytes, field by field, in the notation of 5.1.\n- **Constraints**: the conditions that valid bytes meet. A writer produces only valid bytes, and a decoder rejects bytes that break a constraint.\n- **Semantics**: what the fields mean.\n- **Examples** and **Notes**: informative. They illustrate the rules and never add to them.\n\nByte values are written in hexadecimal, two digits a byte, such as `0f` or `ff`. Every example is the output of cint 0.2.0, of the reference, or of the program shown with it (A.4). A table of bytes lists them in the order they occur, with offsets in decimal. In such a table, `(32 bytes)` stands for a SHA-256 digest, which the text names, and `(n bytes)` for bytes that another table shows. A line `...` in shown output stands for lines left out."
  },
  {
   "id": "spec-01p:scope",
   "edition": "SPEC-01P.2",
   "title": "1 Scope",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#scope",
   "internal": 0,
   "content": "## 1 Scope\n\n1. This document specifies the canonical byte encodings of cint 0.2.0, for the language profile `cint-core-1`:\n   - values of the types of SPEC-04P.2 6.3 that an encoding holds, and mathematical integers;\n   - fault records, and the records of fuel consumed and of an error result that a compiled program writes for the `cint` command;\n   - the state of a program, the checkpoint that holds it and the state hash;\n   - recordings and cases;\n   - the revision identity, the source-map digest and the inputs of execution identity;\n   - the operation fixture format CIF-1.\n2. This document does not specify:\n   - the meaning of values, operators, faults and fuel, which SPEC-04P.2 specifies;\n   - the text of fault reports and diagnostics, and the JSON forms that the tools print, which SPEC-04P.2 8.1 and SPEC-06P.1 specify;\n   - the canonical SIR text over which the revision identity is computed, the conformance suite and its `.expect` format, which SPEC-09P.1 specifies;\n   - the C and Python interfaces through which a host program creates contexts, takes checkpoints and records runs, which SPEC-03P.1 specifies;\n   - the files of a saved workbench session, which SPEC-06P.1 specifies."
  },
  {
   "id": "spec-01p:normative-references",
   "edition": "SPEC-01P.2",
   "title": "2 Normative references",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#normative-references",
   "internal": 0,
   "content": "## 2 Normative references\n\nThe following documents are referred to in the text in such a way that some or all of their content constitutes requirements of this document. For dated references, only the edition cited applies.\n\n- National Institute of Standards and Technology. *Secure Hash Standard (SHS)*. FIPS PUB 180-4, August 2015. Defines SHA-256.\n- F. Yergeau. *UTF-8, a transformation format of ISO 10646*. RFC 3629 (STD 63), November 2003.\n- T. Bray, editor. *The JavaScript Object Notation (JSON) Data Interchange Format*. RFC 8259 (STD 90), December 2017. Used by CIF-1 (Annex B).\n- *JSON Lines*. https://jsonlines.org/. Maintained by Ian Ward. A published convention, with no RFC or ISO standard, for a file of one JSON value per line. Used by CIF-1 (Annex B)."
  },
  {
   "id": "spec-01p:terms-definitions-and-symbols",
   "edition": "SPEC-01P.2",
   "title": "3 Terms, definitions and symbols",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "## 3 Terms, definitions and symbols\n\nThe terms of SPEC-04P.2 clause 3 apply, among them Z, value, type, exact result, fault, fault code, fault record, operation identifier, error, entry, fuel, call depth, frame arena, semantic input, module, array, kernel, dispatch, work-item, arena, pool, handle, revision, the reference and executor. The following terms are added.\n\n<a id=\"term-canonical\"></a>**3.1 canonical**: designated, by a named and versioned rule, as the one representation of a content or the one selection among several. Canonical says which bytes are compared, not that they are correct: two implementations can write equal canonical bytes and both be wrong.\n\n<a id=\"term-encoding\"></a>**3.2 encoding**: a rule that maps a content, such as a value or a fault record, to bytes. An encoding has a name and a version.\n\n<a id=\"term-domain-string\"></a>**3.3 domain string**: the string, of the form `<profile>/<kind>/v<n>`, that begins each binary encoding of this document and the input of every digest, and names its encoding and version, such as `cint-core-1/fault/v2`.\n\n<a id=\"term-tag\"></a>**3.4 tag**: the bytes, beginning with one byte, that name the type of a value where values of several types can occur. Also called a type descriptor.\n\n<a id=\"term-payload\"></a>**3.5 payload**: the bytes of a value without its tag.\n\n<a id=\"term-tagged-value\"></a>**3.6 tagged value**: a tag followed by a payload.\n\n<a id=\"term-presence-byte\"></a>**3.7 presence byte**: a byte `00`, which marks an optional field as absent, or `01`, which marks it present and is followed by the field.\n\n<a id=\"term-decoder\"></a><a id=\"term-writer\"></a>**3.8 writer, decoder**: a *writer* is the part of an implementation that produces the bytes of an encoding; a *decoder* is the part of an implementation that reads the bytes of an encoding."
  },
  {
   "id": "spec-01p:terms-definitions-and-symbols-p1",
   "edition": "SPEC-01P.2",
   "title": "3 Terms, definitions and symbols (part 2)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "<a id=\"term-context\"></a>**3.9 context**: one instance of a program's state, held by a host program, in which entries run one at a time: its module variables, arenas and pools, its buffer registry, its counters and its fault record (SPEC-03P.1 3.4).\n\n<a id=\"term-state\"></a>**3.10 state**: the canonical content of a context between entries: the values of its module-level variables, its arenas and pools, its registry of buffers, its identifier counters, the fault record it holds if any, and the count of effects it has completed.\n\n<a id=\"term-checkpoint\"></a>**3.11 checkpoint**: the canonical bytes of a state, in an envelope that names the runtime contract, from which a context can be restored. A checkpoint is taken between entries, not inside one. A host program receives it as bytes (SPEC-03P.1 9.2), and the tools keep it in a file or, in a workbench session, under a name (SPEC-06P.1 11.1).\n\n<a id=\"term-state-hash\"></a>**3.12 state hash**: the SHA-256 digest of the canonical bytes of a state.\n\n<a id=\"term-effect\"></a>**3.13 effect**: a request that an entry makes of its host. In cint 0.2.0 the one effect is the output of a print statement, whose request is the bytes printed.\n\n<a id=\"term-recording\"></a>**3.14 recording**: a file that holds the identity and code of a program, a checkpoint of a context when recording began, and the events that followed, in order: each entry with its arguments, its effects and its outcome, and the checkpoints, restores, cleared faults and changes of revision between entries. The state hash at each boundary is recorded and chained into one digest (3.17). From a recording the run can be replayed: its entries run again on a context restored from that checkpoint, with the recorded inputs, and each outcome and boundary is compared with the recording."
  },
  {
   "id": "spec-01p:terms-definitions-and-symbols-p2",
   "edition": "SPEC-01P.2",
   "title": "3 Terms, definitions and symbols (part 3)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "<a id=\"term-case\"></a>**3.15 case**: a recording that also holds the source text of every module of its program, so that the run can be shown, replayed and compared on another machine with no other file.\n\n<a id=\"term-boundary\"></a>**3.16 boundary**: a point of a run at which the state of its context is defined and its state hash is taken: the end of an entry that ran, or, at dispatch density, the publication of a kernel dispatch. A recording records the state hash at each boundary, and replay compares it.\n\n<a id=\"term-digest-chain\"></a>**3.17 digest chain**: the digest that a recording carries in its last event, computed from the state hash of its first checkpoint and of each boundary in turn, so that equal chains mean equal states, and equal fault records, at every boundary.\n\n<a id=\"term-runtime-contract-version\"></a>**3.18 runtime contract version**: the name of the interface between compiled code and the runtime library, `cint-rt-3` in cint 0.2.0.\n\n<a id=\"term-sir-text\"></a>**3.19 SIR text**: the canonical text form of one module's intermediate representation, specified by SPEC-09P.1. Its second line, the *sites line*, lists each *site* of the module, an operation that can fault, with its ordinal, line, column and operation identifier; each node that is a site ends with its ordinal `#n` and its source position.\n\n<a id=\"term-source-map\"></a>**3.20 source map**: the sites of every module of a program, each with its ordinal, line, column and operation identifier. The *source-map digest* is its SHA-256 digest (9.2).\n\n<a id=\"term-record-kind\"></a>**3.21 record kind**: whether a fault record is a *run-time* record, produced by an entry, or a *compile-time* record, produced when a constant expression faults during translation. The kind is not in the bytes; the reader of a record knows it from the place the record came from."
  },
  {
   "id": "spec-01p:terms-definitions-and-symbols-p3",
   "edition": "SPEC-01P.2",
   "title": "3 Terms, definitions and symbols (part 4)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "<a id=\"term-execution-identity\"></a>**3.22 execution identity**: the canonical form of the semantic inputs of one entry (9.3)."
  },
  {
   "id": "spec-01p:conformance",
   "edition": "SPEC-01P.2",
   "title": "4 Conformance",
   "clauses": "H-19a IM-148",
   "url": "/specifications/spec-01p/2/#conformance",
   "internal": 0,
   "content": "## 4 Conformance\n\n1. In this document, \"shall\" states a requirement on an implementation, and \"shall not\" a prohibition. \"May\" states a permission.\n2. A conforming implementation shall write every encoding that it produces exactly as this document specifies, so that for the same content every conforming implementation writes the same bytes. A structure in memory that holds the same content, such as a C structure of a fault record, is a view of it and is not compared.\n3. A conforming decoder shall treat its input as untrusted. It shall reject input that breaks a constraint of this document, it shall check every length and count against the bytes that remain before it allocates memory for what follows, and when it rejects input it shall leave unchanged every state that the input would have changed [IM-148] [SPEC-03P.1 H-19a].\n4. Each encoding of clauses 5 to 9 is named by its domain string; the fixture format of Annex B is named CIF-1 and is versioned as B.1 states. An encoding whose layout changes while it carries the same content takes a new version, with its own domain string, and bytes of the earlier version stay readable as that version. A change of the content that an encoding carries for a program, such as a different fault record for the same fault, is a change of the language profile.\n5. The bytes of every encoding are the same on every host and every executor. No encoding depends on the host's byte order, word size or alignment or on its clock, locale, file system or environment (9.4)."
  },
  {
   "id": "spec-01p:conventions",
   "edition": "SPEC-01P.2",
   "title": "5.1 Conventions",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#conventions",
   "internal": 0,
   "content": "### 5.1 Conventions\n\nEvery encoding in this document is built from a few kinds of field, and the same rules of byte order, length and presence apply to all of them.\n\n**Syntax**\n\n| Notation | Bytes |\n|---|---|\n| `U8`, `U16`, `U32`, `U64` | An unsigned integer of 1, 2, 4 or 8 bytes. |\n| `I32`, `I64` | A signed integer of 4 or 8 bytes, in two's complement. |\n| `str` | A `U32` length `n`, then `n` bytes. |\n| `blob` | A `U64` length `n`, then `n` bytes. |\n| `list(x)` | A `U32` count `n`, then `n` fields of the form `x`. |\n| `list64(x)` | A `U64` count `n`, then `n` fields of the form `x`. |\n| `opt(x)` | A presence byte: `00` alone, or `01` followed by a field of the form `x`. |\n| `digest` | 32 bytes, a SHA-256 digest. |\n| `\"text\"` | A `str` whose bytes are the ASCII characters of `text`. |\n\nA layout lists its fields in order, one a line, each with its name, its form and what it holds.\n\n**Constraints**"
  },
  {
   "id": "spec-01p:conventions-p1",
   "edition": "SPEC-01P.2",
   "title": "5.1 Conventions (part 2)",
   "clauses": "IM-144 IM-148 IM-152 IM-153 IM-7 IM-8 M-4",
   "url": "/specifications/spec-01p/2/#conventions",
   "internal": 0,
   "content": "1. <a id=\"IM-144\"></a>Every integer of more than one byte, in every encoding, is little-endian: its least significant byte comes first. A signed integer is in two's complement at its width [IM-144] [SPEC-03P.1 M-4].\n2. <a id=\"IM-153\"></a>Every length and every count is written before the bytes or fields it counts. No encoding uses a terminator, a sentinel value or padding [IM-153].\n3. A field that may be absent is preceded by a presence byte. Absence is the byte `00` alone, never a field of zeros or another reserved value. A presence byte other than `00` or `01` is invalid.\n4. <a id=\"IM-152\"></a>Each encoding in the table of paragraph 7 begins with its *domain string*: a `str` of lowercase ASCII of the form `<profile>/<kind>/v<n>`, such as `cint-core-1/state/v1`. The last three are the inputs of digests, so the input of every digest of this document begins with one too. The domain string names the encoding and its version, so bytes of two kinds or two versions cannot decode as each other [IM-152].\n5. A quantity that a program sees as an `I64`, the canonical word of SPEC-04P.2 6.3.1, is written as an `I64`, whatever representation an implementation uses for it while a program runs: an array's extent, the capacity of an arena or a pool, a handle's length, a dispatch number, a work-item index, a step ordinal, a fuel quantity and a call-depth limit [SPEC-04P.2 IM-7, IM-8]. The lengths and counts that frame the bytes, those of `str`, `blob`, `list` and `list64`, are unsigned, as the table above gives them.\n6. A decoder rejects input that ends before a field is complete, and input with bytes left over after the end of what it decodes [IM-148].\n\n**Semantics**\n\n7. The domain strings of cint 0.2.0 are:"
  },
  {
   "id": "spec-01p:conventions-p2",
   "edition": "SPEC-01P.2",
   "title": "5.1 Conventions (part 3)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#conventions",
   "internal": 0,
   "content": "| Domain string | Encoding | Section |\n|---|---|---|\n| `cint-core-1/fault/v2` | Fault record, version 2 | 6.1 |\n| `cint-core-1/fault/v3` | Fault record, version 3 | 6.3 |\n| `cint-core-1/fuel-consumed/v1` | Fuel consumed by a program's entry | 6.5 |\n| `cint-core-1/error-result/v1` | Error result of a program's entry | 6.5 |\n| `cint-core-1/state/v1` | State | 7.2 |\n| `cint-core-1/arena/v2` | Arena block of a state | 7.3 |\n| `cint-core-1/pool/v2` | Pool block of a state | 7.3 |\n| `cint-core-1/registry/v1` | Registry block of a state | 7.3 |\n| `cint-core-1/checkpoint/v1` | Checkpoint, `CINT-CKPT-1` | 7.5 |\n| `cint-core-1/recording/v1` | Recording, `CINT-REC-1` | 8.1 |\n| `cint-core-1/case/v1` | Case, `CINT-CASE-1` | 8.6 |\n| `cint-core-1/recording-chain/v1` | Input of the digest chain | 8.5 |\n| `cint-core-1/revision/v1` | Input of the revision identity | 9.1 |\n| `cint-core-1/source-map/v1` | Input of the source-map digest | 9.2 |\n\n8. Each encoding of this table is specified at the version that its domain string names, so the checkpoint, the recording and the case of cint 0.2.0 are specified at version 1. A change of an encoding's layout takes a new version, and bytes of the version specified here stay readable as that version (clause 4, paragraph 4).\n\n**Examples**\n\n9. The `I64` value 1000 is the eight bytes `e8 03 00 00 00 00 00 00`, and the `str` holding the text `fuel-v1` is `07 00 00 00 66 75 65 6c 2d 76 31`.\n\n**Notes**\n\n10. Because every count precedes what it counts, a decoder knows the size of each field before it reads it, and can refuse an impossible length before it allocates memory."
  },
  {
   "id": "spec-01p:integer-bool-and-fixed-point-payloads",
   "edition": "SPEC-01P.2",
   "title": "5.2 Integer, Bool and fixed-point payloads",
   "clauses": "IM-145",
   "url": "/specifications/spec-01p/2/#integer-bool-and-fixed-point-payloads",
   "internal": 0,
   "content": "### 5.2 Integer, Bool and fixed-point payloads\n\nThe payload of a value is its bytes without a type. Every type that an encoding holds has a payload of fixed size, except the mathematical integers of 5.3.\n\n**Syntax**\n\n| Type | Payload |\n|---|---|\n| `I8`, `I16`, `I32`, `I64` | `w / 8` bytes |\n| `I128`, `I256`, `I512`, `I1024` | `w / 8` bytes, in limbs of 8 bytes, limb 0 first |\n| `U8`, `U16`, `U32`, `U64` | `w / 8` bytes |\n| `U128`, `U256`, `U512` | `w / 8` bytes, in limbs of 8 bytes, limb 0 first |\n| `Bool` | 1 byte |\n| `Q<i>.<f>` | the payload of its storage integer, of width `i + f` |\n\n**Constraints**\n\n1. <a id=\"IM-145\"></a>A `Bool` payload is `00` for `false` or `01` for `true`; any other byte is invalid [IM-145].\n\n**Semantics**"
  },
  {
   "id": "spec-01p:integer-bool-and-fixed-point-payloads-p1",
   "edition": "SPEC-01P.2",
   "title": "5.2 Integer, Bool and fixed-point payloads (part 2)",
   "clauses": "IM-12 IM-13 IM-14 IM-145",
   "url": "/specifications/spec-01p/2/#integer-bool-and-fixed-point-payloads",
   "internal": 0,
   "content": "2. The payload of an integer of width `w` is its `w / 8` bytes, least significant first. A value of a signed type is in two's complement at width `w`, and a value of an unsigned type is its binary representation [IM-145].\n3. <a id=\"IM-12\"></a><a id=\"IM-13\"></a>A value of a wide type, `I128` to `I1024` or `U128` to `U512`, is made of `w / 64` limbs. Limb 0 holds bits 0 to 63, limb 1 bits 64 to 127 and the last limb the most significant bits, including the sign bit of a signed type. The payload is the limbs in that order, each limb's 8 bytes least significant first, which makes the whole payload little-endian. There is no sign word, no length and no unused limb: every bit pattern is a value, and every value has one payload [IM-12, IM-13].\n4. <a id=\"IM-14\"></a>The payload is the same on every host. At the C interface a wide value is an array of 64-bit limbs in the host's own byte order (SPEC-03P.1); a host whose byte order is big-endian converts each limb when it reads or writes canonical bytes. A type of the C compiler, such as `__int128` or `_BitInt(N)`, never appears in an encoding [IM-14].\n5. The payload of a value of the fixed-point type `Q<i>.<f>` is the payload of its raw value, the integer `v * 2^f`, in its storage type `I8`, `I16`, `I32` or `I64` of width `i + f`. The payload does not say what `f` is; the tag of 5.4 does [IM-145].\n\n**Examples**\n\n6. Payloads of three `I128` values:\n\n| Value | Payload |\n|---|---|\n| -1 | `ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff` |\n| 1 | `01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00` |\n| 2^64 | `00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00` |\n\n7. The `Q16.16` value 1.5 has the raw value 98304, `0x18000`, so its payload is the `I32` payload `00 80 01 00`."
  },
  {
   "id": "spec-01p:mathematical-integers",
   "edition": "SPEC-01P.2",
   "title": "5.3 Mathematical integers",
   "clauses": "IM-145 IM-148",
   "url": "/specifications/spec-01p/2/#mathematical-integers",
   "internal": 0,
   "content": "### 5.3 Mathematical integers\n\nA value in Z, such as the exact result of an operation that overflowed, has no fixed width, so its payload begins with its length.\n\n**Syntax**\n\n```text\nz:\n  length   U32    n, the number of bytes that follow\n  bytes    n bytes, the value in two's complement, least significant first\n```\n\n**Constraints**\n\n1. The bytes are the shortest two's complement representation of the value: `n` is the least count of bytes whose two's complement range holds it. The value 0 has `n = 0` and no bytes. A payload is therefore invalid when its one byte is `00`, when its last byte is `00` and the byte before it is below `80`, or when its last byte is `ff` and the byte before it is `80` or above [IM-145, IM-148].\n2. The bound on `n` depends on the field and the record that hold the value (6.3).\n\n**Examples**\n\n3. Payloads of values in Z:\n\n| Value | Payload |\n|---|---|\n| 0 | `00 00 00 00` |\n| -1 | `01 00 00 00 ff` |\n| 127 | `01 00 00 00 7f` |\n| 128 | `02 00 00 00 80 00` |\n| -128 | `01 00 00 00 80` |\n| 9223372036854775808 | `09 00 00 00 00 00 00 00 00 00 00 80 00` |\n\n4. The value 128 needs a second byte: one byte `80` alone would be -128.\n5. Adding 1 to the largest `I128` has the exact result 2^127, which needs 128 bits and a sign bit:\n\n```cint w128.ci\nI128 a = I128.max;\n\"{a}\\n\";\nI128 b = a + 1;\n```\n\n```text\n170141183460469231731687303715884105727\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> w128.ci:3:12\n   |\n 3 | I128 b = a + 1;\n   |            ^ add.checked.i128\n   |\n   = operation: add.checked.i128\n   = operand-count: 2\n   = operand: I128 170141183460469231731687303715884105727\n   = operand: I128 1\n   = exact:   170141183460469231731687303715884105728\n   = limit:   I128 170141183460469231731687303715884105727\n   ...\n```"
  },
  {
   "id": "spec-01p:mathematical-integers-p1",
   "edition": "SPEC-01P.2",
   "title": "5.3 Mathematical integers (part 2)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#mathematical-integers",
   "internal": 0,
   "content": "6. In the record of this fault, the operands and the exact result are these bytes, from the operand count on; the tags `15` (`I128`) and `0f` (Z) are those of 5.4:\n\n| Offset | Bytes | Field |\n|---:|---|---|\n| 0 | `02 00 00 00` | operand count, 2 |\n| 4 | `15 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff 7f` | first operand, the largest `I128` |\n| 21 | `15 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00` | second operand, 1 |\n| 38 | `01` | exact: present |\n| 39 | `0f 11 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 80 00` | exact: a Z of 17 bytes, 2^127 |"
  },
  {
   "id": "spec-01p:tagged-values",
   "edition": "SPEC-01P.2",
   "title": "5.4 Tagged values",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#tagged-values",
   "internal": 0,
   "content": "### 5.4 Tagged values\n\nWhere a field can hold values of several types, each value is written with a tag that names its type, followed by its payload.\n\n**Syntax**\n\n| Tag | Type | Bytes after the tag byte | Payload |\n|---|---|---|---|\n| `01` | `Bool` | none | 5.2 |\n| `0f` | Z | none | 5.3 |\n| `11` `12` `13` `14` | `I8` `I16` `I32` `I64` | none | 5.2 |\n| `15` `16` `17` `18` | `I128` `I256` `I512` `I1024` | none | 5.2 |\n| `21` `22` `23` `24` | `U8` `U16` `U32` `U64` | none | 5.2 |\n| `25` `26` `27` | `U128` `U256` `U512` | none | 5.2 |\n| `31` | `Q<i>.<f>` | the storage tag `U8`, `11` to `14`; then `f` as `U16` | 5.2 |\n| `51` | array | the element tag `U8`; the rank `U8`; each extent `I64` | the elements |\n| `71` | struct | the definitions and the type, below | the fields |\n| `75` | `Handle` | none | 29 bytes, below |\n\nA struct value, which only a global of a state holds (7.2), has this tag:\n\n```text\nstruct-tag:\n  tag          U8              71\n  definitions  list(definition)\n  type         U8, U32         71 and the index of the last definition\ndefinition:\n  tag          U8              71\n  name         str             the struct's qualified name, module.Name, UTF-8\n  layout       U8              00\n  fields       list(field)\nfield:\n  name         str             the field's name, UTF-8\n  bit width    U8              00\n  type         field-type\nfield-type:\n  scalar       U8              01, 11 to 18, or 21 to 27\n  struct       U8, U32         71 and the index of an earlier definition\n  array        U8              52, then field-type, the rank U8 (1 to 4),\n                               and for each dimension: 01 as U8, ffffffff as U32, the extent I64\n```\n\nIn an array field-type, `01` is the shape form of a fixed extent and `ffffffff` stands for no size symbol, as in the type signatures of SPEC-03P.1 7.5."
  },
  {
   "id": "spec-01p:tagged-values-p1",
   "edition": "SPEC-01P.2",
   "title": "5.4 Tagged values (part 2)",
   "clauses": "A-21 IM-146 IM-147 IM-148",
   "url": "/specifications/spec-01p/2/#tagged-values",
   "internal": 0,
   "content": "A handle value, which only a global of a state holds, has this payload:\n\n```text\nhandle:\n  slot         U64\n  length       I64\n  generation   U64\n  container    U32             the arena's or pool's identifier\n  kind         U8              00 null, 01 arena, 02 pool\n```\n\n**Constraints**\n\n1. <a id=\"IM-147\"></a>A tagged value is its tag followed by its payload [IM-147].\n2. <a id=\"IM-146\"></a>In the tag `31` of a fixed-point type, the storage tag is `11`, `12`, `13` or `14` and gives the storage width `w`, and `f` is at most `w - 1`, so that the type has at least one integer bit [IM-146].\n3. <a id=\"IM-148\"></a>In the tag `51` of an array, the element tag is `01`, `11` to `18` or `21` to `27`, the rank is 1 to 8, and each extent is at least 0. The payload is the elements' payloads in row-major order, the last index varying fastest. Its size, the product of the extents and the element size, is at most `I64.max` and equals the bytes that remain for it [IM-146, IM-148].\n4. In a struct tag, each definition lists its fields in declaration order. A field's type that is a struct refers to an earlier definition, so a definition never refers to itself or to one after it. The definitions are in the order in which a depth-first walk of the struct's type completes them, each struct once, and the struct of the value is the last, which the type names. Every name is UTF-8 and not empty [IM-146] [SPEC-03P.1 A-21].\n5. The payload of a struct value is its fields' payloads in declaration order, with no padding: a nested struct's fields in place, and an array field's elements in row-major order. Its size, computed from the definitions, equals the bytes that remain for it [IM-146, IM-148].\n6. In a handle payload the kind is `00`, `01` or `02` and every byte of a handle of kind `00`, the null handle, is `00` [IM-146, IM-148].\n7. Each field that holds a tagged value allows only some tags:"
  },
  {
   "id": "spec-01p:tagged-values-p2",
   "edition": "SPEC-01P.2",
   "title": "5.4 Tagged values (part 3)",
   "clauses": "IM-146 IM-148",
   "url": "/specifications/spec-01p/2/#tagged-values",
   "internal": 0,
   "content": "| Field | Tags allowed |\n|---|---|\n| Operand of a fault record (6.1) | `01`, `0f`, `11` to `18`, `21` to `27`, `31` |\n| `exact` of a fault record | `0f` |\n| `limit` of a fault record | `01`, `0f`, `11` to `18`, `21` to `27`, `31` |\n| Value of a global in a state (7.2) | `01`, `11` to `18`, `21` to `27`, `51`, `71`, `75` |\n| Argument or result of an entry in a recording (8.4) | `01`, `11` to `14`, `21` to `24` |\n\n   A decoder rejects any other tag in each field [IM-146, IM-148].\n\n**Examples**\n\n8. Tagged values (Annex A.1 has more):\n\n| Value | Tagged bytes |\n|---|---|\n| `I64` -2 | `14 fe ff ff ff ff ff ff ff` |\n| `U8` 255 | `21 ff` |\n| `Q16.16` 1.5 | `31 13 10 00 00 80 01 00` |\n| Z -1 | `0f 01 00 00 00 ff` |\n| `I8[3]` {120, 120, -120} | `51 11 01 03 00 00 00 00 00 00 00 78 78 88` |\n\n9. A module-level struct variable is one global of the state:\n\n```cint sg.ci\nstruct P { I8 x; Bool b; }\nP p = P(x = 5, b = true);\n\nvoid main() {\n    p.x = p.x + 1;\n    \"{p.x}\\n\";\n}\n```\n\n```text\n6\n```\n\n10. Before `main` runs, the value of the global `sg.p` in the state is these bytes:\n\n| Offset | Bytes | Field |\n|---:|---|---|\n| 0 | `71` | tag: struct |\n| 1 | `01 00 00 00` | 1 definition |\n| 5 | `71` | definition 0 |\n| 6 | `04 00 00 00` | name, length 4 |\n| 10 | `\"sg.P\"` | name |\n| 14 | `00` | layout |\n| 15 | `02 00 00 00` | 2 fields |\n| 19 | `01 00 00 00` | field name, length 1 |\n| 23 | `\"x\"` | field name |\n| 24 | `00` | bit width |\n| 25 | `11` | field type `I8` |\n| 26 | `01 00 00 00` | field name, length 1 |\n| 30 | `\"b\"` | field name |\n| 31 | `00` | bit width |\n| 32 | `01` | field type `Bool` |\n| 33 | `71 00 00 00 00` | the type: definition 0 |\n| 38 | `05 01` | payload: `x` is 5, `b` is `true` |\n\n**Notes**\n\n11. A struct value carries its own type, with the names of its fields, so a decoder reads it without the program. A struct with nested structs and array fields is in Annex A.2."
  },
  {
   "id": "spec-01p:decoding-values",
   "edition": "SPEC-01P.2",
   "title": "5.5 Decoding values",
   "clauses": "IM-148",
   "url": "/specifications/spec-01p/2/#decoding-values",
   "internal": 0,
   "content": "### 5.5 Decoding values\n\nA decoder of any encoding of this document reads tagged values and payloads by the same rules, and rejects bytes that are not a canonical value.\n\n**Constraints**\n\n1. A decoder rejects, before it allocates memory for a payload [IM-148]:\n   - a tag that 5.4 does not define, or one that the field does not allow;\n   - a `Bool` byte other than `00` and `01`, including a `Bool` element of an array or a struct;\n   - a Z whose bytes are not minimal (5.3), or whose length is above the bound of its field and record (6.3);\n   - a fixed-point tag whose storage tag is not `11` to `14`, or whose `f` is above `w - 1`;\n   - an array of rank 0 or above 8, with a negative extent, or whose payload size is above `I64.max` or differs from the bytes that remain;\n   - a handle of a kind above `02`, or a null handle with a byte that is not `00`;\n   - a struct tag with a definition that is missing, a name that is empty or not UTF-8, a layout or bit width other than `00`, an array field of rank 0 or above 4 or with another form or size symbol, a reference to its own definition or to one after it, a type that is not the last definition, or a payload whose size differs from the bytes that remain;\n   - a length or count larger than the bytes that remain."
  },
  {
   "id": "spec-01p:layout",
   "edition": "SPEC-01P.2",
   "title": "6.1 Layout",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#layout",
   "internal": 0,
   "content": "### 6.1 Layout\n\nThe fault record is the canonical form of a fault. SPEC-04P.2 8.1 says what each field means and how a report shows it; this subclause gives its bytes.\n\n**Syntax**\n\n```text\nfault-record:\n  domain      str              \"cint-core-1/fault/v2\", or \"cint-core-1/fault/v3\" (6.3)\n  code        U16              the fault code, 1 to 13\n  operation   str              the operation identifier, ASCII\n  operands    list(tagged)     the operands, in source order\n  exact       opt(tagged)      the exact result, a Z\n  limit       opt(tagged)      the bound that was crossed\n  position    position         the position of the fault\n  revision    opt(digest)      the revision of the program (9.1)\n  source-map  opt(digest)      the source-map digest (9.2)\n  address     opt(address)     the place in a kernel dispatch\n  stack       list(position)   the call sites of the active calls, outermost first\nposition:\n  path        str              the module-relative path, UTF-8\n  line        U32              from 1\n  column      U32              from 1\naddress:\n  kernel      str              the kernel's qualified name, UTF-8\n  dispatch    I64              the dispatch number\n  phase       U8               0 entry, 1 work-item, 2 epilogue\n  work-item   opt(item)        present in phase 1 only\nitem:\n  index       I64              the work-item index\n  step        I64              the step ordinal\n```\n\n**Constraints**"
  },
  {
   "id": "spec-01p:layout-p1",
   "edition": "SPEC-01P.2",
   "title": "6.1 Layout (part 2)",
   "clauses": "IM-104 IM-106 IM-149",
   "url": "/specifications/spec-01p/2/#layout",
   "internal": 0,
   "content": "1. <a id=\"IM-149\"></a>The code is the number of the record's fault code, from 1 for `E_OVERFLOW` to 13 for `E_ASSERT`, as the table of SPEC-04P.2 5.2.3 gives it [IM-149] [SPEC-04P.2 IM-104].\n2. The operation identifier has 1 to 64 bytes, each a lowercase letter, a digit, `.` or `_`. There are at most 8 operands, each a tagged value of a tag that 5.4 allows for an operand [IM-149] [SPEC-04P.2 IM-106].\n3. `exact`, when present, is a tagged Z [IM-149].\n4. The path of a position has 1 to 1024 bytes of UTF-8, and its line and column are at least 1 [IM-149] [SPEC-04P.2 IM-106].\n5. An absent revision, source-map digest or address is a presence byte `00`, never 32 zero bytes or another placeholder [IM-149].\n6. The kernel name of an address has at most 256 bytes of UTF-8, and its phase is 0, 1 or 2. The work-item field is present when the phase is 1 and absent otherwise [IM-149].\n7. The stack has fewer positions than the entry's call-depth limit, and a decoder rejects a stack of more than 1024 positions [IM-149] [SPEC-04P.2 IM-106].\n\n**Semantics**\n\n8. The bytes of a record are a function of its content alone: the writer takes no padding, alignment or other byte from the structure in memory that holds the record, and conformance compares the bytes, never the structure [IM-149] [SPEC-09P.1 RT-13, RT-14].\n9. cint 0.2.0 writes the source-map digest of every fault record as absent. A recording or a case holds the source-map digest of its program in its header (8.2), which names the positions of every record it holds.\n\n**Examples**\n\n10. A fault inside a kernel has an address:\n\n```cint kern.ci\nkernel bump[n](in I64[n] old, out I64[n] next) {\n    next = old + 1;\n}\n\nvoid main() {\n    I64[3] a = [1, 2, 9223372036854775807];\n    I64[3] b;\n    bump(a, b);\n    \"{b[0]}\\n\";\n}\n```"
  },
  {
   "id": "spec-01p:layout-p2",
   "edition": "SPEC-01P.2",
   "title": "6.1 Layout (part 3)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#layout",
   "internal": 0,
   "content": "```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> kern.ci:2:16\n   |\n 2 |     next = old + 1;\n   |                ^ add.checked.i64\n   |\n   = operation: add.checked.i64\n   = operand-count: 2\n   = operand: I64 9223372036854775807\n   = operand: I64 1\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n   ...\n```\n\n11. The record of this fault ends with these bytes, from the address on:\n\n| Offset | Bytes | Field |\n|---:|---|---|\n| 0 | `01` | address: present |\n| 1 | `09 00 00 00` | kernel, length 9 |\n| 5 | `\"kern.bump\"` | kernel |\n| 14 | `00 00 00 00 00 00 00 00` | dispatch number 0 |\n| 22 | `01` | phase 1, work-item |\n| 23 | `01` | work item: present |\n| 24 | `02 00 00 00 00 00 00 00` | work-item index 2 |\n| 32 | `02 00 00 00 00 00 00 00` | step ordinal 2 |\n| 40 | `01 00 00 00` | stack: 1 position |\n| 44 | `07 00 00 00` | path, length 7 |\n| 48 | `\"kern.ci\"` | path |\n| 55 | `08 00 00 00` | line number 8 |\n| 59 | `05 00 00 00` | column number 5 |\n\n**Notes**\n\n12. No field of a fault record holds a native address, a register, a time, a thread identifier, a backend name or an absolute path, so a fault has the same record on every executor and every host."
  },
  {
   "id": "spec-01p:a-worked-record",
   "edition": "SPEC-01P.2",
   "title": "6.2 A worked record",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#a-worked-record",
   "internal": 0,
   "content": "### 6.2 A worked record\n\nThe record of the fault in the Introduction, byte by byte.\n\n**Examples**\n\n1. `cint run` keeps the bytes of the fault record of a run in the file `fault.bin` of the run's directory, under the directory given by `--cache`:\n\n```console\n$ cint run --cache out ledger.ci\nrest 70\nfault[E_NARROW]: the value does not fit the destination type\n...\n   = revision: 359672553c501187e1e53e4878d6ede8f1994b52ce0c64c8f3ec4fbdf3f9b3db\n...\n$ od -An -tx1 -v out/*/run-0/fault.bin\n 14 00 00 00 63 69 6e 74 2d 63 6f 72 65 2d 31 2f\n 66 61 75 6c 74 2f 76 32 06 00 11 00 00 00 61 73\n 2e 63 68 65 63 6b 65 64 2e 69 36 34 2e 75 38 01\n 00 00 00 14 f6 ff ff ff ff ff ff ff 01 0f 01 00\n 00 00 f6 01 21 00 09 00 00 00 6c 65 64 67 65 72\n 2e 63 69 05 00 00 00 17 00 00 00 01 35 96 72 55\n 3c 50 11 87 e1 e5 3e 48 78 d6 ed e8 f1 99 4b 52\n ce 0c 64 c8 f3 ec 4f bd f3 f9 b3 db 00 00 01 00\n 00 00 09 00 00 00 6c 65 64 67 65 72 2e 63 69 0b\n 00 00 00 05 00 00 00\n```\n\n2. The revision is the 32 bytes at offsets 92 to 123, the same digest that the report prints. Field by field:"
  },
  {
   "id": "spec-01p:a-worked-record-p1",
   "edition": "SPEC-01P.2",
   "title": "6.2 A worked record (part 2)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#a-worked-record",
   "internal": 0,
   "content": "| Offset | Bytes | Field |\n|---:|---|---|\n| 0 | `14 00 00 00` | domain string, length 20 |\n| 4 | `\"cint-core-1/fault/v2\"` | domain string |\n| 24 | `06 00` | code 6, `E_NARROW` |\n| 26 | `11 00 00 00` | operation, length 17 |\n| 30 | `\"as.checked.i64.u8\"` | operation |\n| 47 | `01 00 00 00` | 1 operand |\n| 51 | `14 f6 ff ff ff ff ff ff ff` | operand: `I64` -10 |\n| 60 | `01` | exact: present |\n| 61 | `0f 01 00 00 00 f6` | exact: Z -10 |\n| 67 | `01` | limit: present |\n| 68 | `21 00` | limit: `U8` 0 |\n| 70 | `09 00 00 00` | position: path, length 9 |\n| 74 | `\"ledger.ci\"` | position: path |\n| 83 | `05 00 00 00` | position: line number 5 |\n| 87 | `17 00 00 00` | position: column number 23 |\n| 91 | `01` | revision: present |\n| 92 | (32 bytes) | revision |\n| 124 | `00` | source-map digest: absent |\n| 125 | `00` | address: absent |\n| 126 | `01 00 00 00` | stack: 1 position |\n| 130 | `09 00 00 00` | path, length 9 |\n| 134 | `\"ledger.ci\"` | path |\n| 143 | `0b 00 00 00` | line number 11 |\n| 147 | `05 00 00 00` | column number 5 |\n\n**Notes**\n\n3. The record does not hold the fuel consumed, which the report prints after the record's fields; fuel has its own record (6.5)."
  },
  {
   "id": "spec-01p:size-bounds-and-version-3",
   "edition": "SPEC-01P.2",
   "title": "6.3 Size bounds and version 3",
   "clauses": "IM-108 IM-148 IM-149",
   "url": "/specifications/spec-01p/2/#size-bounds-and-version-3",
   "internal": 0,
   "content": "### 6.3 Size bounds and version 3\n\nEvery field of a fault record has a bound, so a decoder can refuse an oversized record before it reads it. The bound on a Z depends on the record's version and kind.\n\n**Constraints**\n\n1. <a id=\"IM-108\"></a>In a run-time record of version 2, every Z, whether an operand, `exact` or `limit`, has at most 257 bytes. The largest such value is the 2048-bit product inside a checked `*` or a `muldiv` of `I1024` operands [IM-108].\n2. A compile-time record is of version 2. Its operands may be a Z of up to 513 bytes, which holds the largest integer literal with its sign, and its `exact` a Z of up to 520 bytes, which holds the largest literal scaled to the fixed-point type `Q1.63`. Its `limit` has at most 257 bytes [IM-108, IM-148].\n3. A run-time record whose operation identifier begins with `dot.checked.i1024.` is written in version 3, with the domain string `cint-core-1/fault/v3`. Every other record is written in version 2. Version 3 has the layout of version 2; it differs in its bound alone: every Z of a version 3 record has at most 264 bytes, which holds the exact sum of up to `I64.max` products of two `I1024` values [IM-108, IM-149].\n4. No compile-time record is of version 3 [IM-108, IM-149].\n\n**Notes**\n\n5. Each record thus has exactly one encoding: no record that version 2 can hold is written in version 3."
  },
  {
   "id": "spec-01p:record-kinds-and-decoding",
   "edition": "SPEC-01P.2",
   "title": "6.4 Record kinds and decoding",
   "clauses": "IM-148 IM-149",
   "url": "/specifications/spec-01p/2/#record-kinds-and-decoding",
   "internal": 0,
   "content": "### 6.4 Record kinds and decoding\n\nA decoder of a fault record is told the record's kind by its caller, because the same bytes are bounded differently at run time and at compile time.\n\n**Constraints**\n\n1. A decoder is given the record kind with the bytes, which do not carry it: compile-time for a record that a compiler reports with a diagnostic of a faulting constant, run-time for a record of an entry, including every record held in a state, a checkpoint or a recording. A record decoded under the wrong kind is rejected when a field is above that kind's bound [IM-148, IM-149].\n2. A decoder rejects, besides the values of 5.5 [IM-148]:\n   - a domain string other than the two of 6.1;\n   - a code outside 1 to 13, an operation identifier that is empty, longer than 64 bytes or has another character, or more than 8 operands;\n   - an `exact` that is not a Z;\n   - a run-time record of version 3 whose operation does not begin with `dot.checked.i1024.`, and one of version 2 whose operation does;\n   - a version 3 record decoded with the compile-time kind;\n   - a position whose path is empty, longer than 1024 bytes or not UTF-8, or whose line or column is 0;\n   - an address whose phase is above 2, or with a work item outside phase 1;\n   - a stack of more than 1024 positions;\n   - bytes after the last position of the stack, when the record is a file of its own."
  },
  {
   "id": "spec-01p:records-of-fuel-consumed-and-of-an-error-result",
   "edition": "SPEC-01P.2",
   "title": "6.5 Records of fuel consumed and of an error result",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#records-of-fuel-consumed-and-of-an-error-result",
   "internal": 0,
   "content": "### 6.5 Records of fuel consumed and of an error result\n\nA compiled program run by the `cint` command reports, beside its fault record, the fuel its entry consumed and an error result when `main` returns an error. Each is a small record with its own domain string.\n\n**Syntax**\n\n```text\nfuel-record:\n  domain      str     \"cint-core-1/fuel-consumed/v1\"\n  consumed    I64     the fuel consumed by the entry, at least 0\nerror-record:\n  domain      str     \"cint-core-1/error-result/v1\"\n  set         str     the error set's qualified name, module.Set\n  value       str     the error value's name\n  tag type    U32     the tag of the set's tag type, 21 to 24\n  tag         U64     the value's tag, from 1\n```\n\n**Constraints**\n\n1. A fuel record has exactly 40 bytes. In an error record the tag is at least 1 and fits the tag type, and nothing follows the tag.\n\n**Semantics**\n\n2. A program writes the fuel record when its entry ran, whether it ended normally, with an error result or with a fault. It writes the error record in place of a fault record when `main` returns an error; `cint run` then exits with status 6 (SPEC-06P.1).\n\n**Examples**\n\n3. A `main` that returns an error:\n\n```console\n$ cat err.ci\nerror LedgerError { overdrawn }\n\nLedgerError!void main() {\n    \"checking\\n\";\n    return LedgerError.overdrawn;\n}\n$ cint run --cache out-err err.ci\nchecking\nerror: err.LedgerError.overdrawn (tag 1)\n$ od -An -tx1 -v out-err/*/run-0/fault.bin\n 1b 00 00 00 63 69 6e 74 2d 63 6f 72 65 2d 31 2f\n 65 72 72 6f 72 2d 72 65 73 75 6c 74 2f 76 31 0f\n 00 00 00 65 72 72 2e 4c 65 64 67 65 72 45 72 72\n 6f 72 09 00 00 00 6f 76 65 72 64 72 61 77 6e 22\n 00 00 00 01 00 00 00 00 00 00 00\n$ od -An -tx1 -v out-err/*/run-0/fuel.bin\n 1c 00 00 00 63 69 6e 74 2d 63 6f 72 65 2d 31 2f\n 66 75 65 6c 2d 63 6f 6e 73 75 6d 65 64 2f 76 31\n 01 00 00 00 00 00 00 00\n```"
  },
  {
   "id": "spec-01p:records-of-fuel-consumed-and-of-an-error-result-p1",
   "edition": "SPEC-01P.2",
   "title": "6.5 Records of fuel consumed and of an error result (part 2)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#records-of-fuel-consumed-and-of-an-error-result",
   "internal": 0,
   "content": "4. The error record names the set `err.LedgerError` and the value `overdrawn`, with the tag type `22`, the tag of `U16` and the tag 1. The fuel record holds the fuel consumed, 1."
  },
  {
   "id": "spec-01p:what-state-holds",
   "edition": "SPEC-01P.2",
   "title": "7.1 What state holds",
   "clauses": "IM-150 IM-151 IM-155 M-3",
   "url": "/specifications/spec-01p/2/#what-state-holds",
   "internal": 0,
   "content": "### 7.1 What state holds\n\nThe state of a context is everything that one entry leaves for the next. It holds logical values only, so that two executors that agree on a program's meaning write the same state.\n\n**Semantics**\n\n1. SPEC-03P.1 5.1 states what the state of a context holds: its program's revision, profile and fuel model, its module-level variables, its arenas, pools and registered buffers, its identifier counters and count of entries begun, the fault record it holds and its count of effects completed. 7.2 to 7.4 give their bytes [SPEC-03P.1 M-3].\n2. <a id=\"IM-151\"></a>State contains logical values only: typed values, declared lengths and logical identifiers. It never contains a native pointer, a device allocation, padding or any other byte that depends on where or how the program runs [IM-151].\n3. <a id=\"IM-155\"></a>A quantity of one entry is not state: the fuel allowance, the fuel consumed, the dispatch counter and the call-depth limit are inputs or results of the entry (8.4), and the local variables of active calls are gone between entries [IM-155].\n4. <a id=\"IM-150\"></a>7.2 gives the framing of state, its domain strings and its order. The blocks of arenas, pools and the registry (7.3) have their own domain strings, inside that framing [IM-150]."
  },
  {
   "id": "spec-01p:state-layout",
   "edition": "SPEC-01P.2",
   "title": "7.2 State layout",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#state-layout",
   "internal": 0,
   "content": "### 7.2 State layout\n\n**Syntax**\n\n```text\nstate:\n  domain      str              \"cint-core-1/state/v1\"\n  revision    digest           the revision of the program (9.1)\n  profile     str              \"cint-core-1\"\n  globals     list64(global)   sorted by the bytes of their names\n  arenas      blob             the arena block (7.3), or empty\n  pools       blob             the pool block (7.3), or empty\n  registry    blob             the registry block (7.3), or empty\n  next-buffer U64              the next buffer identifier\n  next-arena  U64              the next arena identifier\n  next-pool   U64              the next pool identifier\n  entries     U64              the entry sequence number\n  fuel-model  str              \"fuel-v1\"\n  fault       opt(fault-record)  the fault record held (6.1)\n  effects     I64              the effect-log position\nglobal:\n  name        str              the qualified name, module.name, UTF-8\n  value       tagged           its value (5.4)\n```\n\n**Constraints**"
  },
  {
   "id": "spec-01p:state-layout-p1",
   "edition": "SPEC-01P.2",
   "title": "7.2 State layout (part 2)",
   "clauses": "H-19a IM-156",
   "url": "/specifications/spec-01p/2/#state-layout",
   "internal": 0,
   "content": "1. <a id=\"IM-156\"></a>The globals are sorted by the bytes of their names, each name strictly after the one before it; a name is not empty and is UTF-8 [IM-156].\n2. A module-level variable of an integer or `Bool` type is a global whose value has that type's tag. A module-level array is one global whose value is an array (tag `51`) with its elements in row-major order. A module-level struct variable is one global whose value has the struct tag `71`, with its type and its payload. A module-level `Handle` is one global whose value has the handle tag `75` [IM-156].\n3. Each of the arena, pool and registry blocks is a `blob`. Its length is 0 when the state has no arena, pool or registered buffer; an arena or pool block stays empty until the first operation on an arena or a pool [IM-156].\n4. The fault record is a run-time record, bounded as such (6.3) [IM-156].\n5. Each identifier counter is greater than every identifier of its kind in the state. The next buffer identifier is at least 1, and the next arena and pool identifiers are at most 2^32 [IM-156] [SPEC-03P.1 H-19a].\n6. The effect-log position is at least 0, and nothing follows it [IM-156] [SPEC-03P.1 H-19a].\n\n**Semantics**\n\n7. The entry sequence number counts the entries begun in the context. The effect-log position counts the effects completed; clearing a held fault changes neither [IM-156].\n8. The fault record held in state carries its own domain string, so the version of its encoding is visible inside the state bytes [IM-156].\n\n**Examples**\n\n9. The case that `cint debug locate` saves for `ledger.ci` (8.6) begins with a checkpoint of the state before `main` runs. Its state, from the domain string on, is these 182 bytes:"
  },
  {
   "id": "spec-01p:state-layout-p2",
   "edition": "SPEC-01P.2",
   "title": "7.2 State layout (part 3)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#state-layout",
   "internal": 0,
   "content": "| Offset | Bytes | Field |\n|---:|---|---|\n| 0 | `14 00 00 00` | domain string, length 20 |\n| 4 | `\"cint-core-1/state/v1\"` | domain string |\n| 24 | (32 bytes) | revision |\n| 56 | `0b 00 00 00` | profile, length 11 |\n| 60 | `\"cint-core-1\"` | profile |\n| 71 | `01 00 00 00 00 00 00 00` | 1 global |\n| 79 | `0e 00 00 00` | name, length 14 |\n| 83 | `\"ledger.balance\"` | name |\n| 97 | `14 64 00 00 00 00 00 00 00` | value: `I64` 100 |\n| 106 | `00 00 00 00 00 00 00 00` | arena block: empty |\n| 114 | `00 00 00 00 00 00 00 00` | pool block: empty |\n| 122 | `00 00 00 00 00 00 00 00` | registry block: empty |\n| 130 | `01 00 00 00 00 00 00 00` | next buffer identifier 1 |\n| 138 | `01 00 00 00 00 00 00 00` | next arena identifier 1 |\n| 146 | `01 00 00 00 00 00 00 00` | next pool identifier 1 |\n| 154 | `00 00 00 00 00 00 00 00` | entry sequence number 0 |\n| 162 | `07 00 00 00` | fuel model, length 7 |\n| 166 | `\"fuel-v1\"` | fuel model |\n| 173 | `00` | fault record: absent |\n| 174 | `00 00 00 00 00 00 00 00` | effect-log position 0 |"
  },
  {
   "id": "spec-01p:arena-pool-and-registry-blocks",
   "edition": "SPEC-01P.2",
   "title": "7.3 Arena, pool and registry blocks",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#arena-pool-and-registry-blocks",
   "internal": 0,
   "content": "### 7.3 Arena, pool and registry blocks\n\nEach block holds one kind of storage of the context and begins with its own domain string.\n\n**Syntax**"
  },
  {
   "id": "spec-01p:arena-pool-and-registry-blocks-p1",
   "edition": "SPEC-01P.2",
   "title": "7.3 Arena, pool and registry blocks (part 2)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#arena-pool-and-registry-blocks",
   "internal": 0,
   "content": "```text\narena-block:\n  domain      str              \"cint-core-1/arena/v2\"\n  rows        list64(arena)    by identifier, at least 1\n  contents    for each module-level arena, in order of its row:\n                element type (7.4), then its used elements\narena:\n  id          U32              from 1\n  parent      U32              the parent's identifier, 0 for a module-level arena\n  retired     U8               0 or 1\n  offset      I64              the offset in the parent, in elements\n  capacity    I64              in elements\n  used        I64              the used extent, in elements\n  generation  U64\npool-block:\n  domain      str              \"cint-core-1/pool/v2\"\n  pools       list64(pool)     at least 1\npool:\n  id          U32              its position in the list, from 1\n  type        element type (7.4)\n  capacity    I64              in slots\n  used        U64              the number of slots ever taken\n  top         U64              the first slot of the free list, plus 1; 0 when the list is empty\n  slots       used times slot\n  elements    the payload of each occupied slot's element, in slot order\nslot:\n  generation  U64\n  mark        U8               0 vacant, 1 occupied, 2 retired\n  below       U64              the next slot of the free list, plus 1; 0 at its end\nregistry-block:\n  domain      str              \"cint-core-1/registry/v1\"\n  entries     list64(entry)    by identifier, at least 1\nentry:\n  id          U64\n  generation  U64\n  origin      U8               1 borrowed, 2 bridge\n  element     U16              the element type's tag, or 0\n  storage     U8               0\n  frac        U16              0\n  record      U32              the struct's number, for a struct element; 0 otherwise\n  extent      I64\n  ceiling     U8               0 read, 1 write: the widest access a view of it may have\n  publish     U8               0 none, 1 copy: whether a kernel"
  },
  {
   "id": "spec-01p:arena-pool-and-registry-blocks-p2",
   "edition": "SPEC-01P.2",
   "title": "7.3 Arena, pool and registry blocks (part 3)",
   "clauses": "H-19a M-3",
   "url": "/specifications/spec-01p/2/#arena-pool-and-registry-blocks",
   "internal": 0,
   "content": "**Constraints**\n\n1. An arena row has 41 bytes. Its identifier is at least 1, its retired byte is 0 or 1, its capacity and used extent are at least 0 with the used extent at most the capacity, and its generation is at most 2^64 - 2 [SPEC-03P.1 H-19a].\n2. The rows are in increasing order of identifier. The module-level arenas come first, with identifiers 1 to `n`, not retired and at offset 0. A child arena's parent is an earlier row; the child lies within its parent's capacity, and, unless retired, within its parent's used extent; a child of a retired arena is retired [SPEC-03P.1 H-19a].\n3. The element type of each module-level arena is followed by exactly its used elements, and the block ends after the last of them [SPEC-03P.1 M-3, H-19a].\n4. Each pool's identifier is its position in the list, from 1, and there are fewer than 2^32 pools. A pool's used slots are at most its capacity. A slot has 17 bytes: a retired slot has the generation 2^64 - 2, a vacant slot a generation of at least 1, every generation is at most 2^64 - 2, and a slot that is not vacant has `below` 0. Starting at `top`, the free list visits every vacant slot exactly once and no other slot. The elements of the occupied slots follow the slots, and the block ends after the last pool [SPEC-03P.1 M-3, H-19a].\n5. A registry entry has 37 bytes. The identifiers are at least 1 and increase; a generation is 1 to 2^64 - 2; the origin is 1 or 2; the storage, `frac` and state bytes are 0; `record` is 0 unless the element is a struct; the extent is at least 0; and the element, ceiling and publish fields hold values that SPEC-03P.1 6.1 defines for a registration: the element is 0 only for a borrowed buffer, the ceiling is 0 or 1, and the publish byte is 0 or 1, and 1 only when the ceiling is 1. An entry holds no contents [SPEC-03P.1 M-3, H-19a].\n\n**Semantics**"
  },
  {
   "id": "spec-01p:arena-pool-and-registry-blocks-p3",
   "edition": "SPEC-01P.2",
   "title": "7.3 Arena, pool and registry blocks (part 4)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#arena-pool-and-registry-blocks",
   "internal": 0,
   "content": "6. The registry block lists the buffers that a host program has lent to the context (SPEC-03P.1). A context that only runs its program has none."
  },
  {
   "id": "spec-01p:element-types",
   "edition": "SPEC-01P.2",
   "title": "7.4 Element types",
   "clauses": "A-21 H-19a M-3",
   "url": "/specifications/spec-01p/2/#element-types",
   "internal": 0,
   "content": "### 7.4 Element types\n\nAn arena or a pool holds elements of one type, which the block writes once, with the size of one element, so that a decoder can step through the elements without the program.\n\n**Syntax**\n\n```text\nelement-type:\n  width        U32              the bytes of one element's payload\n  definitions  list(definition) as in a struct tag (5.4)\n  type         field-type       a scalar tag, 75, or 71 and the last definition's index\n```\n\n**Constraints**\n\n1. With no definitions, the type is a scalar tag or `75`, and the width is the size of that type's payload. With definitions, the type is `71` and the index of the last definition, and the definitions follow the constraints of a struct tag, except that an array field has rank 1 [SPEC-03P.1 M-3, A-21, H-19a].\n\n**Examples**\n\n2. The element type of an arena of `I32` is `04 00 00 00 00 00 00 00 13`: width 4, no definitions, the tag of `I32`. Annex A.3 shows a whole arena block and pool block."
  },
  {
   "id": "spec-01p:checkpoints",
   "edition": "SPEC-01P.2",
   "title": "7.5 Checkpoints",
   "clauses": "H-15 H-19 H-19a",
   "url": "/specifications/spec-01p/2/#checkpoints",
   "internal": 0,
   "content": "### 7.5 Checkpoints\n\nA checkpoint is a state in an envelope. The envelope is not hashed: it names the runtime contract under which the state was taken.\n\n**Syntax**\n\n```text\ncheckpoint:\n  domain       str            \"cint-core-1/checkpoint/v1\"\n  contract     str            the runtime contract version, \"cint-rt-3\"\n  payload      opt(digest)    absent\n  build-record opt(digest)    absent\n  build        opt(digest)    absent\n  state        blob           the state (7.2)\n```\n\n**Constraints**\n\n1. The runtime contract version has 1 to 64 bytes, each a printable ASCII character from `21` to `7e`. The length of the state equals the bytes that remain, and the state's bytes are exactly one state [SPEC-03P.1 H-19, H-19a].\n2. cint 0.2.0 writes the payload digest, the build record digest and the build identity as absent [SPEC-03P.1 H-15, H-19].\n\n**Semantics**\n\n3. The format is `CINT-CKPT-1`. A checkpoint is the bytes that a host program receives when it checkpoints a context (SPEC-03P.1), and that a workbench session saves for each of its checkpoints (SPEC-06P.1) [SPEC-03P.1 H-19].\n\n**Examples**\n\n4. The checkpoint at the start of the case of `ledger.ci` has 235 bytes: this envelope, then the 182 bytes of state of 7.2.\n\n| Offset | Bytes | Field |\n|---:|---|---|\n| 0 | `19 00 00 00` | domain string, length 25 |\n| 4 | `\"cint-core-1/checkpoint/v1\"` | domain string |\n| 29 | `09 00 00 00` | runtime contract, length 9 |\n| 33 | `\"cint-rt-3\"` | runtime contract |\n| 42 | `00` | payload digest: absent |\n| 43 | `00` | build record digest: absent |\n| 44 | `00` | build identity: absent |\n| 45 | `b6 00 00 00 00 00 00 00` | state, length 182 |\n| 53 | (182 bytes) | state (7.2) |"
  },
  {
   "id": "spec-01p:state-hash",
   "edition": "SPEC-01P.2",
   "title": "7.6 State hash",
   "clauses": "H-15 IM-154 IM-156 M-5",
   "url": "/specifications/spec-01p/2/#state-hash",
   "internal": 0,
   "content": "### 7.6 State hash\n\n**Semantics**\n\n1. <a id=\"IM-154\"></a>The state hash of a context is `SHA-256` of its state bytes, from the length of the state's domain string through the effect-log position, as 7.2 lays them out. The envelope of a checkpoint is not part of it [IM-154] [SPEC-03P.1 M-5].\n2. An implementation computes SHA-256 itself, and the conformance suite checks it against the digests of fixed inputs; the SHA-256 of the empty input, for example, is `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` [IM-154].\n3. State hashes are compared only between states of one runtime contract version. The revision is part of the state, and the revision changes with the runtime contract version (9.1), so rebuilding an unchanged program against another version changes its state hash [IM-156] [SPEC-03P.1 H-15].\n\n**Notes**\n\n4. The fault record held in state is part of the hashed bytes, and its position is part of the record. Moving a faulting line therefore changes the state hash of the faulted state, though the revision stays the same (9.4)."
  },
  {
   "id": "spec-01p:restoring-a-checkpoint",
   "edition": "SPEC-01P.2",
   "title": "7.7 Restoring a checkpoint",
   "clauses": "H-19 H-19a M-11",
   "url": "/specifications/spec-01p/2/#restoring-a-checkpoint",
   "internal": 0,
   "content": "### 7.7 Restoring a checkpoint\n\nA restore replaces the state of a context with the state of a checkpoint. Checkpoint bytes are untrusted input, so a restore checks everything before it changes anything.\n\n**Constraints**\n\n1. A restore refuses a checkpoint whose runtime contract version or revision is not exactly the context's; SPEC-03P.1 9.2 states the rule [SPEC-03P.1 H-19].\n2. Before it changes any state, a restore checks every constraint of clauses 5 and 7 that the bytes alone can break, and then, against the program, the following; a checkpoint that fails a check is refused, and the context is left exactly as it was [SPEC-03P.1 H-19a]:\n   - the globals are exactly the program's module-level variables, each with the same qualified name and the same type;\n   - the module-level arenas and pools are exactly those that the program declares, each with the same element type;\n   - every struct number of the registry names a struct of the program;\n   - a held fault record has a position that names a site of the program.\n\n**Semantics**\n\n3. A restore sets each identifier counter as SPEC-03P.1 6.1 states, so that no identifier is issued twice in a context's lifetime; a recording records the counters it chose (8.4) [SPEC-03P.1 M-11]."
  },
  {
   "id": "spec-01p:the-recording-file",
   "edition": "SPEC-01P.2",
   "title": "8.1 The recording file",
   "clauses": "H-14",
   "url": "/specifications/spec-01p/2/#the-recording-file",
   "internal": 0,
   "content": "### 8.1 The recording file\n\nA recording holds the program's identity and code, a checkpoint of the context when recording began, and the events that followed. With them, the entries run in a context can be replayed and each step compared with what happened.\n\n**Syntax**\n\n```text\nrecording:\n  header       header (8.2)     the domain string \"cint-core-1/recording/v1\", or \"cint-core-1/case/v1\"\n  code         code (8.3)\n  initial      blob             a checkpoint (7.5) of the context when recording began\n  events       event (8.4)      one or more, the end event last\n```\n\n**Constraints**\n\n1. The initial checkpoint is a valid checkpoint whose revision is the revision of the header. The last event is the end event, and no byte follows it [SPEC-03P.1 H-14].\n\n**Semantics**\n\n2. The format is `CINT-REC-1`. A host program makes a recording through a recorder (SPEC-03P.1); `cint workbench` records every session; `cint debug locate` saves a case (8.6) [SPEC-03P.1 H-14]."
  },
  {
   "id": "spec-01p:header",
   "edition": "SPEC-01P.2",
   "title": "8.2 Header",
   "clauses": "H-14 H-14a",
   "url": "/specifications/spec-01p/2/#header",
   "internal": 0,
   "content": "### 8.2 Header\n\n**Syntax**\n\n```text\nheader:\n  domain       str              \"cint-core-1/recording/v1\", or \"cint-core-1/case/v1\"\n  profile      str              \"cint-core-1\"\n  fuel-model   str              \"fuel-v1\"\n  contract     str              the runtime contract version\n  revision     digest           the revision of the code (9.1)\n  source-map   opt(digest)      the source-map digest of the code (9.2)\n  mode         U8               0 full, 1 digest\n  interval     U64              1\n  density      U8               0 entry, 1 dispatch\n```\n\n**Constraints**\n\n1. <a id=\"H-14a\"></a>The runtime contract version has 1 to 64 bytes from `21` to `7e`. The mode is 0 or 1, the interval is 1, and the density is 0 or 1 [H-14a] [SPEC-03P.1 H-14].\n2. The source-map digest is present exactly when the code gives one (9.2), and it equals the digest of the code [SPEC-03P.1 H-14].\n\n**Semantics**\n\n3. The interval 1 means that the state hash of every entry is recorded. At entry density the boundaries are the ends of entries; at dispatch density each dispatch of a kernel is a boundary too [H-14a] [SPEC-03P.1 H-14].\n4. In cint 0.2.0 a recording in digest mode differs from one in full mode only in its mode byte.\n\n**Examples**\n\n5. The header of the case of `ledger.ci`, through the module count of its code:"
  },
  {
   "id": "spec-01p:header-p1",
   "edition": "SPEC-01P.2",
   "title": "8.2 Header (part 2)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#header",
   "internal": 0,
   "content": "| Offset | Bytes | Field |\n|---:|---|---|\n| 0 | `13 00 00 00` | domain string, length 19 |\n| 4 | `\"cint-core-1/case/v1\"` | domain string |\n| 23 | `0b 00 00 00` | profile, length 11 |\n| 27 | `\"cint-core-1\"` | profile |\n| 38 | `07 00 00 00` | fuel model, length 7 |\n| 42 | `\"fuel-v1\"` | fuel model |\n| 49 | `09 00 00 00` | runtime contract, length 9 |\n| 53 | `\"cint-rt-3\"` | runtime contract |\n| 62 | (32 bytes) | revision |\n| 94 | `01` | source-map digest: present |\n| 95 | (32 bytes) | source-map digest |\n| 127 | `00` | mode: full |\n| 128 | `01 00 00 00 00 00 00 00` | interval 1 |\n| 136 | `00` | density: entry |\n| 137 | `01 00 00 00` | code: 1 module |"
  },
  {
   "id": "spec-01p:code",
   "edition": "SPEC-01P.2",
   "title": "8.3 Code",
   "clauses": "H-14",
   "url": "/specifications/spec-01p/2/#code",
   "internal": 0,
   "content": "### 8.3 Code\n\nA recording carries the code it ran, so a replay needs no other file and reproduces every fault record byte for byte.\n\n**Syntax**\n\n```text\ncode:\n  modules      list(module)\nmodule:\n  path         str              the module-relative path, ending in \".ci\"\n  sir          blob             the module's SIR text, with its sites line\n  source       opt(blob)        the module's source text\n```\n\n**Constraints**\n\n1. Each path has 4 to 1024 bytes of UTF-8 and ends in `.ci` [SPEC-03P.1 H-14].\n\n**Semantics**\n\n2. The code holds every module of the program: the root module and every module it imports. Each module's SIR text is the one from which the revision (9.1) and the source-map digest (9.2) are computed. A module's source text is present when the host supplied it, and in every module of a case [SPEC-03P.1 H-14]."
  },
  {
   "id": "spec-01p:events",
   "edition": "SPEC-01P.2",
   "title": "8.4 Events",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#events",
   "internal": 0,
   "content": "### 8.4 Events\n\nEach event is one byte that gives its kind, followed by its fields.\n\n**Syntax**"
  },
  {
   "id": "spec-01p:events-p1",
   "edition": "SPEC-01P.2",
   "title": "8.4 Events (part 2)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#events",
   "internal": 0,
   "content": "```text\nevent 1, entry:\n  sequence     U64              the entry sequence number, from 1\n  form         U8               0 an exported function, 1 the program entry\n  module       str              the path of the function's module; empty for the program entry\n  function     str              the function's name; empty for the program entry\n  arguments    list(tagged)     at most 16; none for the program entry\n  fuel         I64              the fuel budget, or -1 for no budget\n  depth        I64              the call-depth limit, at least 1\n  frame-arena  I64              the frame-arena capacity, at least 0\n  inputs       U32              0\nevent 2, effect:\n  ordinal      I64              the effect-log position of the effect, from 0\n  site         U32, U32         the module's number in the program and the site's ordinal\n  name         str              \"print\"\n  status       I32              the status that the host returned\n  request      blob             the bytes printed\nevent 3, outcome:\n  status       I32              0 to 5\n  fault        opt(str)         the fault record, as a length and its bytes\n  consumed     I64              the fuel consumed, 0 when the entry did not run\n  result       opt(tagged)      the value returned\n  error        opt(error)       the error returned\n  outputs      U32              0\n  state-hash   opt(digest)      the state hash after the entry\n  allowance    I64              the fuel allowance at the end, or -1 for none\nerror:\n  set          str              the error set's qualified name\n  tag          U64              the error value's tag, from 1\nevent 4, clear:\n  record       digest           SHA-256 of the fault record cleared\nevent 5, checkpoint:\n  state-hash   digest           the state hash of the checkpoint taken\nevent 6, restore:\n  state-hash   digest           the state hash of the checkpoint restored\n  next-buffer  U64 "
  },
  {
   "id": "spec-01p:events-p2",
   "edition": "SPEC-01P.2",
   "title": "8.4 Events (part 3)",
   "clauses": "H-14 M-11",
   "url": "/specifications/spec-01p/2/#events",
   "internal": 0,
   "content": "**Constraints**\n\n1. Events come in this order: an entry, then its effects and dispatch events in the order they happened, then its outcome. Effect, dispatch and outcome events occur only inside an entry, and the other events only outside one. A dispatch event occurs only at dispatch density [SPEC-03P.1 H-14].\n2. In an entry event, the program entry has an empty module, an empty function and no arguments. Arguments are values of `Bool`, `I8` to `I64` or `U8` to `U64` [SPEC-03P.1 H-14].\n3. The statuses of an outcome are 0 `CINT_OK` and 1 `CINT_FAULT`, for an entry that ran, and 2 `CINT_REFUSED`, 3 `CINT_BUSY`, 4 `CINT_FAULTED` and 5 `CINT_RESOURCE`, for one that did not. An outcome fits its entry [SPEC-03P.1 H-14]:\n   - for an entry that ran, the state hash is present; the fault record is present exactly when the status is 1; a result and an error are never both present, and neither is present with status 1; the allowance is the entry's fuel budget, or a lower budget of at least 0 that an interrupt set; and the fuel consumed is at most the allowance when the allowance is not -1;\n   - for an entry that did not run, the state hash, the result and the error are absent, the fuel consumed is 0, the allowance is the entry's fuel budget, and a fault record is present only with status 5.\n4. After an outcome with status 5 the next event is the end, with reason 1, and an end with reason 1 occurs only there [SPEC-03P.1 H-14].\n5. A restore event's state hash is the state hash of its checkpoint, and each counter it records is at least the checkpoint's [SPEC-03P.1 H-14, M-11].\n6. The count of the end event equals the number of events before it [SPEC-03P.1 H-14].\n\n**Semantics**"
  },
  {
   "id": "spec-01p:events-p3",
   "edition": "SPEC-01P.2",
   "title": "8.4 Events (part 4)",
   "clauses": "H-14 H-19b",
   "url": "/specifications/spec-01p/2/#events",
   "internal": 0,
   "content": "7. An effect's request is the bytes that its print statement wrote. The concatenation of the requests of an entry's effects is what the entry printed, including the bytes printed before a fault [SPEC-03P.1 H-14].\n8. A revision event records a change of the context's program to another revision between entries, with that revision's code, so that a replay applies it [SPEC-03P.1 H-14, H-19b].\n\n**Examples**\n\n9. The events of the case of `ledger.ci`: the program entry, its one print and its outcome, a fault; then the end. The 151 bytes of the fault record are those of 6.2."
  },
  {
   "id": "spec-01p:events-p4",
   "edition": "SPEC-01P.2",
   "title": "8.4 Events (part 5)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#events",
   "internal": 0,
   "content": "| Offset | Bytes | Field |\n|---:|---|---|\n| 0 | `01` | event: entry |\n| 1 | `01 00 00 00 00 00 00 00` | sequence 1 |\n| 9 | `01` | form: the program entry |\n| 10 | `00 00 00 00` | module: empty |\n| 14 | `00 00 00 00` | function: empty |\n| 18 | `00 00 00 00` | no arguments |\n| 22 | `ff ff ff ff ff ff ff ff` | fuel budget: none |\n| 30 | `00 01 00 00 00 00 00 00` | call-depth limit 256 |\n| 38 | `00 00 00 01 00 00 00 00` | frame-arena capacity 16777216 |\n| 46 | `00 00 00 00` | inputs 0 |\n| 50 | `02` | event: effect |\n| 51 | `00 00 00 00 00 00 00 00` | ordinal 0 |\n| 59 | `00 00 00 00` | site: module 0 |\n| 63 | `03 00 00 00` | site: ordinal 3 |\n| 67 | `05 00 00 00` | name, length 5 |\n| 71 | `\"print\"` | name |\n| 76 | `00 00 00 00` | status 0 |\n| 80 | `08 00 00 00 00 00 00 00` | request, length 8 |\n| 88 | `72 65 73 74 20 37 30 0a` | request: `rest 70` and a line feed |\n| 96 | `03` | event: outcome |\n| 97 | `01 00 00 00` | status 1, `CINT_FAULT` |\n| 101 | `01` | fault record: present |\n| 102 | `97 00 00 00` | fault record, length 151 |\n| 106 | (151 bytes) | fault record (6.2) |\n| 257 | `03 00 00 00 00 00 00 00` | fuel consumed 3 |\n| 265 | `00` | result: absent |\n| 266 | `00` | error: absent |\n| 267 | `00 00 00 00` | outputs 0 |\n| 271 | `01` | state hash: present |\n| 272 | (32 bytes) | state hash after the entry |\n| 304 | `ff ff ff ff ff ff ff ff` | allowance: none |\n| 312 | `08` | event: end |\n| 313 | `00` | reason: closed by the host |\n| 314 | (32 bytes) | head of the digest chain |\n| 346 | `03 00 00 00 00 00 00 00` | 3 events before it |"
  },
  {
   "id": "spec-01p:digest-chain",
   "edition": "SPEC-01P.2",
   "title": "8.5 Digest chain",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#digest-chain",
   "internal": 0,
   "content": "### 8.5 Digest chain\n\nThe digest chain folds the state hash of every boundary into one digest, so that two recordings with equal chains passed through equal states with equal fault records.\n\n**Syntax**\n\n```text\nD_0 = SHA-256( \"cint-core-1/recording-chain/v1\", the state hash of the initial checkpoint )\nD_k = SHA-256( \"cint-core-1/recording-chain/v1\", D_(k-1), boundary_k )\nboundary:\n  entry        U64              the index of the boundary's entry event, counting events from 0\n  kind         U8               0 the end of an entry, 1 a dispatch\n  dispatch     opt(I64)         the dispatch number\n  state-hash   digest           the state hash at the boundary\n  fault        opt(str)         the fault record, as a length and its bytes\n```\n\nThe domain string enters each digest as a `str`, its length then its bytes.\n\n**Constraints**\n\n1. Each entry that ran, with status 0 or 1, adds one boundary of kind 0 at its outcome, with the outcome's state hash and fault record. An entry that did not run adds none.\n2. A dispatch event adds a boundary of kind 1 with its number and state hash and no fault record, unless the outcome of its entry follows it directly with the same state hash. That outcome's boundary of kind 0 then carries the dispatch number, and the dispatch adds no boundary of its own.\n3. The head of the chain is the last `D_k`, and the end event holds it.\n\n**Notes**\n\n4. The chain detects a difference at a boundary. A difference that appears and disappears between two boundaries leaves the chain unchanged. Annex A.4 recomputes the chain of the case of `ledger.ci`."
  },
  {
   "id": "spec-01p:cases",
   "edition": "SPEC-01P.2",
   "title": "8.6 Cases",
   "clauses": "H-14b",
   "url": "/specifications/spec-01p/2/#cases",
   "internal": 0,
   "content": "### 8.6 Cases\n\nA case is a recording that carries its program's source text, so that the debug tools can show the source of every position in it.\n\n**Constraints**\n\n1. A case has the domain string `cint-core-1/case/v1` and is in full mode, and every module of its code, and of the code of each revision event, has its source text. A decoder refuses a case without one, or in digest mode [SPEC-03P.1 H-14b].\n\n**Semantics**\n\n2. The format is `CINT-CASE-1`. Apart from its domain string, a case is laid out as a recording [SPEC-03P.1 H-14b].\n\n**Examples**\n\n3. `cint debug locate` runs a program on the interpreter and saves the run as a case. `cint debug replay` decodes the case, replays it, compares each boundary with the recording and prints the case's revision, its source-map digest, the head of its digest chain and the final state hash:\n\n```console\n$ cint debug locate ledger.ci --save-case ledger.case --out dbg\nprogram    ledger.ci   evaluator cpu-sir-interp, recorded as the case ledger.case\ntarget     boundary 1 of 1, the program entry: the first fault, reproduced by replay\n...\n$ cint debug replay ledger.case\ncase       ledger.case   1 boundary   3 events   mode full   density entry\nrevision   359672553c501187e1e53e4878d6ede8f1994b52ce0c64c8f3ec4fbdf3f9b3db\nsource-map 8c97a22e8332385f6b94e1782030208003280b8e6859b1775f2a93caa402e87e\nboundary  event  entry                          outcome                  fuel\n       1      2  the program entry              faulted E_NARROW         3\nreplay     ok, 1 of 1 boundary compared with the recording\nchain      e54344d0fb4bcc2af778845380e8b60127eb639189fad8b9df78e45b60c34795\nstate      6699607c6fabf35dc4931ef60208e1fdf6cde9838caf325470be34ce0807a279\n```"
  },
  {
   "id": "spec-01p:cases-p1",
   "edition": "SPEC-01P.2",
   "title": "8.6 Cases (part 2)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#cases",
   "internal": 0,
   "content": "4. The revision is the one in the report of 6.2, recomputed by the interpreter from the SIR text in the case. The chain line is the head of the digest chain, and the state line the state hash after the entry, both as the end and outcome events of 8.4 hold them."
  },
  {
   "id": "spec-01p:decoding-a-recording",
   "edition": "SPEC-01P.2",
   "title": "8.7 Decoding a recording",
   "clauses": "H-14 H-17a",
   "url": "/specifications/spec-01p/2/#decoding-a-recording",
   "internal": 0,
   "content": "### 8.7 Decoding a recording\n\n**Constraints**\n\n1. A decoder checks a whole recording before any part of it is used, and refuses it entirely when a check fails [SPEC-03P.1 H-14, H-17a]:\n   - the header (8.2), the code (8.3), the initial checkpoint (7.5) and every checkpoint of a restore event;\n   - that the revision of the initial checkpoint is the revision of the header;\n   - the source-map digest of the header and of each revision event against its code;\n   - the order and fields of every event (8.4), and each outcome against its entry;\n   - the digest chain and the event count against the end event;\n   - that the file ends with the end event: a file without one is incomplete and is never loaded in part."
  },
  {
   "id": "spec-01p:revision-identity",
   "edition": "SPEC-01P.2",
   "title": "9.1 Revision identity",
   "clauses": "H-15 IM-157 SIR-17",
   "url": "/specifications/spec-01p/2/#revision-identity",
   "internal": 0,
   "content": "### 9.1 Revision identity\n\nThe revision identity of a program names its meaning under one runtime contract. It is computed from the program's SIR text with every source position removed, so it changes when the program's operations change and not when only their positions do.\n\n**Syntax**\n\n```text\nrevision = SHA-256(\n  \"cint-core-1/revision/v1\"      str\n  \"cint-core-1\"                  str, the profile\n  contract                       str, the runtime contract version\n  modules                        U32, the number of modules\n  for each module, in the byte order of its path:\n    path                         str, the module-relative path, UTF-8\n    text                         blob, the module's position-free SIR text\n)\n```\n\n**Semantics**\n\n1. The *position-free SIR text* of a module is its SIR text with its `sites` line and every position annotation removed, and its site ordinals kept; SPEC-09P.1 6.5 states the rule [SPEC-09P.1 SIR-17].\n2. <a id=\"IM-157\"></a>The revision of a program is the digest above, over the root module and every module it imports. It is computed over the program's meaning, not over its source formatting, and not over an executable or a kernel binary [IM-157] [SPEC-09P.1 SIR-17].\n3. This one value is the revision of fault records (6.1), of state (7.2), of checkpoints and of recordings and cases (8.2). There is no second digest of a program's code [IM-157] [SPEC-03P.1 H-15].\n4. The runtime contract version is an input: rebuilding an unchanged program against another runtime contract version changes its revision, and so the state hash of each of its states [IM-157] [SPEC-03P.1 H-15].\n5. The fuel model is not an input of the revision; it is a separate input of execution identity (9.3) [SPEC-09P.1 SIR-17].\n\n**Notes**"
  },
  {
   "id": "spec-01p:revision-identity-p1",
   "edition": "SPEC-01P.2",
   "title": "9.1 Revision identity (part 2)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#revision-identity",
   "internal": 0,
   "content": "6. Adding a comment, a blank line or a space or moving a function, changes positions and leaves the revision unchanged. Reordering two statements, or adding an operation that can fault, changes the site ordinals and therefore the revision."
  },
  {
   "id": "spec-01p:source-map-digest",
   "edition": "SPEC-01P.2",
   "title": "9.2 Source-map digest",
   "clauses": "SIR-17",
   "url": "/specifications/spec-01p/2/#source-map-digest",
   "internal": 0,
   "content": "### 9.2 Source-map digest\n\nThe source-map digest records the positions that the revision leaves out: with it, a site ordinal in a recording can be traced to a line and column.\n\n**Semantics**\n\n1. The source-map digest of a program is a SHA-256 digest over the `sites` line of each module's SIR text, which lists every site's ordinal, line, column and operation; SPEC-09P.1 6.5 states the rule and its bytes [SPEC-09P.1 SIR-17].\n2. Every executor computes the source-map digest from the same SIR text, so every executor gets the same value. A recording holds it in its header and in each revision event (8.2) [SPEC-09P.1 SIR-17]."
  },
  {
   "id": "spec-01p:execution-identity",
   "edition": "SPEC-01P.2",
   "title": "9.3 Execution identity",
   "clauses": "H-14 IM-159",
   "url": "/specifications/spec-01p/2/#execution-identity",
   "internal": 0,
   "content": "### 9.3 Execution identity\n\nThe execution identity of an entry is the canonical form of everything that decides its outcome.\n\n**Semantics**\n\n1. The execution identity of an entry is the tuple of its semantic inputs, from the profile and the fuel model to its frame-arena capacity; SPEC-04P.2 8.2 states the rule [SPEC-04P.2 IM-159].\n2. A recording holds each of these in canonical form: the header holds the profile, the fuel model, the revision and the source-map digest; the entry event holds the entry, its arguments as tagged values and its three limits; the state hash before the entry is the state hash of the boundary or checkpoint before it; and each effect event holds the status that the host supplied for the effect [SPEC-04P.2 IM-159] [SPEC-03P.1 H-14].\n3. SPEC-04P.2 8.2 states what two entries with equal execution identity agree on: their output, their fault record, their fuel consumed and the state they leave."
  },
  {
   "id": "spec-01p:what-never-enters-an-identity",
   "edition": "SPEC-01P.2",
   "title": "9.4 What never enters an identity",
   "clauses": "H-15 IM-151 IM-157",
   "url": "/specifications/spec-01p/2/#what-never-enters-an-identity",
   "internal": 0,
   "content": "### 9.4 What never enters an identity\n\n**Semantics**\n\n1. The revision depends only on the profile, the runtime contract version and the position-free SIR text of each module with its module-relative path. The directory a tool runs in, the absolute path of a file, the time, the time zone, the locale, the environment, the executor, the C compiler and the host do not enter it [IM-157] [SPEC-03P.1 H-15].\n2. The build identity, the payload digest and the build record digest are separate fields of the checkpoint envelope; they enter neither the revision nor the state hash. Executables of one program built for different executors or machines, under one runtime contract version, have one revision [SPEC-03P.1 H-15].\n3. State holds no time, locale, path outside a module-relative path, native address, thread identifier or backend name, so neither does a state hash [IM-151].\n\n**Examples**\n\n4. A comment line moves every position of `ledger.ci` down one line. `moved/ledger.ci` is that program, and a run from another directory, with another time zone and locale, sees the same program:\n\n```console\n$ cat moved/ledger.ci\n// A ledger with one account.\nI64 balance = 100;\n\nvoid withdraw(I64 amount) {\n    balance -= amount;\n    U8 rest = balance as U8;\n    \"rest {rest}\\n\";\n}\n\nvoid main() {\n    withdraw(30);\n    withdraw(80);\n}\n$ cint run moved/ledger.ci\nrest 70\nfault[E_NARROW]: the value does not fit the destination type\n  --> ledger.ci:6:23\n...\n   = revision: 359672553c501187e1e53e4878d6ede8f1994b52ce0c64c8f3ec4fbdf3f9b3db\n...\n$ cd moved && TZ=Asia/Tokyo LC_ALL=C cint run ../ledger.ci\nrest 70\nfault[E_NARROW]: the value does not fit the destination type\n  --> ledger.ci:5:23\n...\n   = revision: 359672553c501187e1e53e4878d6ede8f1994b52ce0c64c8f3ec4fbdf3f9b3db\n...\n```"
  },
  {
   "id": "spec-01p:what-never-enters-an-identity-p1",
   "edition": "SPEC-01P.2",
   "title": "9.4 What never enters an identity (part 2)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#what-never-enters-an-identity",
   "internal": 0,
   "content": "5. All three runs have the revision of 6.2. The source map of the moved program differs, and so does the state hash after its fault, whose record holds line 6:\n\n```console\n$ cint debug locate moved/ledger.ci --save-case moved.case --out dbg-moved\nprogram    moved/ledger.ci   evaluator cpu-sir-interp, recorded as the case moved.case\n...\n$ cint debug replay moved.case\ncase       moved.case   1 boundary   3 events   mode full   density entry\nrevision   359672553c501187e1e53e4878d6ede8f1994b52ce0c64c8f3ec4fbdf3f9b3db\nsource-map 9468edf527b220f336c50ae1bc85e775c1d5de45f9665d014a75f270735f8360\nboundary  event  entry                          outcome                  fuel\n       1      2  the program entry              faulted E_NARROW         3\nreplay     ok, 1 of 1 boundary compared with the recording\nchain      e0fb9977a7d7e4e0fe9b16a25442582caa4931e0db53cf2330f7b30e07dfbd2f\nstate      3db1185b4fd68a6cf49fa7d99016e839dd3d9fe53076d3c59660def4db41c2ce\n```\n\n**Notes**\n\n6. A fault record holds module-relative paths, so the directory from which a program runs does not change it."
  },
  {
   "id": "spec-01p:future-directions",
   "edition": "SPEC-01P.2",
   "title": "10 Future directions",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#future-directions",
   "internal": 0,
   "content": "## 10 Future directions\n\nThis clause is informative. It lists encodings that the design of cint names and that cint 0.2.0 does not write; none of them is a rule of this edition.\n\n1. **Arguments and supplied effects as digests.** An entry's arguments, with the full contents of any array a host lends, encoded under `cint-core-1/args/v1` and hashed, and a digest of what the host supplied to the entry, so that an execution identity is a short tuple of digests.\n2. **View identities in fault records.** A tag for the identity of a view, with its buffer, generation, shape, strides and permission and none of its contents, so that the record of a reduction can name the view it read.\n3. **Fixed-point globals.** A module-level variable of a fixed-point type as a global of state, with the tag `31`.\n4. **Build digests.** The payload digest, the build record digest and the build identity of a checkpoint's envelope and of a recording, written and checked.\n5. **Fuller recordings.** Digest mode that records digests of the contents of lent buffers instead of the contents; input and output records; registration and release events; a state-hash interval above 1.\n6. **A tree state hash.** A state hash built from digests of fixed-size chunks of each buffer, so that a device can hash its own memory and transfer only digests.\n7. **Migrations.** A checkpoint restored into another revision of its program through a migration that the program declares, recorded as an event.\n8. **`U1024`.** An unsigned 1024-bit type, with its own tag."
  },
  {
   "id": "spec-01p:worked-encodings",
   "edition": "SPEC-01P.2",
   "title": "Annex A (informative) Worked encodings",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#worked-encodings",
   "internal": 0,
   "content": "## Annex A (informative) Worked encodings"
  },
  {
   "id": "spec-01p:tagged-values-2",
   "edition": "SPEC-01P.2",
   "title": "A.1 Tagged values",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#tagged-values-2",
   "internal": 0,
   "content": "### A.1 Tagged values\n\n| Value | Tagged bytes |\n|---|---|\n| `Bool` `true` | `01 01` |\n| `I8` -1 | `11 ff` |\n| `I16` 1000 | `12 e8 03` |\n| `I32` -2 | `13 fe ff ff ff` |\n| `I64` -2 | `14 fe ff ff ff ff ff ff ff` |\n| `I64` 1000 | `14 e8 03 00 00 00 00 00 00` |\n| `U8` 255 | `21 ff` |\n| `U16` 65535 | `22 ff ff` |\n| `I128` 2^64 | `15 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00` |\n| `U128` 1 | `25 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00` |\n| `Q16.16` 1.5 | `31 13 10 00 00 80 01 00` |\n| `Q8.8` -0.5 | `31 12 08 00 80 ff` |\n| Z 0 | `0f 00 00 00 00` |\n| Z -1 | `0f 01 00 00 00 ff` |\n| Z 9223372036854775808 | `0f 09 00 00 00 00 00 00 00 00 00 00 80 00` |\n| `I8[3]` {120, 120, -120} | `51 11 01 03 00 00 00 00 00 00 00 78 78 88` |\n| `U8[2, 2]` {{1, 2}, {3, 4}} | `51 21 02 02 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 01 02 03 04` |"
  },
  {
   "id": "spec-01p:a-struct-with-nested-structs-and-an-array-field",
   "edition": "SPEC-01P.2",
   "title": "A.2 A struct with nested structs and an array field",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#a-struct-with-nested-structs-and-an-array-field",
   "internal": 0,
   "content": "### A.2 A struct with nested structs and an array field\n\n1. This program has module-level variables of five kinds:\n\n```cint st.ci\nstruct Pt { I32 x; I32 y; }\nstruct Seg { Pt a; Pt b; I8[2] tag; }\nI64 total = 3;\nBool ready = true;\nI128 big = 18446744073709551616;\nU8[2, 2] grid = [[1, 2], [3, 4]];\nSeg s = Seg(a = Pt(x = 1, y = 2), b = Pt(x = 3, y = 4), tag = [7, 8]);\n\nvoid main() {\n    total += 1;\n    \"{total}\\n\";\n}\n```\n\n```text\n4\n```\n\n2. In the state before `main` runs, the globals are in the byte order of their names: `st.big`, `st.grid`, `st.ready`, `st.s`, `st.total`. The value of `st.s` lists `Pt`, which `Seg` uses, before `Seg`:"
  },
  {
   "id": "spec-01p:a-struct-with-nested-structs-and-an-array-field-p1",
   "edition": "SPEC-01P.2",
   "title": "A.2 A struct with nested structs and an array field (part 2)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#a-struct-with-nested-structs-and-an-array-field",
   "internal": 0,
   "content": "| Offset | Bytes | Field |\n|---:|---|---|\n| 0 | `71` | tag: struct |\n| 1 | `02 00 00 00` | 2 definitions |\n| 5 | `71` | definition 0 |\n| 6 | `05 00 00 00` | name, length 5 |\n| 10 | `\"st.Pt\"` | name |\n| 15 | `00` | layout |\n| 16 | `02 00 00 00` | 2 fields |\n| 20 | `01 00 00 00` | field name, length 1 |\n| 24 | `\"x\"` | field name |\n| 25 | `00` | bit width |\n| 26 | `13` | field type `I32` |\n| 27 | `01 00 00 00` | field name, length 1 |\n| 31 | `\"y\"` | field name |\n| 32 | `00` | bit width |\n| 33 | `13` | field type `I32` |\n| 34 | `71` | definition 1 |\n| 35 | `06 00 00 00` | name, length 6 |\n| 39 | `\"st.Seg\"` | name |\n| 45 | `00` | layout |\n| 46 | `03 00 00 00` | 3 fields |\n| 50 | `01 00 00 00` | field name, length 1 |\n| 54 | `\"a\"` | field name |\n| 55 | `00` | bit width |\n| 56 | `71 00 00 00 00` | field type: definition 0 |\n| 61 | `01 00 00 00` | field name, length 1 |\n| 65 | `\"b\"` | field name |\n| 66 | `00` | bit width |\n| 67 | `71 00 00 00 00` | field type: definition 0 |\n| 72 | `03 00 00 00` | field name, length 3 |\n| 76 | `\"tag\"` | field name |\n| 79 | `00` | bit width |\n| 80 | `52 11 01` | field type: array of `I8`, rank 1 |\n| 83 | `01 ff ff ff ff 02 00 00 00 00 00 00 00` | extent 2 |\n| 96 | `71 01 00 00 00` | the type: definition 1 |\n| 101 | `01 00 00 00 02 00 00 00` | payload: `a.x` 1, `a.y` 2 |\n| 109 | `03 00 00 00 04 00 00 00` | payload: `b.x` 3, `b.y` 4 |\n| 117 | `07 08` | payload: `tag` 7, 8 |"
  },
  {
   "id": "spec-01p:a-checkpoint-with-an-arena-and-a-pool",
   "edition": "SPEC-01P.2",
   "title": "A.3 A checkpoint with an arena and a pool",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#a-checkpoint-with-an-arena-and-a-pool",
   "internal": 0,
   "content": "### A.3 A checkpoint with an arena and a pool\n\n1. A workbench session declares a pool and an arena, takes a handle into each and checkpoints the result:\n\n```console\n$ cint workbench --echo --out wb\ncint workbench   profile cint-core-1   backend cpu-sir-interp   new session\nci[1]> Pool(I64, 4) pool;\npool : not shown by the session (it shows integers, Bool, and arrays of them)\nci[2]> Arena(I32, 8) ar;\nar : not shown by the session (it shows integers, Bool, and arrays of them)\nci[3]> Handle(I64) h;\nh : not shown by the session (it shows integers, Bool, and arrays of them)\nci[4]> Handle(I32[]) a;\na : not shown by the session (it shows integers, Bool, and arrays of them)\nci[5]> void setup() { h = pool.insert(7); a = ar.alloc(3); ar[a][1] = 5; }\nsetup : () -> void   revision session@r5\nci[6]> setup();\nci[7]> :checkpoint one\ncheckpoint one   #1   bindings 2   revisions: session@r5\nci[7]> :save saved\nsaved session to saved   entries 6   checkpoints 1   objects 29\nci[7]> :quit --yes\n```\n\n2. The saved session keeps each object in a file named by the SHA-256 of its bytes. One of them is the checkpoint `one`, 481 bytes. Its state, from the global count on, is these bytes:"
  },
  {
   "id": "spec-01p:a-checkpoint-with-an-arena-and-a-pool-p1",
   "edition": "SPEC-01P.2",
   "title": "A.3 A checkpoint with an arena and a pool (part 2)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#a-checkpoint-with-an-arena-and-a-pool",
   "internal": 0,
   "content": "| Offset | Bytes | Field |\n|---:|---|---|\n| 0 | `02 00 00 00 00 00 00 00` | 2 globals |\n| 8 | `09 00 00 00` | name, length 9 |\n| 12 | `\"session.a\"` | name |\n| 21 | `75` | tag: handle |\n| 22 | `00 00 00 00 00 00 00 00` | slot 0 |\n| 30 | `03 00 00 00 00 00 00 00` | length 3 |\n| 38 | `00 00 00 00 00 00 00 00` | generation 0 |\n| 46 | `01 00 00 00` | container: arena 1 |\n| 50 | `01` | kind: arena |\n| 51 | `09 00 00 00` | name, length 9 |\n| 55 | `\"session.h\"` | name |\n| 64 | `75` | tag: handle |\n| 65 | `00 00 00 00 00 00 00 00` | slot 0 |\n| 73 | `01 00 00 00 00 00 00 00` | length 1 |\n| 81 | `00 00 00 00 00 00 00 00` | generation 0 |\n| 89 | `01 00 00 00` | container: pool 1 |\n| 93 | `02` | kind: pool |\n| 94 | `5e 00 00 00 00 00 00 00` | arena block, length 94 |\n| 102 | `14 00 00 00` | domain string, length 20 |\n| 106 | `\"cint-core-1/arena/v2\"` | domain string |\n| 126 | `01 00 00 00 00 00 00 00` | 1 arena |\n| 134 | `01 00 00 00` | id 1 |\n| 138 | `00 00 00 00` | parent: none |\n| 142 | `00` | not retired |\n| 143 | `00 00 00 00 00 00 00 00` | offset 0 |\n| 151 | `08 00 00 00 00 00 00 00` | capacity 8 |\n| 159 | `03 00 00 00 00 00 00 00` | used 3 |\n| 167 | `00 00 00 00 00 00 00 00` | generation 0 |\n| 175 | `04 00 00 00` | element width 4 |\n| 179 | `00 00 00 00` | no definitions |\n| 183 | `13` | element type `I32` |\n| 184 | `00 00 00 00 05 00 00 00 00 00 00 00` | elements 0, 5, 0 |\n| 196 | `5d 00 00 00 00 00 00 00` | pool block, length 93 |\n| 204 | `13 00 00 00` | domain string, length 19 |\n| 208 | `\"cint-core-1/pool/v2\"` | domain string |\n| 227 | `01 00 00 00 00 00 00 00` | 1 pool |\n| 235 | `01 00 00 00` | id 1 |\n| 239 | `08 00 00 00` | element width 8 |\n| 243 | `00 00 00 00` | no definitions |\n| 247 | `14` | element type `I64` |\n| 248 | `04 00 00 00 00 00 00 00` | capacity 4 |\n| 256 | `01 00 00 00 00 00 00 00` | 1 slot used |\n| 264 | `00 00 00 00 00 00 00 00` | free list: empty |\n"
  },
  {
   "id": "spec-01p:a-checkpoint-with-an-arena-and-a-pool-p2",
   "edition": "SPEC-01P.2",
   "title": "A.3 A checkpoint with an arena and a pool (part 3)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#a-checkpoint-with-an-arena-and-a-pool",
   "internal": 0,
   "content": "3. The arena holds the three elements that `ar.alloc(3)` took, the second set to 5; the pool's one used slot holds 7. A session entry that is a declaration is not an entry of the context, so one entry, the call of `setup`, has begun."
  },
  {
   "id": "spec-01p:recomputing-the-digest-chain",
   "edition": "SPEC-01P.2",
   "title": "A.4 Recomputing the digest chain",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#recomputing-the-digest-chain",
   "internal": 0,
   "content": "### A.4 Recomputing the digest chain\n\n1. This Python program reads a case or a recording at entry density whose entries all ran, recomputes its digest chain from the rules of 8.5, and prints the head:\n\n```python chain.py\nimport hashlib, struct, sys\n\ndef u(d, at, n): return int.from_bytes(d[at:at + n], \"little\"), at + n\ndef s(d, at): n, at = u(d, at, 4); return d[at:at + n], at + n\ndef b(d, at): n, at = u(d, at, 8); return d[at:at + n], at + n\ndef frame(t): return struct.pack(\"<I\", len(t)) + t\nDOMAIN = frame(b\"cint-core-1/recording-chain/v1\")"
  },
  {
   "id": "spec-01p:recomputing-the-digest-chain-p1",
   "edition": "SPEC-01P.2",
   "title": "A.4 Recomputing the digest chain (part 2)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#recomputing-the-digest-chain",
   "internal": 0,
   "content": "d = open(sys.argv[1], \"rb\").read()\nat = 0\nfor _ in range(4): _, at = s(d, at)        # domain, profile, fuel model, contract\nat += 32                                    # revision\nat += 1 + 32 * d[at]                        # source-map digest\nat += 1 + 8 + 1                             # mode, interval, density\nmods, at = u(d, at, 4)\nfor _ in range(mods):\n    _, at = s(d, at)\n    _, at = b(d, at)\n    at += 1 + (8 + u(d, at + 1, 8)[0] if d[at] else 0)\nckpt, at = b(d, at)\nc = 4 + len(b\"cint-core-1/checkpoint/v1\")\n_, c = s(ckpt, c)\nc += 3                                      # three absent digests\nstate, c = b(ckpt, c)\nchain = hashlib.sha256(DOMAIN + hashlib.sha256(state).digest()).digest()\nindex = entry = 0\nwhile True:\n    kind = d[at]; at += 1\n    if kind == 1:\n        entry = index\n        at += 8 + 1\n        _, at = s(d, at); _, at = s(d, at)\n        n, at = u(d, at, 4)\n        assert n == 0\n        at += 24 + 4\n    elif kind == 2:\n        at += 8 + 8\n        _, at = s(d, at)\n        at += 4\n        _, at = b(d, at)\n    elif kind == 3:\n        at += 4\n        fault = None\n        if d[at]:\n            fault, at = s(d, at + 1)\n        else:\n            at += 1\n        at += 8 + 1 + 1 + 4\n        assert d[at] == 1\n        h = d[at + 1:at + 33]; at += 33 + 8\n        rec = struct.pack(\"<Q\", entry) + b\"\\x00\\x00\" + h\n        rec += b\"\\x00\" if fault is None else b\"\\x01\" + frame(fault)\n        chain = hashlib.sha256(DOMAIN + chain + rec).digest()\n    elif kind == 8:\n        assert d[at + 1:at + 33] == chain\n        break\n    index += 1\nprint(chain.hex())\n```\n\n2. On the case of 8.6 it prints the chain that `cint debug replay` prints:\n\n```console\n$ python3 chain.py ledger.case\ne54344d0fb4bcc2af778845380e8b60127eb639189fad8b9df78e45b60c34795\n```"
  },
  {
   "id": "spec-01p:operation-fixtures-cif-1",
   "edition": "SPEC-01P.2",
   "title": "Annex B (normative) Operation fixtures, CIF-1",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#operation-fixtures-cif-1",
   "internal": 0,
   "content": "## Annex B (normative) Operation fixtures, CIF-1"
  },
  {
   "id": "spec-01p:format",
   "edition": "SPEC-01P.2",
   "title": "B.1 Format",
   "clauses": "IM-168 IM-169",
   "url": "/specifications/spec-01p/2/#format",
   "internal": 0,
   "content": "### B.1 Format\n\nAn operation fixture tests one operation on given operands, with no program around it. A file of fixtures in the format CIF-1 lists them, one a line.\n\n**Syntax**\n\n| Key | Content |\n|---|---|\n| `id` | The fixture's identifier, unique in its file, such as `div.checked.i64.007`. |\n| `status` | `\"S\"`. |\n| `op` | The operation identifier, with its rounding mode when the operation rounds. |\n| `args` | An array of typed values, the operands in order. |\n| `expect` | Exactly one of `{\"value\": typed value}`, `{\"fault\": fault}`, `{\"compile_error\": code}` and `{\"reject\": true}`. |\n| `derivation` | Optional: a string that says how the expected result was derived. |\n\nA typed value is `{\"t\": type, \"v\": integer}`, such as `{\"t\": \"I64\", \"v\": \"-7\"}`; a fixed-point value is `{\"t\": type, \"raw\": integer}`, its raw value, such as `{\"t\": \"Q16.16\", \"raw\": \"98304\"}`; an array is `{\"t\": \"I8[3]\", \"v\": [\"120\", \"120\", \"-120\"]}`. A fault is an object with the key `code` and, when the fixture asserts them, `exact`, `limit`, `index` and `operands`.\n\n**Constraints**\n\n1. <a id=\"IM-168\"></a>A CIF-1 file is JSON Lines: UTF-8, one JSON object a line, each line ended by a line feed, with the keys in the order of the table [IM-168].\n2. Every integer is a JSON string of decimal digits with an optional leading `-`, so that no JSON reader loses precision; RFC 8259 notes that JSON numbers are interchangeable exactly only between -(2^53 - 1) and 2^53 - 1 [IM-168].\n3. <a id=\"IM-169\"></a>A fault object has `code` and, when the record has them, `exact`, `limit`, `index` (for `fold_checked`) and `operands` (an array of typed values) [IM-169].\n\n**Semantics**"
  },
  {
   "id": "spec-01p:format-p1",
   "edition": "SPEC-01P.2",
   "title": "B.1 Format (part 2)",
   "clauses": "IM-167 IM-170",
   "url": "/specifications/spec-01p/2/#format",
   "internal": 0,
   "content": "4. <a id=\"IM-167\"></a>Each fixture maps to a program: one that declares the operands with their types, applies the operation once, and whose expected outcome has the same operation identifier, fault code, operands, `exact` and `limit` [IM-167].\n5. <a id=\"IM-170\"></a>A fixture is frozen once published. A change of meaning takes a new group of fixtures under a new profile, never an edit; a change of encoding with the same content takes a new version of the format, and fixtures of the old version stay valid in it [IM-170].\n6. Every implementation, the reference included, produces the expected result of every fixture. The reference computes in Python with exact integers and fractions and shares no code with the C implementation [IM-170].\n\n**Examples**\n\n7. Four fixtures, the third of fixed point and the fourth of `fold_checked`, which faults at index 1 when the running sum 120 + 120 leaves `I8`:\n\n```console\n$ cat sample.cif1.jsonl\n{\"id\":\"add.checked.i64.001\",\"status\":\"S\",\"op\":\"add.checked.i64\",\"args\":[{\"t\":\"I64\",\"v\":\"9223372036854775807\"},{\"t\":\"I64\",\"v\":\"1\"}],\"expect\":{\"fault\":{\"code\":\"E_OVERFLOW\",\"exact\":\"9223372036854775808\",\"limit\":\"9223372036854775807\"}}}\n{\"id\":\"rem.checked.i64.003\",\"status\":\"S\",\"op\":\"rem.checked.i64\",\"args\":[{\"t\":\"I64\",\"v\":\"7\"},{\"t\":\"I64\",\"v\":\"-2\"}],\"expect\":{\"value\":{\"t\":\"I64\",\"v\":\"-1\"}}}\n{\"id\":\"mul.checked.q16_16.002\",\"status\":\"S\",\"op\":\"mul.checked.q16_16.half_even\",\"args\":[{\"t\":\"Q16.16\",\"raw\":\"1\"},{\"t\":\"Q16.16\",\"raw\":\"98304\"}],\"expect\":{\"value\":{\"t\":\"Q16.16\",\"raw\":\"2\"}}}\n{\"id\":\"fold_checked.add.i8.001\",\"status\":\"S\",\"op\":\"fold_checked.add.i8\",\"args\":[{\"t\":\"I8\",\"v\":\"0\"},{\"t\":\"I8[3]\",\"v\":[\"120\",\"120\",\"-120\"]}],\"expect\":{\"fault\":{\"code\":\"E_OVERFLOW\",\"exact\":\"240\",\"limit\":\"127\",\"index\":\"1\"}}}\n$ python3 -m cint_ref cif1 sample.cif1.jsonl\ncif1: 4 records, 4 agree, 0 disagree, 0 unsupported, 0 invalid\n```"
  },
  {
   "id": "spec-01p:format-p2",
   "edition": "SPEC-01P.2",
   "title": "B.1 Format (part 3)",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#format",
   "internal": 0,
   "content": "8. The remainder of 7 by -2 is -1, because `%` takes the quotient rounded toward negative infinity (SPEC-04P.2 6.7.7). The `Q16.16` values 2^-16 (raw 1) and 1.5 (raw 98304) have the product 1.5 times 2^-16, the raw value 1.5, which rounds half to even to the raw value 2."
  },
  {
   "id": "spec-01p:clause-index",
   "edition": "SPEC-01P.2",
   "title": "Annex C (informative) Clause index",
   "clauses": "",
   "url": "/specifications/spec-01p/2/#clause-index",
   "internal": 0,
   "content": "## Annex C (informative) Clause index\n\nThe clause identifiers of SPEC-01P.1 and where their rules are in the P editions; an identifier that the table does not list has no rule in them. SPEC-04P.2 sections are given by number; where a clause is split, each part is listed."
  },
  {
   "id": "spec-01p:clause-index-p1",
   "edition": "SPEC-01P.2",
   "title": "Annex C (informative) Clause index (part 2)",
   "clauses": "IM-1 IM-10 IM-100 IM-101 IM-102 IM-103 IM-104 IM-105 IM-106 IM-107 IM-108 IM-11",
   "url": "/specifications/spec-01p/2/#clause-index",
   "internal": 0,
   "content": "| Clauses of SPEC-01P.1 | Where they are now |\n|---|---|\n| <a id=\"IM-1\"></a>IM-1 | SPEC-04P.2 6.1 |\n| IM-2, IM-3 | Not carried: they divided the rules of SPEC-01P.1 between its sections. |\n| <a id=\"IM-4\"></a><a id=\"IM-6\"></a>IM-4, IM-6 | SPEC-04P.2 6.3.1 |\n| <a id=\"IM-5\"></a>IM-5 | SPEC-04P.2 6.2 |\n| <a id=\"IM-7\"></a><a id=\"IM-8\"></a>IM-7, IM-8 | SPEC-04P.2 6.3.1; their encoding part in 5.1 here |\n| <a id=\"IM-9\"></a><a id=\"IM-10\"></a><a id=\"IM-11\"></a>IM-9 to IM-11 | SPEC-04P.2 6.3 |\n| IM-12, IM-13 | SPEC-04P.2 6.3.1 for the types; their bytes in 5.2 here |\n| IM-14 | 5.2 here; the C interface in SPEC-03P.1 |\n| IM-15 | Not carried: it described a layout that `cint-core-1` does not use. |\n| <a id=\"IM-16\"></a>IM-16 to IM-18 | SPEC-04P.2 6.3.1 |\n| <a id=\"IM-19\"></a><a id=\"IM-20\"></a>IM-19, IM-20 | SPEC-04P.2 6.4 |\n| <a id=\"IM-21\"></a><a id=\"IM-22\"></a><a id=\"IM-23\"></a><a id=\"IM-24\"></a><a id=\"IM-25\"></a><a id=\"IM-26\"></a><a id=\"IM-27\"></a>IM-21 to IM-27 | SPEC-04P.2 6.5 and 6.8 |\n| <a id=\"IM-28\"></a><a id=\"IM-29\"></a><a id=\"IM-30\"></a><a id=\"IM-31\"></a><a id=\"IM-32\"></a><a id=\"IM-33\"></a><a id=\"IM-34\"></a>IM-28 to IM-34 | SPEC-04P.2 6.7 |\n| <a id=\"IM-35\"></a><a id=\"IM-36\"></a><a id=\"IM-37\"></a><a id=\"IM-39\"></a><a id=\"IM-40\"></a><a id=\"IM-41\"></a>IM-35 to IM-41 | SPEC-04P.2 6.7 and 7.2 |\n| <a id=\"IM-42\"></a><a id=\"IM-43\"></a><a id=\"IM-44\"></a><a id=\"IM-45\"></a><a id=\"IM-46\"></a><a id=\"IM-47\"></a><a id=\"IM-48\"></a><a id=\"IM-49\"></a>IM-42 to IM-49 | SPEC-04P.2 6.7 |\n| <a id=\"IM-50\"></a>IM-50 | SPEC-04P.2 6.6 |\n| <a id=\"IM-51\"></a><a id=\"IM-52\"></a><a id=\"IM-53\"></a>IM-51 to IM-53 | SPEC-04P.2 7.2 |\n| <a id=\"IM-54\"></a><a id=\"IM-55\"></a><a id=\"IM-56\"></a><a id=\"IM-57\"></a>IM-54 to IM-59 | SPEC-04P.2 6.3.2 |\n| <a id=\"IM-60\"></a><a id=\"IM-61\"></a><a id=\"IM-62\"></a>IM-60 to IM-62 | SPEC-04P.2 6.7 |\n| <a id=\"IM-63\"></a><a id=\"IM-64\"></a>IM-63, IM-64 | SPEC-04P.2 6.7 and 7.2 |\n|"
  },
  {
   "id": "spec-02p:spec-02p-1",
   "edition": "SPEC-02P.1",
   "title": "SPEC-02P.1",
   "clauses": "",
   "url": "/specifications/spec-02p/1/",
   "internal": 0,
   "content": "# SPEC-02P.1: Kernels and executors\n\nSPEC-02P.1, edition 1 of the kernels and executors specification, cint v0.2.0, 2026-10-11."
  },
  {
   "id": "spec-02p:foreword",
   "edition": "SPEC-02P.1",
   "title": "Foreword",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#foreword",
   "internal": 0,
   "content": "## Foreword\n\nThis document specifies what an executor of cint 0.2.0 does to carry out a kernel dispatch, and how each of the three executors of that release does it. It is the companion of SPEC-04P.2, whose clause 6.13 states what a kernel and a dispatch mean to a program.\n\nEach rule ends with one or more clause identifiers in brackets. An identifier, such as F-5 or B-16a, names one rule across editions and documents: a rule keeps its identifier when its text moves to another section or another document, and an identifier is never reused. Code comments, test files and other documents cite rules by these identifiers. Identifiers that begin with `A`, `P` or `X` name rules of kernels, here and in SPEC-04P.2; in SPEC-03P.1 the same letters name rules of the host interface, which are other rules. A rule that another edition states is cited in brackets with that edition's name, such as [SPEC-04P.2 X-1]: the rule is stated there, and this document says what an executor does to keep it. Section numbers belong to this edition only."
  },
  {
   "id": "spec-02p:introduction",
   "edition": "SPEC-02P.1",
   "title": "Introduction",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#introduction",
   "internal": 0,
   "content": "## Introduction\n\nA kernel is written for one point of an iteration space, and a dispatch runs it for every point. SPEC-04P.2 6.13 defines the meaning of a dispatch by a sequential procedure: check the arguments, run the work-items one at a time in ascending order, complete the reductions and publish the outputs only if nothing faulted. An executor that runs work-items in another order, or many at once on a GPU, has to reach the outcome of that procedure by other means: the same output bytes, the same reduction results, the same fuel consumed and, when something faults, the same fault record, down to the work-item and the operation inside it.\n\nThis first example dispatches one kernel. `scale` multiplies each element of `a` by `k`; the program runs it twice:\n\n```cint scale.ci\nkernel scale[n](in I64[n] a, in I64 k, out I64[n] b) over [i: n] {\n    b[i] = a[i] * k;\n}\n\nvoid run() {\n    I64[4] a = [1, -2, 3, 4];\n    I64[4] b;\n    scale(a, 3, b);\n    \"{b[0]} {b[1]} {b[2]} {b[3]}\\n\";\n    a[1] = 4611686018427387904;\n    a[3] = -4611686018427387904;\n    scale(a, 3, b);\n    \"{b[0]} {b[1]} {b[2]} {b[3]}\\n\";\n}\n\nrun();\n```\n\n```text\n3 -6 9 12\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> scale.ci:2:17\n   |\n 2 |     b[i] = a[i] * k;\n   |                 ^ mul.checked.i64\n   |\n   = operation: mul.checked.i64\n   = operand-count: 2\n   = operand: I64 4611686018427387904\n   = operand: I64 3\n   = exact:   13835058055282163712\n   = limit:   I64 9223372036854775807\n   ...\n   = address: scale.scale, dispatch 1, phase 1, work-item 1, step 2\n   ...\n```"
  },
  {
   "id": "spec-02p:introduction-p1",
   "edition": "SPEC-02P.1",
   "title": "Introduction (part 2)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#introduction",
   "internal": 0,
   "content": "In the second dispatch, work-items 1 and 3 both overflow. The fault reported is the one at the lower work-item, 1, whichever an executor meets first. Its address names the kernel `scale` of module `scale`, the second dispatch of the entry (numbered from 0), the work-item phase, work-item 1 and step 2: the place `b[i]` is step 0, the read `a[i]` step 1 and the product step 2. Nothing of the faulted dispatch is published, so `b` still holds `3 -6 9 12`. Every executor of cint 0.2.0 is required to report this same record (clause 4)."
  },
  {
   "id": "spec-02p:how-this-document-is-organized",
   "edition": "SPEC-02P.1",
   "title": "How this document is organized",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#how-this-document-is-organized",
   "internal": 0,
   "content": "### How this document is organized\n\nClauses 1 to 4 give the scope, the references, the terms and what conformance means. Clause 5 describes a dispatch: its phases, its number, the checks it makes before any work-item runs, the step ordinal, and the choice and content of the fault it reports. Clause 6 gives the test that decides whether the arguments of a dispatch may overlap. Clause 7 states how outputs are held back until a dispatch succeeds. Clause 8 states how a work-item is evaluated and charged fuel, and clause 9 how reductions are computed so that their results do not depend on the order of evaluation. Clause 10 states the obligations of every executor and describes `cpu-c17`, `cpu-sir-interp` and `gpu-cuda`. Clause 11 works one kernel through the rules on all three. Clause 12 lists directions that cint 0.2.0 does not implement.\n\nSubclauses follow the shape of SPEC-04P.2: a summary, then **Semantics**, **Faults**, **Examples** and **Notes** as a subclause needs them. Examples and notes are informative. Every example is a complete program, and its output is shown exactly as cint 0.2.0 prints it on `cpu-c17`; the reference gives the same outcome. Where a tool of that release refuses an example (4, paragraph 4), the output shown is the reference's. A line `...` in shown output stands for lines left out. Sessions of the tools are shown in console blocks, with each command after `$ ` and each entry of a session after its prompt."
  },
  {
   "id": "spec-02p:scope",
   "edition": "SPEC-02P.1",
   "title": "1 Scope",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#scope",
   "internal": 0,
   "content": "## 1 Scope\n\n1. This document specifies, for programs in `cint-core-1`, the language profile that SPEC-04P.2 defines:\n   - the phases of a dispatch, the numbering of dispatches and the checks a dispatch makes before any work-item runs, in their order;\n   - the step ordinal, and which of several faults in one dispatch is reported;\n   - the test that decides whether two arguments of a dispatch may overlap;\n   - the staging and publication of outputs;\n   - the evaluation of a work-item and the fuel it is charged;\n   - the evaluation of reductions inside kernels and the attribution of their faults;\n   - what every executor shall and shall not do, and what each executor of cint 0.2.0 runs and refuses.\n2. This document does not specify:\n   - the form and meaning of kernels, arrays and views as a program sees them, which SPEC-04P.2 6.12 and 6.13 specify;\n   - the host interface through which a host program registers memory, places it on a device and issues dispatches, which SPEC-03P.1 specifies;\n   - the byte encodings of fault records, which SPEC-01P.2 specifies;\n   - the intermediate representation, the C that the compiler emits and the conformance suite, which SPEC-09P.1 specifies;\n   - speed. No performance figure is given, and none is claimed."
  },
  {
   "id": "spec-02p:normative-references",
   "edition": "SPEC-02P.1",
   "title": "2 Normative references",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#normative-references",
   "internal": 0,
   "content": "## 2 Normative references\n\nThe following documents are referred to in the text in such a way that some or all of their content constitutes requirements of this document. For dated references, only the edition cited applies.\n\n- ISO/IEC 9899:2018, *Information technology: Programming languages: C* (C17). Used for the C that `cpu-c17` emits and the C17 component `cpu-sir-interp`.\n- NVIDIA. *Parallel Thread Execution ISA*, version 9.4. Used for the device code of `gpu-cuda`: sections 9.7.1.3 (`mul`), 9.7.2.1 and 9.7.2.2 (`add.cc`, `addc`) and 9.7.15.5 (`atom`).\n- NVIDIA. *CUDA Driver API Reference Manual*, version 13.4. Used for section 6.27, Module Management, through which `gpu-cuda` loads its device code.\n\nThe other cint documents of the same release, SPEC-04P.2, SPEC-01P.2, SPEC-03P.1 and SPEC-09P.1, are named in the text where they hold detail."
  },
  {
   "id": "spec-02p:terms-definitions-and-symbols",
   "edition": "SPEC-02P.1",
   "title": "3 Terms, definitions and symbols",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "## 3 Terms, definitions and symbols\n\nThe terms of SPEC-04P.2 clause 3 apply, among them *value*, *fault*, *fault record*, *operation identifier*, *refusal*, *the reference*, *executor*, *entry*, *fuel*, *view*, *kernel*, *dispatch*, *work-item* and *revision*. In addition:\n\n<a id=\"term-iteration-space\"></a>**3.1 iteration space**: the set of index tuples given by a kernel's `over` clause. Each tuple is one work-item.\n\n<a id=\"term-work-item-index\"></a>**3.2 work-item index**: the position of a work-item's index tuple in the row-major order of the iteration space, counted from 0. For `over [y: h, x: w]`, the work-item `(y, x)` has index `y * w + x`.\n\n<a id=\"term-owned-block\"></a>**3.3 owned block**: the elements of an `out` or `inout` array argument that one work-item may write: those whose leading indices are the work-item's index tuple.\n\n<a id=\"term-varying\"></a><a id=\"term-uniform\"></a>**3.4 uniform, varying**: a value in a kernel body is *uniform* when it is the same for every work-item of a dispatch, and *varying* otherwise.\n\n<a id=\"term-contribution\"></a>**3.5 contribution**: the value a work-item adds to a reduction when it executes a `reduce` statement.\n\n<a id=\"term-phase\"></a>**3.6 phase**: one of the three parts of a dispatch: *entry* (numbered 0), in which the arguments are checked; *work-item* (1), in which the work-items run; and *epilogue* (2), in which the reductions are completed.\n\n<a id=\"term-entry-check\"></a>**3.7 entry check**: a check a dispatch makes in its entry phase, before any work-item runs.\n\n<a id=\"term-dispatch-number\"></a>**3.8 dispatch number**: the position of a dispatch among the dispatches of its entry, counted from 0.\n\n<a id=\"term-step-ordinal\"></a>**3.9 step ordinal**: the position of an operation among the counted operations a work-item has evaluated, counted from 0 (5.4)."
  },
  {
   "id": "spec-02p:terms-definitions-and-symbols-p1",
   "edition": "SPEC-02P.1",
   "title": "3 Terms, definitions and symbols (part 2)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "<a id=\"term-address\"></a>**3.10 address**: the part of a fault record that locates a fault in a dispatch: the kernel's qualified name, the dispatch number, the phase, and, in the work-item phase, the work-item index and the step ordinal.\n\n<a id=\"term-canonical-fault\"></a>**3.11 canonical fault**: the fault a dispatch reports: the least of the faults it could raise, in the order of 5.5.\n\n<a id=\"term-staging\"></a>**3.12 staging**: storage that holds the outputs of a dispatch until they are published. A program cannot observe it.\n\n<a id=\"term-publish\"></a>**3.13 publish**: to make every output of a dispatch visible at once.\n\n<a id=\"term-storage\"></a>**3.14 storage**: the elements a view reaches into: an array, an arena, or a region registered through the host interface. Views made from one array share its storage.\n\n<a id=\"term-addressed-storage\"></a>**3.15 addressed storage**: the set of element offsets that a view reaches (6.2).\n\n<a id=\"term-bounding-interval\"></a>**3.16 bounding interval**: the smallest interval of element offsets that contains a view's addressed storage (6.2).\n\n<a id=\"term-device\"></a><a id=\"term-host\"></a>**3.17 host, device**: the *host* is the processor that runs a program's sequential code; a *device* is a GPU on which an executor runs work-items.\n\n<a id=\"term-placement\"></a>**3.18 placement**: the memory, host or device, that holds a view's storage.\n\n<a id=\"term-capability-profile\"></a>**3.19 capability profile**: the record of what an executor admits and what it refuses (10.2).\n\n<a id=\"term-launch\"></a>**3.20 launch**: one start of device code over a range of work-item indices.\n\n<a id=\"term-fault-word\"></a>**3.21 fault word**: the 64-bit location in device memory that holds the least index of a work-item that faulted on the device (10.6)."
  },
  {
   "id": "spec-02p:symbols",
   "edition": "SPEC-02P.1",
   "title": "3.22 Symbols",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#symbols",
   "internal": 0,
   "content": "### 3.22 Symbols\n\n| Symbol | Meaning |\n|---|---|\n| `N` | The number of work-items of a dispatch: the product of the extents of its iteration space. |\n| `k` | The index of the work-item of the canonical fault. |\n| `abs(s)` | The absolute value of the integer `s`. |\n| `gcd(a, b, ...)` | The greatest common divisor of the integers listed, not all 0. |\n| `C(i)` | The total fuel that work-item `i` charges when it runs to its end or to its first fault. |"
  },
  {
   "id": "spec-02p:conformance",
   "edition": "SPEC-02P.1",
   "title": "4 Conformance",
   "clauses": "BACK-03",
   "url": "/specifications/spec-02p/1/#conformance",
   "internal": 0,
   "content": "## 4 Conformance\n\n1. In this document, \"shall\" states a requirement on an executor or on a program, and \"shall not\" a prohibition. \"May\" states a permission.\n2. <a id=\"Q-2\"></a>An executor conforms to this document when, for every dispatch it admits, it produces the outcome of the procedure of 5.1: the same output bytes, the same reduction results, the same fuel consumed, the same dispatch numbers and the same fault record as the reference. For a dispatch it does not admit, it refuses with `E_UNSUPPORTED`, during translation or in the entry phase, before any output is written and before any fuel is charged; it does not run the dispatch in a narrower or approximate form (10.1) [Q-2].\n3. `cpu-c17` is the executor against which the others are compared, and every executor is compared with the reference on the conformance suite, as SPEC-09P.1 5.3 states; where an executor or the reference differs from this document, this document governs, and the difference is a defect [SPEC-09P.1 BACK-03].\n4. As SPEC-04P.2 clause 4 states, an implementation may also refuse a construct that it does not implement, with a diagnostic whose code begins with `C9`. The program stays conforming, and on an implementation that runs it, its outcome is the one this document specifies. SPEC-09P.1 lists the constructs that the cint tools of each release refuse."
  },
  {
   "id": "spec-02p:the-phases-of-a-dispatch",
   "edition": "SPEC-02P.1",
   "title": "5.1 The phases of a dispatch",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#the-phases-of-a-dispatch",
   "internal": 0,
   "content": "### 5.1 The phases of a dispatch\n\nA dispatch has three phases. In the entry phase it checks its arguments and charges its fuel. In the work-item phase it runs the body once for every point of the iteration space. In the epilogue it completes the reductions. Its outputs are published only after all three succeed. This subclause states the procedure whose outcome every executor gives.\n\n**Semantics**\n\n1. An executor shall give every dispatch the outcome of the procedure of SPEC-04P.2 6.13.6, whatever order of execution it uses, sequential or parallel. That procedure makes the entry checks of 5.3, the last of which charges the dispatch's fuel. It then runs each work-item in ascending index, as an independent sequential program charged as 8.4 states, and then completes the reductions (9.3) and publishes the outputs (clause 7). It stops at the first fault [SPEC-04P.2 X-1].\n2. <a id=\"F-12\"></a>A dispatch is synchronous: the statement after it starts only when the dispatch has published its outputs. The dispatches of an entry are carried out in program order. An executor may prepare a dispatch before the one ahead of it completes, but if the one ahead faults, the prepared one is discarded: it publishes nothing and takes no dispatch number. An executor shall not begin a dispatch that reads the outputs of an earlier dispatch until the earlier one has published them [F-12].\n3. A fault in any phase ends the entry, as every fault does (SPEC-04P.2 5.2.3).\n\n**Notes**\n\n4. The procedure defines an outcome, not a method. `cpu-c17` and the interpreter follow it as written. `gpu-cuda` runs the work-item phase on a device, with many work-items at once, and recovers the outcome of the procedure by the protocol of 10.6."
  },
  {
   "id": "spec-02p:dispatch-numbers",
   "edition": "SPEC-02P.1",
   "title": "5.2 Dispatch numbers",
   "clauses": "IM-112",
   "url": "/specifications/spec-02p/1/#dispatch-numbers",
   "internal": 0,
   "content": "### 5.2 Dispatch numbers\n\nEvery dispatch of an entry has a number, its position among the dispatches of that entry. The number is part of the address of a fault in the dispatch.\n\n**Semantics**\n\n1. <a id=\"F-1\"></a>Each entry counts its dispatches. The first dispatch of an entry has number 0, the next 1 and so on, in program order. Every dispatch takes the next number, whether it succeeds or faults, and a dispatch that faults in its entry phase takes one too. A dispatch that the host interface refuses before it begins, because its arguments cannot be formed into values at all, takes none (SPEC-03P.1) [F-1] [SPEC-04P.2 P-3, IM-112].\n2. The count restarts at 0 at every entry. It is not part of the program's state, and a checkpoint neither saves nor restores it [F-1] [SPEC-04P.2 IM-112].\n3. A fault outside any dispatch has no address at all; no dispatch number stands for \"not in a kernel\" [F-1].\n4. <a id=\"F-2\"></a>A dispatch has one number even when an executor splits it into several launches [F-2].\n\n**Examples**\n\n5. One entry runs three dispatches of one kernel. The first two double both elements; the third overflows at work-item 1:\n\n```cint dispatch_count.ci\nkernel double[n](in I64[n] a, out I64[n] b) over [i: n] {\n    b[i] = a[i] * 2;\n}\n\nvoid run() {\n    I64[2] a = [1, 1152921504606846976];\n    I64[2] b;\n    double(a, b);\n    double(b, a);\n    \"{a[0]} {a[1]}\\n\";\n    double(a, b);\n}\n\nrun();\n```\n\n```text\n4 4611686018427387904\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> dispatch_count.ci:2:17\n   |\n 2 |     b[i] = a[i] * 2;\n   |                 ^ mul.checked.i64\n   |\n   = operation: mul.checked.i64\n   = operand-count: 2\n   = operand: I64 4611686018427387904\n   = operand: I64 2\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n   ...\n   = address: dispatch_count.double, dispatch 2, phase 1, work-item 1, step 2\n   ...\n```"
  },
  {
   "id": "spec-02p:entry-checks",
   "edition": "SPEC-02P.1",
   "title": "5.3 Entry checks",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#entry-checks",
   "internal": 0,
   "content": "### 5.3 Entry checks\n\nBefore any work-item runs, a dispatch checks that its arguments are usable and that it can pay for its work-items. The checks run in a fixed order, so that a dispatch with several faulty arguments reports the same fault on every executor.\n\n**Semantics**\n\n1. <a id=\"F-5\"></a>A dispatch makes the checks of Table 1 in the order of the table. Within a check, the arguments are taken in the order in which their parameters are declared, and the dimensions of each in order. The first check that fails gives the fault of the dispatch, in the entry phase; no further check runs and no work-item runs [F-5].\n\nTable 1. Entry checks, in order."
  },
  {
   "id": "spec-02p:entry-checks-p1",
   "edition": "SPEC-02P.1",
   "title": "5.3 Entry checks (part 2)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#entry-checks",
   "internal": 0,
   "content": "| Check | What is checked | Fault | Operation | Operands | Limit |\n|---|---|---|---|---|---|\n| 1 | The storage of each array argument has not been released or reset since the view was made | `E_STALE_HANDLE` | `bind.stale` | parameter; the view's generation (`U64`) | the storage's current generation (`U64`) |\n| 2 | Each argument of an `out` or `inout` parameter is a view that may be written | `E_ALIAS` | `bind.permission` | parameter | none |\n| 3 | Each array argument has the parameter's element type | `E_UNSUPPORTED` | `bind.type` | parameter | none |\n| 3 | Each array argument has the parameter's rank | `E_SHAPE` | `bind.type` | parameter; the view's rank | the declared rank |\n| 4 | Every array argument is held in memory that the executor runs the dispatch on | `E_UNSUPPORTED` | `bind.placement` | the first parameter that differs | none |\n| 5 | The size symbols bind, and every extent agrees (SPEC-04P.2 6.13.2) | `E_SHAPE` | `bind.shape` | parameter; dimension; the argument's extent | the extent computed from the declaration |\n| 5 | An extent expression `n + c` or `n - c` stays in `I64` | `E_OVERFLOW` | `add.checked.i64`, `sub.checked.i64` | the two operands | the bound crossed |\n| 5 | Each constraint of the `where` clause holds, in written order | `E_SHAPE` | `bind.where` | the constraint's index from 0; the value of its left side; the value of its right side | none |\n| 6 | Each argument of an `out` or `inout` parameter passes the test of 6.4 | `E_ALIAS` | `bind.injective` | parameter | none |\n| 7 | Each argument of an `out` or `inout` parameter is shown disjoint from every other array argument by the test of 6.3 | `E_ALIAS` | `bind.alias` | the `out` or `inout` parameter; the other parameter | none |\n| 8 | The dispatch is within the executor's limits | `E_UNSUPPORTED` | `bind.limit` | parameter | none |\n| 9 | The fuel left in the entry covers `N` units (8.4) | `E_FU"
  },
  {
   "id": "spec-02p:entry-checks-p2",
   "edition": "SPEC-02P.1",
   "title": "5.3 Entry checks (part 3)",
   "clauses": "V-12 V-13",
   "url": "/specifications/spec-02p/1/#entry-checks",
   "internal": 0,
   "content": "A *generation* is a count that each storage keeps and that its release or reset advances; a view records the generation of its storage when the view is made, and check 1 compares the two. A parameter is given by its position in the declaration, counted from 0, and a dimension likewise. Every operand of a `bind` operation is an `I64` unless the table says otherwise, and no entry check has an exact result.\n\n2. Checks 1 to 3 and 5 to 7 depend only on the program and its arguments, and decide the same way on every executor. Check 4 depends also on the memory an executor runs on, and decides the same way when the arguments are placed where each executor runs. Check 8 is a refusal by one executor: its fault is not compared between executors [F-5].\n3. Check 9 comes after check 8, so a dispatch that an executor does not admit is never charged. No entry check changes state or charges fuel except check 9, whose charge is made only when every other check has passed [F-5].\n4. <a id=\"V-12\"></a>All array arguments of one dispatch shall have the same placement, and that placement shall be one the executor runs on. No executor moves program data between host and device memory to meet this rule; a program moves data explicitly, through the host interface (SPEC-03P.1). The one exception is the read-back of 10.6, which serves only to describe a fault [V-12].\n5. <a id=\"V-13\"></a>Placement is not part of any outcome. Output bytes, reduction results and fault records do not depend on it, and the descriptor of a view in a fault record (6.3) leaves it out [V-13].\n6. Checks 2 and 3 fail only for a dispatch issued through the host interface: for a dispatch written in cint source, translation rejects the same mismatches with a diagnostic (SPEC-04P.2 6.13.2).\n\n**Faults**"
  },
  {
   "id": "spec-02p:entry-checks-p3",
   "edition": "SPEC-02P.1",
   "title": "5.3 Entry checks (part 4)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#entry-checks",
   "internal": 0,
   "content": "7. Each row of Table 1 gives the fault code, the operation identifier, the operands and the limit of the fault that its check raises. The position and the stack of every entry-phase fault are those of 5.6.\n\n**Examples**\n\n8. The two passes of the size binding: `n` is bound to 3 by `b`, so `a` should have extent 4. Its extent is 5, and check 5 faults on parameter 0, dimension 0:\n\n```cint shape_rt.ci\nkernel k[n](in I64[n + 1] a, out I64[n] b) over [i: n] {\n    b[i] = a[i] + a[i + 1];\n}\n\nvoid go(I64 m) {\n    I64[8] a;\n    I64[8] b;\n    k(a[0..5], b[0..m]);\n    \"done\\n\";\n}\ngo(3);\n```\n\n```text\nfault[E_SHAPE]: shapes do not match\n  --> shape_rt.ci:8:5\n   |\n 8 |     k(a[0..5], b[0..m]);\n   |     ^ bind.shape\n   |\n   = operation: bind.shape\n   = operand-count: 3\n   = operand: I64 0\n   = operand: I64 0\n   = operand: I64 5\n   = exact:   none\n   = limit:   I64 4\n   ...\n   = address: shape_rt.k, dispatch 0, phase 0, work-item none, step none\n   ...\n```\n\n9. In this example a `where` constraint is false. The constraint `n >= 2` has index 0, and its sides are 1 and 2:\n\n```cint where_rt.ci\nkernel smooth[n](in I64[n] u, out I64[n] v) over [i: n] where n >= 2 {\n    v[i] = u[i];\n}\n\nvoid go(I64 m) {\n    I64[4] a;\n    I64[4] b;\n    smooth(a[0..m], b[0..m]);\n    \"done\\n\";\n}\ngo(1);\n```\n\n```text\nfault[E_SHAPE]: shapes do not match\n  --> where_rt.ci:8:5\n   |\n 8 |     smooth(a[0..m], b[0..m]);\n   |     ^ bind.where\n   |\n   = operation: bind.where\n   = operand-count: 3\n   = operand: I64 0\n   = operand: I64 1\n   = operand: I64 2\n   = exact:   none\n   = limit:   none\n   ...\n```"
  },
  {
   "id": "spec-02p:step-ordinal",
   "edition": "SPEC-02P.1",
   "title": "5.4 Step ordinal",
   "clauses": "IM-113 IM-114",
   "url": "/specifications/spec-02p/1/#step-ordinal",
   "internal": 0,
   "content": "### 5.4 Step ordinal\n\nThe step ordinal locates a fault inside a work-item. It counts operations of the source program, not instructions of an executor, so that every executor gives the same number.\n\n**Semantics**\n\n1. <a id=\"F-6\"></a>Within a work-item, each evaluation of a counted operation receives the next step ordinal, from 0, in the evaluation order of SPEC-04P.2, the place of a store before its right side; SPEC-04P.2 8.1 lists the counted operations, which include the shifts and unary minus and leave out the bitwise operators `&`, `|`, `^` and `~` [F-6] [SPEC-04P.2 IM-113].\n2. An operation counts whether or not it can fault for the operands at hand, and however an executor carries it out [SPEC-04P.2 IM-114].\n3. <a id=\"F-6a\"></a>A `reduce` statement counts once, as one call of its operation, at the point where the work-item executes it [F-6a].\n4. A fault at a fuel charge inside the body carries as its step ordinal the number of counted operations that the work-item evaluated before the charge (8.4) [F-6a].\n\n**Examples**\n\n5. In `r[i] = a[i] + b[i] * c[i]`, the place `r[i]` is step 0, the reads `a[i]`, `b[i]` and `c[i]` are steps 1 to 3, the product is step 4 and the sum step 5. Work-item 1 overflows at the sum:\n\n```cint step5.ci\nkernel muladd[n](in I64[n] a, in I64[n] b, in I64[n] c, out I64[n] r) over [i: n] {\n    r[i] = a[i] + b[i] * c[i];\n}\n\nvoid go() {\n    I64[2] a = [1, 9223372036854775807];\n    I64[2] b = [2, 1];\n    I64[2] c = [3, 1];\n    I64[2] r;\n    muladd(a, b, c, r);\n    \"unreachable\\n\";\n}\ngo();\n```"
  },
  {
   "id": "spec-02p:step-ordinal-p1",
   "edition": "SPEC-02P.1",
   "title": "5.4 Step ordinal (part 2)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#step-ordinal",
   "internal": 0,
   "content": "```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> step5.ci:2:17\n   |\n 2 |     r[i] = a[i] + b[i] * c[i];\n   |                 ^ add.checked.i64\n   |\n   = operation: add.checked.i64\n   = operand-count: 2\n   = operand: I64 9223372036854775807\n   = operand: I64 1\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n   ...\n   = address: step5.muladd, dispatch 0, phase 1, work-item 1, step 5\n   ...\n```\n\n**Notes**\n\n6. A step ordinal says which operation of a work-item faulted, and the position and the operation identifier of the record say the same in source terms. An executor that cannot count steps on its own hardware may obtain the ordinal by running the faulting work-item again (10.6)."
  },
  {
   "id": "spec-02p:canonical-fault-selection",
   "edition": "SPEC-02P.1",
   "title": "5.5 Canonical fault selection",
   "clauses": "IM-112",
   "url": "/specifications/spec-02p/1/#canonical-fault-selection",
   "internal": 0,
   "content": "### 5.5 Canonical fault selection\n\nSeveral work-items of one dispatch can fault, and a work-item can fault while a reduction would also fault in the epilogue. One of these faults is reported, chosen by a rule that does not depend on the order in which an executor met them.\n\n**Semantics**\n\n1. <a id=\"F-3\"></a>The faults of a dispatch are ordered by the key (phase, work-item index, step ordinal). Faults of the entry phase are ordered by the order of the checks of 5.3, and faults of the epilogue by the declaration order of the reduction targets (9.3). The canonical fault of a dispatch is the least fault under this key, and it is the one reported [F-3] [SPEC-04P.2 IM-112].\n2. Across dispatches, the dispatch number orders faults. Because a fault ends the entry, the first dispatch that faults is the last dispatch of its entry [F-3].\n3. <a id=\"F-4\"></a>The order is logical. It makes no claim about which hardware thread faulted first in time, and an executor that meets faults in another order shall still report the least [F-4].\n\n**Examples**\n\n4. The work-item `(y, x)` of a 3 by 4 iteration space has index `4 * y + x`. Work-items `(2, 1)` and `(2, 3)`, indices 9 and 11, both divide by 0; work-item 9 is reported:\n\n```cint index2d.ci\nkernel recip[h, w](in I64[h, w] a, out I64[h, w] b) over [y: h, x: w] {\n    b[y, x] = 1000 / a[y, x];\n}\n\nvoid run() {\n    I64[3, 4] a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 10, 0]];\n    I64[3, 4] b;\n    recip(a, b);\n}\n\nrun();\n```\n\n```text\nfault[E_DIV_ZERO]: division by zero\n  --> index2d.ci:2:20\n   |\n 2 |     b[y, x] = 1000 / a[y, x];\n   |                    ^ div.checked.i64\n   |\n   = operation: div.checked.i64\n   = operand-count: 2\n   = operand: I64 1000\n   = operand: I64 0\n   = exact:   none\n   = limit:   none\n   ...\n   = address: index2d.recip, dispatch 0, phase 1, work-item 9, step 2\n   ...\n```"
  },
  {
   "id": "spec-02p:canonical-fault-selection-p1",
   "edition": "SPEC-02P.1",
   "title": "5.5 Canonical fault selection (part 2)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#canonical-fault-selection",
   "internal": 0,
   "content": "5. With `k = 2`, work-items 1 and 3 overflow, and the sum of the four products would also overflow `I32` in the epilogue. The work-item phase comes first, so work-item 1 is reported:\n\n```cint mix.ci\nkernel scaled_total[n](in I32[n] x, in I32 k, out I32[n] y, out I32 s) over [i: n] {\n    I32 v = x[i] * k;\n    y[i] = v;\n    reduce s = sum(v);\n}\n\nvoid run(I32 k) {\n    I32[4] x = [5, 1073741824, 7, 1073741824];\n    I32[4] y;\n    I32 s = 0;\n    scaled_total(x, k, y, s);\n    \"{s}\\n\";\n}\n\nrun(2);\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> mix.ci:2:18\n   |\n 2 |     I32 v = x[i] * k;\n   |                  ^ mul.checked.i32\n   |\n   = operation: mul.checked.i32\n   = operand-count: 2\n   = operand: I32 1073741824\n   = operand: I32 2\n   = exact:   2147483648\n   = limit:   I32 2147483647\n   ...\n   = address: mix.scaled_total, dispatch 0, phase 1, work-item 1, step 1\n   ...\n```\n\n6. With `k = 1`, no work-item faults and the epilogue reports the sum. Its operand is the number of contributions, and its position is the operation `sum` in the `reduce` statement:\n\n```cint mix1.ci\nkernel scaled_total[n](in I32[n] x, in I32 k, out I32[n] y, out I32 s) over [i: n] {\n    I32 v = x[i] * k;\n    y[i] = v;\n    reduce s = sum(v);\n}\n\nvoid run(I32 k) {\n    I32[4] x = [5, 1073741824, 7, 1073741824];\n    I32[4] y;\n    I32 s = 0;\n    scaled_total(x, k, y, s);\n    \"{s}\\n\";\n}\n\nrun(1);\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> mix1.ci:4:16\n   |\n 4 |     reduce s = sum(v);\n   |                ^ sum.checked.i32.i32\n   |\n   = operation: sum.checked.i32.i32\n   = operand-count: 1\n   = operand: I64 4\n   = exact:   2147483660\n   = limit:   I32 2147483647\n   ...\n   = address: mix1.scaled_total, dispatch 0, phase 2, work-item none, step none\n   ...\n```"
  },
  {
   "id": "spec-02p:the-fault-record-of-a-dispatch",
   "edition": "SPEC-02P.1",
   "title": "5.6 The fault record of a dispatch",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#the-fault-record-of-a-dispatch",
   "internal": 0,
   "content": "### 5.6 The fault record of a dispatch\n\nA fault in a dispatch has the record of every fault (SPEC-04P.2 8.1), with an address added. This subclause states what the address and the other fields hold in each phase.\n\n**Semantics**\n\n1. <a id=\"F-8\"></a>The record of a fault in a dispatch holds, beyond the fields of every fault record, the address of the fault: the kernel's name qualified by its module, the dispatch number and the phase. A fault in the work-item phase also holds the work-item index and the step ordinal; a fault in the entry or the epilogue phase holds neither [F-8].\n2. The operation, operands, exact result and limit are, in the entry phase, those of Table 1; in the work-item phase, those of the operation that faulted, as SPEC-04P.2 states for it; in the epilogue, those of the reduction (9.3) [F-8].\n3. The position is: in the entry phase, the dispatch, at the kernel's name in the dispatch statement; in the work-item phase, the operator or subscript that faulted; in the epilogue, the operation named in the `reduce` statement. The stack of a work-item or epilogue fault has the dispatch as its innermost entry. The stack of an entry-phase fault is that of the code that issued the dispatch, as for a fault at the entry of a call. A dispatch is not a call: it is charged only the fuel of 8.4 [F-8].\n4. Details of an executor, a device or the native code are not part of the record. A tool may show them beside it, marked as not part of the record [F-8].\n5. A fault of check 7 also carries a descriptor of each of the two views (6.3).\n\n**Notes**"
  },
  {
   "id": "spec-02p:the-fault-record-of-a-dispatch-p1",
   "edition": "SPEC-02P.1",
   "title": "5.6 The fault record of a dispatch (part 2)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#the-fault-record-of-a-dispatch",
   "internal": 0,
   "content": "6. `cint run` prints the address as one line, `= address: module.kernel, dispatch D, phase P, work-item W, step S`, with `none` for a field the phase does not have. Examples 4 to 6 of 5.5 show it for the work-item phase and the epilogue, and examples 8 and 9 of 5.3 for the entry phase. SPEC-06P.1 describes the report, and SPEC-01P.2 the encoding of the record."
  },
  {
   "id": "spec-02p:aliasing-the-overlap-test",
   "edition": "SPEC-02P.1",
   "title": "6 Aliasing: the overlap test",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#aliasing-the-overlap-test",
   "internal": 0,
   "content": "## 6 Aliasing: the overlap test"
  },
  {
   "id": "spec-02p:what-the-test-establishes",
   "edition": "SPEC-02P.1",
   "title": "6.1 What the test establishes",
   "clauses": "A-3",
   "url": "/specifications/spec-02p/1/#what-the-test-establishes",
   "internal": 0,
   "content": "### 6.1 What the test establishes\n\nEvery output of a dispatch must share no element with any other array argument (SPEC-04P.2 6.13.2). This clause gives the test with which an executor establishes that, and states its limits.\n\n**Semantics**\n\n1. An executor establishes that an `out` or `inout` argument shares no element with another array argument by the test of 6.3, at entry check 7. As SPEC-04P.2 6.13.2 states, the test is sufficient but not exact: a pair it shows disjoint shares no element, and every other pair faults `E_ALIAS`, whether the two views overlap or not [SPEC-04P.2 A-3].\n2. The same test serves every way of issuing a dispatch, and no assertion by a program that two arguments are independent is taken as evidence [SPEC-04P.2 A-3]."
  },
  {
   "id": "spec-02p:addressed-storage-and-bounding-interval",
   "edition": "SPEC-02P.1",
   "title": "6.2 Addressed storage and bounding interval",
   "clauses": "V-4 V-5",
   "url": "/specifications/spec-02p/1/#addressed-storage-and-bounding-interval",
   "internal": 0,
   "content": "### 6.2 Addressed storage and bounding interval\n\nA view reaches a set of elements of its storage. The test of 6.3 reasons about that set through its offsets and through the interval that contains it.\n\n**Semantics**\n\n1. A view of rank `r` has an origin, the offset in its storage of the element with all indices 0, and an extent and a stride for each dimension, and its element at an index tuple has the offset that SPEC-04P.2 6.12.4 gives, computed exactly [SPEC-04P.2 V-4].\n2. The addressed storage of a view is the set of the offsets of all its index tuples. It is empty when any extent is 0. When every extent is positive, the bounding interval of the view is the closed interval `[lo, hi]`, where `lo` is the origin plus `stride * (extent - 1)` summed over the dimensions with a negative stride, and `hi` is the origin plus the same sum over the dimensions with a positive stride. It is the smallest interval that contains the addressed storage, and `lo` and `hi` are both addressed. A view is formed only when its bounding interval lies within its storage (SPEC-04P.2 6.12.4) [SPEC-04P.2 V-5].\n\n**Examples**\n\n3. This example lists views of `I32[8, 16] m` and of `I32[8] a`, with their origins, strides and bounding intervals:\n\n| View | Origin | Extents | Strides | Bounding interval |\n|---|---|---|---|---|\n| `m[.., 0..8]` | 0 | (8, 8) | (16, 1) | [0, 119] |\n| `m[.., 8..16]` | 8 | (8, 8) | (16, 1) | [8, 127] |\n| `m[.., 0..16 by 2]` | 0 | (8, 8) | (16, 2) | [0, 126] |\n| `m[.., 1..16 by 2]` | 1 | (8, 8) | (16, 2) | [1, 127] |\n| `a` | 0 | (8) | (1) | [0, 7] |\n| `reverse(a, 0)` | 7 | (8) | (-1) | [0, 7] |"
  },
  {
   "id": "spec-02p:the-pairwise-test",
   "edition": "SPEC-02P.1",
   "title": "6.3 The pairwise test",
   "clauses": "A-5 A-6",
   "url": "/specifications/spec-02p/1/#the-pairwise-test",
   "internal": 0,
   "content": "### 6.3 The pairwise test\n\nThe pairwise test applies three tests in order, each of which can show two views disjoint. A pair that none of them shows disjoint is refused.\n\n**Semantics**\n\n1. <a id=\"A-5\"></a>For each `out` or `inout` parameter `p`, in declaration order, and each other array parameter `q`, in declaration order, the arguments of `p` and `q` are tested; a pair of two `out` or `inout` parameters is tested once, from the earlier of the two. The tests are applied in order, and the first that shows the pair disjoint accepts it [A-5]:\n   1. *Empty test*: the view of `p` or the view of `q` has no elements.\n   2. *Interval test*: the bounding intervals of the two views, taken as ranges of bytes in one memory, do not intersect. Views of two arrays that share no memory never intersect.\n   3. *Gcd test*: the two views have the same storage and the same element size; `g` is the greatest common divisor of `abs(stride)` over every dimension of either view whose extent is above 1; and `g >= 2` and `origin(p) mod g` differs from `origin(q) mod g`.\n2. A pair that no test of paragraph 1 shows disjoint faults `E_ALIAS` [A-5].\n3. The gcd test is sound. A dimension of extent 1 adds nothing to any offset, and every other dimension adds a multiple of its stride, which is a multiple of `g`. Every offset of either view is therefore congruent to its origin modulo `g`, and two views whose origins differ modulo `g` have no offset in common [A-5].\n4. <a id=\"A-6\"></a>No more general test is made. Whether two strided views share an element is in general an integer feasibility problem, which NumPy's documentation of `numpy.shares_memory` calls NP-complete; the interval test corresponds to `numpy.may_share_memory`. A disjoint layout that these tests do not show disjoint is refused, and the remedy is a layout that they do show, or an explicit copy [A-6].\n\n**Faults**"
  },
  {
   "id": "spec-02p:the-pairwise-test-p1",
   "edition": "SPEC-02P.1",
   "title": "6.3 The pairwise test (part 2)",
   "clauses": "A-8",
   "url": "/specifications/spec-02p/1/#the-pairwise-test",
   "internal": 0,
   "content": "5. <a id=\"A-8\"></a>`E_ALIAS` is raised at entry check 7 by the first pair, in the order of paragraph 1, that no test shows disjoint. The record holds the operation identifier `bind.alias`; two `I64` operands, the position of `p` and then that of `q`; no exact result and no limit; and a descriptor of the view of `p` and then of `q`: the element type, the rank, the origin, the extent and the stride of each dimension, and whether the view may be written. The descriptors leave out the placement. The record does not say which test failed. Its position is the dispatch [A-8].\n\n**Examples**\n\n6. Two arguments are two planes of one array. The bounding intervals are [0, 63] and [64, 127], and the interval test accepts the pair:\n\n```cint alias_planes.ci\nkernel copy2[h, w](in I32[h, w] u, out I32[h, w] v) over [y: h, x: w] {\n    v[y, x] = u[y, x] + 1;\n}\n\nvoid go() {\n    I32[2, 8, 8] p;\n    p[0, 3, 4] = 41;\n    copy2(p[0], p[1]);\n    \"{p[1, 3, 4]}\\n\";\n}\ngo();\n```\n\n```text\n42\n```\n\n7. Two arguments are the even and the odd elements of each row. The bounding intervals [0, 126] and [1, 127] intersect, but every stride is a multiple of `g = 2` and the origins are 0 and 1, so the gcd test accepts the pair:\n\n```cint alias_even_odd.ci\nkernel inc2[h, w](in I32[h, w] u, out I32[h, w] v) over [y: h, x: w] {\n    v[y, x] = u[y, x] + 1;\n}\n\nvoid run() {\n    I32[8, 16] m;\n    m[2, 6] = 41;\n    inc2(m[.., 0..16 by 2], m[.., 1..16 by 2]);\n    \"{m[2, 7]}\\n\";\n}\n\nrun();\n```\n\n```text\n42\n```\n\n8. The left and right halves of each row share no element, but no test shows it: the bounding intervals [0, 119] and [8, 127] intersect and the strides 16 and 1 give `g = 1`. The pair faults; the operands name `v` (1) and `u` (0):\n\n```cint alias_cols.ci\nkernel copy2[h, w](in I32[h, w] u, out I32[h, w] v) over [y: h, x: w] {\n    v[y, x] = u[y, x] + 1;\n}"
  },
  {
   "id": "spec-02p:the-pairwise-test-p2",
   "edition": "SPEC-02P.1",
   "title": "6.3 The pairwise test (part 3)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#the-pairwise-test",
   "internal": 0,
   "content": "void go() {\n    I32[8, 16] m;\n    copy2(m[.., 0..8], m[.., 8..16]);\n    \"done\\n\";\n}\ngo();\n```\n\n```text\nfault[E_ALIAS]: views overlap\n  --> alias_cols.ci:7:5\n   |\n 7 |     copy2(m[.., 0..8], m[.., 8..16]);\n   |     ^ bind.alias\n   |\n   = operation: bind.alias\n   = operand-count: 2\n   = operand: I64 1\n   = operand: I64 0\n   = exact:   none\n   = limit:   none\n   ...\n```\n\n9. An array and its reversal share every element:\n\n```cint rev_alias.ci\nkernel copy1[n](in I32[n] u, out I32[n] v) over [i: n] {\n    v[i] = u[i] + 1;\n}\n\nvoid go() {\n    I32[8] a;\n    copy1(a, reverse(a, 0));\n}\ngo();\n```\n\n```text\nfault[E_ALIAS]: views overlap\n  --> rev_alias.ci:7:5\n   |\n 7 |     copy1(a, reverse(a, 0));\n   |     ^ bind.alias\n   |\n   = operation: bind.alias\n   = operand-count: 2\n   = operand: I64 1\n   = operand: I64 0\n   ...\n```\n\n**Notes**\n\n10. The gcd is taken over the dimensions of both views together. Taken over one view only it would be unsound: with `p` of extents (2, 2), strides (1, 4) and origin 0 and `q` of extents (1, 2), strides (1, 4) and origin 1, the gcd over `q` alone is 4 and the origins differ modulo 4, yet both views contain the offsets 1 and 5. Over both views the gcd is 1, and the test makes no claim.\n11. Some refused pairs do overlap: the same view twice, or two views of one element. Others, such as example 8, do not. The fault is the same, because the rule is about what the test shows, not about what is true."
  },
  {
   "id": "spec-02p:the-write-view-test",
   "edition": "SPEC-02P.1",
   "title": "6.4 The write-view test",
   "clauses": "A-4 A-7",
   "url": "/specifications/spec-02p/1/#the-write-view-test",
   "internal": 0,
   "content": "### 6.4 The write-view test\n\nAn `out` or `inout` argument must reach a distinct element for each index tuple, or two work-items could write one element. Views made in cint source always do; a view that arrives through the host interface is checked at entry check 6.\n\n**Semantics**\n\n1. <a id=\"A-7\"></a>A view with no elements passes. Otherwise, discard the dimensions of extent 1 and sort the others by `abs(stride)`, ascending, ties by ascending dimension number, as `d1, d2, ...`. The view passes when `abs(stride(d1)) >= 1` and, for every `j > 1`, `abs(stride(dj))` is at least 1 plus the sum, over every `i < j`, of `abs(stride(di)) * (extent(di) - 1)` [A-7].\n2. A view that passes reaches a distinct offset for each index tuple: each dimension in the sorted order steps past every offset that the dimensions before it can reach. The test is sufficient but not exact [A-7].\n\n**Faults**\n\n3. `E_ALIAS` is raised at entry check 6 by the first `out` or `inout` argument that does not pass. The record holds the operation identifier `bind.injective` and one `I64` operand, the parameter's position, with no exact result and no limit. Its position is the dispatch [A-7] [SPEC-04P.2 A-4].\n\n**Examples**\n\n4. Row-major and column-major views pass, and so do their reversals, transposes and regular slices. The view of extents (2, 2) and strides (1, 1) fails, and it does reach offset 1 twice. The view of extents (3, 2) and strides (2, 3) reaches the distinct offsets 0, 3, 2, 5, 4 and 7, but fails, because 3 is less than `1 + 2 * 2`.\n\n**Notes**\n\n5. In cint source, the views a program can form all pass: slices take a step that is a positive literal, and `reverse` and `transpose` keep distinct offsets distinct."
  },
  {
   "id": "spec-02p:when-the-checks-run",
   "edition": "SPEC-02P.1",
   "title": "6.5 When the checks run",
   "clauses": "A-8",
   "url": "/specifications/spec-02p/1/#when-the-checks-run",
   "internal": 0,
   "content": "### 6.5 When the checks run\n\n**Semantics**\n\n1. When two arguments of a dispatch in cint source are the same variable, or provably the same view expression, and one of them is bound to an `out` or `inout` parameter, translation rejects the dispatch with the diagnostic C5010. Every other case is checked in the entry phase, before any work-item runs [A-8].\n\n**Examples**\n\n2. The same array for an `in` and an `out` parameter is rejected before the program runs:\n\n```cint same_c5010.ci\nkernel copy1[n](in I32[n] u, out I32[n] v) over [i: n] {\n    v[i] = u[i] + 1;\n}\n\nvoid go() {\n    I32[8] a;\n    copy1(a, a);\n}\ngo();\n```\n\n```text\nerror[C5010]: parameter mode, alias, or ABI rule\n  --> same_c5010.ci:7:14\n   |\n 7 |     copy1(a, a);\n   |              ^\n```"
  },
  {
   "id": "spec-02p:publish-on-success",
   "edition": "SPEC-02P.1",
   "title": "7.1 Publish on success",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#publish-on-success",
   "internal": 0,
   "content": "### 7.1 Publish on success\n\nA dispatch writes its outputs to staging and publishes them only when it has succeeded. A program, or a host, therefore sees either every output of a dispatch or none.\n\n**Semantics**\n\n1. An executor writes every output of a dispatch to staging, and publishes the outputs, or nothing, as SPEC-04P.2 6.13.4 states [SPEC-04P.2 P-1].\n2. Neither a statement of the program nor a call of the host interface made after a dispatch can observe some of its outputs published and others not (SPEC-04P.2 6.13.4); code outside the program that reads borrowed host memory while a dispatch runs is outside this rule (SPEC-03P.1) [SPEC-04P.2 P-2].\n3. <a id=\"P-11\"></a>After a dispatch faults, the host observes: every `in`, `out` and `inout` argument unchanged; every variable bound to a scalar `out` unchanged; the fault record of 5.6; the fuel consumed of 8.4; the dispatch count advanced by one; and the context faulted until the host clears or restores it [P-11].\n4. <a id=\"P-5\"></a>No way of staging is observable. Publication does not change the identity of the storage or invalidate a view of it, and every view of the storage, made before or after the dispatch, reads the published elements afterward [P-5].\n\n**Examples**\n\n5. A `cint-workbench` session runs entries one at a time and keeps their variables, so it can show what a faulted dispatch leaves. The first dispatch publishes `total = 5`; the second faults at work-item 1, and `total` keeps 5:"
  },
  {
   "id": "spec-02p:publish-on-success-p1",
   "edition": "SPEC-02P.1",
   "title": "7.1 Publish on success (part 2)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#publish-on-success",
   "internal": 0,
   "content": "```console\n$ cint-workbench\n...\nci[1]> kernel total_checked[n](in I64[n] x, out I64 s) over [i: n] { reduce s = fold_checked(add, 0, x[i]); }\ntotal_checked   revision session@r1\nci[2]> I64 total = 3;\ntotal = 3 : I64\nci[3]> I64[3] data = [5, 1, -1];\ndata : I64[3]   3 elements   host\n  [0] = 5\n  [1] = 1\n  [2] = -1\nci[4]> total_checked(data, total);\nci[5]> total\n= 5 : I64\nci[6]> data[0] = 9223372036854775807;\nci[7]> total_checked(data, total);\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> entry 1:1:74\n   |\n 1 | kernel total_checked[n](in I64[n] x, out I64 s) over [i: n] { reduce s = fold_checked(add, 0, x[i]); }\n   |                                                                          ^ fold_checked.add.i64\n   |\n   = operation: fold_checked.add.i64\n   = operand-count: 3\n   = operand: I64 1\n   = operand: I64 9223372036854775807\n   = operand: I64 1\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n...\n   = address: session.total_checked, dispatch 0, phase 1, work-item 1, step 1\n...\nci[8]> total\n= 5 : I64\n```\n\nThe session runs on `cpu-sir-interp`. The revision line of the report, which this transcript leaves out, names the program the positions refer to."
  },
  {
   "id": "spec-02p:a-staged-inout",
   "edition": "SPEC-02P.1",
   "title": "7.2 A staged `inout`",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#a-staged-inout",
   "internal": 0,
   "content": "### 7.2 A staged `inout`\n\n**Semantics**\n\n1. In a dispatch, an `inout` parameter has the copy-in, copy-out meaning that SPEC-04P.2 6.13.4 states: every read of it gives the element's value from before the dispatch, even after its own work-item has written the element [SPEC-04P.2 P-4].\n\n**Examples**\n\n2. Each work-item writes its element twice. The second statement reads `t[i]` again and gets the value from before the dispatch, not the value the first statement wrote, so the result is ten times the old value:\n\n```cint inout_twice.ci\nkernel bump[n](inout I64[n] t) over [i: n] {\n    t[i] = t[i] + 1;\n    t[i] = t[i] * 10;\n}\n\nvoid run() {\n    I64[3] t = [1, 2, 3];\n    bump(t);\n    \"{t[0]} {t[1]} {t[2]}\\n\";\n}\n\nrun();\n```\n\n```text\n10 20 30\n```"
  },
  {
   "id": "spec-02p:copy-out",
   "edition": "SPEC-02P.1",
   "title": "7.3 Copy-out",
   "clauses": "BACK-10",
   "url": "/specifications/spec-02p/1/#copy-out",
   "internal": 0,
   "content": "### 7.3 Copy-out\n\n**Semantics**\n\n1. <a id=\"B-16d\"></a>Every executor of cint 0.2.0 publishes every output by *copy-out*: it gives the output storage of its own for staging, of the same kind of memory as the output, and on success copies the staged elements into the output. For an `inout`, the staging starts as a copy of the elements before the dispatch. An output in device memory is staged in device memory, never through host memory [P-5, B-16d].\n2. On a fault, the staging is discarded and the outputs are not touched [SPEC-09P.1 BACK-10].\n3. <a id=\"P-5a\"></a>A kernel that a host program calls directly lists each copy of publication in the copy report of its entry (SPEC-03P.1). A dispatch issued from cint source copies the same way and does not list its copies [P-5a].\n4. Storage that an executor uses for its own purposes during a dispatch, such as the fault word and the scratch of 10.5 and 10.6, is not program data and is not listed as a copy [B-16d]."
  },
  {
   "id": "spec-02p:steps-made-of-several-dispatches",
   "edition": "SPEC-02P.1",
   "title": "7.4 Steps made of several dispatches",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#steps-made-of-several-dispatches",
   "internal": 0,
   "content": "### 7.4 Steps made of several dispatches\n\n**Semantics**\n\n1. <a id=\"P-13\"></a>A sequence of dispatches is not published as a unit. A step of a program that needs several dispatches gets all-or-nothing behavior by double buffering: every dispatch of the step writes into a second set of arrays, and the program uses that set as its current state only after the last dispatch of the step succeeds. If a dispatch faults, the entry ends before the exchange and the first set still holds the last complete step [P-13].\n\n**Notes**\n\n2. The worked example of clause 11 alternates two arrays in this way: each dispatch reads one and writes the other."
  },
  {
   "id": "spec-02p:execution-of-a-work-item",
   "edition": "SPEC-02P.1",
   "title": "8 Execution of a work-item",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#execution-of-a-work-item",
   "internal": 0,
   "content": "## 8 Execution of a work-item"
  },
  {
   "id": "spec-02p:independence-of-work-items",
   "edition": "SPEC-02P.1",
   "title": "8.1 Independence of work-items",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#independence-of-work-items",
   "internal": 0,
   "content": "### 8.1 Independence of work-items\n\n**Semantics**\n\n1. A work-item cannot observe another work-item, so every order of running the work-items, concurrent orders included, gives the same staged outputs and the same canonical fault, as SPEC-04P.2 6.13.6 states; contributions to reductions and charges of fuel are combined only by the rules of clause 9 and 8.4 [SPEC-04P.2 X-2].\n2. <a id=\"W-1\"></a>A kernel body has no memory shared between work-items, no barrier, no atomic operation and no other way for work-items to communicate [W-1].\n3. <a id=\"W-2\"></a>Because of paragraphs 1 and 2, the canonical fault can be addressed by work-item and step, and a single work-item can be run again, alone, to describe a fault (10.6) [W-2]."
  },
  {
   "id": "spec-02p:uniform-and-varying-values",
   "edition": "SPEC-02P.1",
   "title": "8.2 Uniform and varying values",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#uniform-and-varying-values",
   "internal": 0,
   "content": "### 8.2 Uniform and varying values\n\n**Semantics**\n\n1. <a id=\"X-3\"></a>Every expression in a kernel body is uniform or varying. Size symbols and scalar `in` parameters are uniform. The over variables are varying. An expression is varying when an operand is varying, when it reads an array element at a varying index, or when it is a local variable assigned under varying control flow; local variables are classified by inference [X-3].\n2. <a id=\"X-5\"></a>The distinction never changes meaning: a varying `if`, `while` or `break` means exactly what it means in the sequential procedure of 5.1, and an executor carries it out by masking, by divergent threads, or in any other way that gives that meaning [X-5].\n3. <a id=\"X-6\"></a>The body is written for one work-item. It has no lane indices, vector types or masks. For `over [y: h, x: w]`, work-item `i` runs with `y = i / w` and `x = i % w`; for more dimensions the tuple is the row-major decomposition of `i` in the same way [X-6].\n\n**Notes**\n\n4. The distinction serves executors in lowering a body and tools in describing it. The single-work-item body and the distinction between uniform and varying values follow the SPMD model of ISPC (Bibliography)."
  },
  {
   "id": "spec-02p:evaluation-inside-a-work-item",
   "edition": "SPEC-02P.1",
   "title": "8.3 Evaluation inside a work-item",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#evaluation-inside-a-work-item",
   "internal": 0,
   "content": "### 8.3 Evaluation inside a work-item\n\n**Semantics**\n\n1. Within a work-item, statements and expressions are evaluated and checked as SPEC-04P.2 6.13.3 states, and an executor may reorder, combine or vectorize the work only when the result, including which fault occurs first and its operands, is unchanged [SPEC-04P.2 X-7]."
  },
  {
   "id": "spec-02p:fuel",
   "edition": "SPEC-02P.1",
   "title": "8.4 Fuel",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#fuel",
   "internal": 0,
   "content": "### 8.4 Fuel\n\nA dispatch is charged fuel in two parts: one unit for each work-item, at entry, and the charges its work-items make as they run, as sequential code would.\n\n**Semantics**"
  },
  {
   "id": "spec-02p:fuel-p1",
   "edition": "SPEC-02P.1",
   "title": "8.4 Fuel (part 2)",
   "clauses": "BACK-09 BACK-12",
   "url": "/specifications/spec-02p/1/#fuel",
   "internal": 0,
   "content": "1. Fuel is charged against the budget of the current entry, as SPEC-04P.2 6.13.6 states; there is no budget per work-item [SPEC-04P.2 X-8].\n2. The dispatch charge of `N` units, one for each work-item, is made once, at entry check 9; if it would take the entry's consumed fuel above its budget, the dispatch faults `E_FUEL` in the entry phase and no work-item runs [SPEC-04P.2 X-8].\n3. Inside a work-item, loop iterations and calls charge one unit each, as in sequential code, and the charges are ordered by ascending work-item index, then by evaluation order within a work-item [SPEC-04P.2 X-8].\n4. The canonical `E_FUEL` fault inside a dispatch is the first charge, in the order of paragraph 3, at which the entry's consumed fuel (everything consumed before the dispatch, plus `N`, plus the charges of every lower work-item, plus the charges this work-item made before) would exceed the budget. Its step ordinal is the number of counted operations the work-item evaluated before the charge [SPEC-04P.2 X-8].\n5. The fuel consumed by a dispatch is that of SPEC-04P.2 6.13.6 and SPEC-09P.1 8.5: on success, `N` plus every charge of every work-item; after a fault at work-item `k`, `N` plus the charges of work-items 0 to `k - 1` plus the charges of `k` made before its fault; after an entry-phase fault, nothing. A charge that faults `E_FUEL` is not counted, and neither is any charge made by a work-item above `k` on an executor that ran it [SPEC-04P.2 X-8] [SPEC-09P.1 BACK-09].\n6. An executor that runs work-items in parallel computes the same consumption and the same canonical fault from the exact prefix sums of the total charges `C(i)` of the work-items, as SPEC-09P.1 8.5 states [SPEC-09P.1 BACK-09].\n7. Running a work-item or a group of work-items again, to describe a fault, charges no fuel (SPEC-09P.1 8.5) [SPEC-09P.1 BACK-12].\n\n**Faults**"
  },
  {
   "id": "spec-02p:fuel-p2",
   "edition": "SPEC-02P.1",
   "title": "8.4 Fuel (part 3)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#fuel",
   "internal": 0,
   "content": "8. `E_FUEL` is raised by a charge that would take the entry's consumed fuel above its budget. The record holds the operation identifier `fuel.charge`, no operands, no exact result and the budget as the limit, an `I64`. In the entry phase its position is the dispatch; inside a work-item, the loop or call that charged.\n\n**Examples**\n\n9. The kernel `count_up` runs a loop of 10 iterations in each of its 1,000 work-items, and work-item 900 overflows. A `cint-workbench` session sets a fuel budget per entry with `:fuel`, and `--check cpu-c17` runs each entry on `cpu-c17` as well as on `cpu-sir-interp` and compares the outcomes. Without a budget the overflow at work-item 900 is reported, after 10,003 units: 2 for the calls of `go` and `run`, 1,000 for the dispatch, 10 for each of work-items 0 to 899, and 1 for the first iteration of work-item 900. With a budget of 6,002, work-item 500 cannot make its first charge, and the fuel fault comes first:\n\n```console\n$ cat budget.ci\nkernel count_up[n](in I64[n] a, out I64[n] r) over [i: n] {\n    I64 acc = a[i];\n    for j in 0..10 {\n        acc = acc + 1;\n    }\n    r[i] = acc;\n}"
  },
  {
   "id": "spec-02p:fuel-p3",
   "edition": "SPEC-02P.1",
   "title": "8.4 Fuel (part 4)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#fuel",
   "internal": 0,
   "content": "export I64 run() {\n    I64[1000] a;\n    I64[1000] r;\n    a[900] = 9223372036854775807;\n    count_up(a, r);\n    return r[999];\n}\n$ cint-workbench budget.ci\n...\nci[1]> :load budget.ci\nloaded budget (budget.ci)\nci[2]> export I64 go() { return budget.run(); }\ngo : () -> I64   revision session@r1\nci[3]> :run go() --check cpu-c17\n...\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> budget.ci:4:19\n...\n   = address: budget.count_up, dispatch 0, phase 1, work-item 900, step 1\n...\n   = fuel-consumed: 10003 (not part of the fault record)\n...\ncheck: cpu-sir-interp and cpu-c17 agree at 1 boundary\nci[4]> :fuel 6002\nfuel: 6002 units per entry\nci[4]> :run go() --check cpu-c17\nfault[E_FUEL]: fuel allowance exhausted\n  --> budget.ci:3:5\n   |\n 3 |     for j in 0..10 {\n   |     ^ fuel.charge\n   |\n   = operation: fuel.charge\n   = operand-count: 0\n   = exact:   none\n   = limit:   I64 6002\n...\n   = address: budget.count_up, dispatch 0, phase 1, work-item 500, step 1\n...\n   = fuel-consumed: 6002 (not part of the fault record)\n...\ncheck: cpu-sir-interp and cpu-c17 agree at 1 boundary\n```\n\nThe step ordinal 1 of the fuel fault counts the read `a[i]`, the one counted operation before the loop's first charge. The fuel consumed, 6,002, does not include the charge that faulted, and the overflow at work-item 900 is not reached."
  },
  {
   "id": "spec-02p:accumulator-widths",
   "edition": "SPEC-02P.1",
   "title": "9.1 Accumulator widths",
   "clauses": "BACK-07 IM-80 R-4 R-5",
   "url": "/specifications/spec-02p/1/#accumulator-widths",
   "internal": 0,
   "content": "### 9.1 Accumulator widths\n\nA `sum` in a kernel adds its contributions exactly and checks only the final total against the target's type. This subclause states how wide an exact sum must be held.\n\n**Semantics**\n\n1. A sum of `n >= 1` values of `w` bits, signed or unsigned, never leaves the range of an accumulator of `w + ceil(log2(n))` bits of the same signedness, in any order of addition, as SPEC-04P.2 7.3 states [SPEC-04P.2 IM-80].\n2. <a id=\"R-5\"></a>Because `n` is at most `MAX(I64)`, below 2^63, the accumulators of Table 2 suffice for every dispatch. An executor shall hold the sum of a `sum` reduction exactly, in these accumulators or by any other method that gives the exact sum, and check it once, at the end, against the target's type [R-5] [SPEC-04P.2 IM-80].\n\nTable 2. Accumulators for `sum`.\n\n| Width of a contribution | Signed contributions | Unsigned contributions |\n|---|---|---|\n| Up to 64 bits | `I128` | 128-bit unsigned |\n| 128 bits | `I256` | 256-bit unsigned |\n| 256 bits | `I512` | 512-bit unsigned |\n| 512 bits | `I1024` | 1024-bit unsigned |\n| 1024 bits | an internal accumulator of 1088 bits, which is not a program type | the same |\n\n3. <a id=\"BACK-07\"></a>The compiler chooses the width of the accumulator before the dispatch, from the largest number of contributions the dispatch can have. With no other bound, that number is `MAX(I64)`, so a `sum` of 64-bit contributions needs 127 bits, and the check of the final total against the target's type is made once [BACK-07].\n4. The other reductions (`fold_checked`, `sum_wrap`, `sum_sat`, `min`, `max` and `count`) act at the width of the contribution type, for every integer type, the wide types included [R-5].\n5. A reduction over a fixed-point type acts on the stored integers of its contributions and gives its result in their format, and no reduction rounds, as SPEC-04P.2 7.3 states [SPEC-04P.2 R-4]."
  },
  {
   "id": "spec-02p:accumulator-widths-p1",
   "edition": "SPEC-02P.1",
   "title": "9.1 Accumulator widths (part 2)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#accumulator-widths",
   "internal": 0,
   "content": "**Examples**\n\n6. This example computes three exact sums. The first passes through `MAX(I64) + 1` and returns to `MAX(I64)` without a fault. The second sums four `I32` maxima into an `I64` target. The third is the first one in `I128`:\n\n```cint acc.ci\nkernel total[n](in I64[n] x, out I64 s) over [i: n] {\n    reduce s = sum(x[i]);\n}\n\nkernel total32[n](in I32[n] x, out I64 s) over [i: n] {\n    reduce s = sum(x[i]);\n}\n\nkernel total128[n](in I128[n] x, out I128 s) over [i: n] {\n    reduce s = sum(x[i]);\n}\n\nvoid run() {\n    I64[3] x = [9223372036854775807, 1, -1];\n    I64 s = 0;\n    total(x, s);\n    \"{s}\\n\";\n    I32[4] y = [2147483647, 2147483647, 2147483647, 2147483647];\n    total32(y, s);\n    \"{s}\\n\";\n    I128[3] z = [I128.max, 1, -1];\n    I128 w = 0;\n    total128(z, w);\n    \"{w}\\n\";\n}\n\nrun();\n```\n\n```text\n9223372036854775807\n8589934588\n170141183460469231731687303715884105727\n```\n\n7. This example reduces `Q16.16` contributions with a `sum` and a `max`:\n\n```cint fixed_reduce.ci\nkernel tot[n](in Q16.16[n] a, out Q16.16 s, out Q16.16 m) over [i: n] {\n    reduce s = sum(a[i]);\n    reduce m = max(a[i]);\n}\n\nvoid go() {\n    Q16.16[3] a = [1.25, -0.5, 2.0];\n    Q16.16 s = 0.0;\n    Q16.16 m = 0.0;\n    tot(a, s, m);\n    \"{s} {m}\\n\";\n}\ngo();\n```\n\n```text\n2.75 2.0\n```"
  },
  {
   "id": "spec-02p:order-of-evaluation",
   "edition": "SPEC-02P.1",
   "title": "9.2 Order of evaluation",
   "clauses": "BACK-08 IM-82 IM-84 IM-85 IM-86 R-10 R-9",
   "url": "/specifications/spec-02p/1/#order-of-evaluation",
   "internal": 0,
   "content": "### 9.2 Order of evaluation\n\n**Semantics**\n\n1. `sum` and `sum_wrap` have no intermediate fault, and the results of `min`, `max` and `count` do not depend on order (SPEC-04P.2 7.3), so an executor may evaluate them in any order or tree [SPEC-04P.2 IM-82, IM-85].\n2. An executor shall give the left-to-right value of `sum_sat`, the fold `acc = acc +| x` from 0 over the contributions in ascending work-item order, as SPEC-04P.2 7.3 states; reassociating `+|` does not conform [SPEC-04P.2 IM-84].\n3. <a id=\"R-10\"></a><a id=\"IM-86\"></a>An executor may compute `sum_sat` in parallel by composing maps. Write `clamp(v, L, H)` for `min(max(v, L), H)`, and `f(c, L, H)` for the map that sends `x` to `clamp(x + c, L, H)`, with `L <= H` and three free parameters. Applying `f(c1, L1, H1)` and then `f(c2, L2, H2)` gives `f(c1 + c2, P, Q)`, with `P = clamp(L1 + c2, L2, H2)` and `Q = clamp(H1 + c2, L2, H2)`. Each contribution `e` is the map `f(e, MIN(T), MAX(T))`, the composed offset `c` is held exactly in the `sum` accumulator, and the result is the composed map applied to 0. The maps are not closed under composition when `L` and `H` are fixed at the type's bounds, and a scan built that way does not conform [R-10, IM-86].\n4. <a id=\"R-9\"></a><a id=\"BACK-08\"></a>An executor may compute `fold_checked(add, init, ...)` in parallel. Before the first fault, the accumulator after contribution `j` equals `init` plus the exact sum of contributions 0 to `j`, so an exact prefix sum in the `sum` accumulator finds the first contribution whose prefix leaves the target's range, and gives the same fault and operands as the sequential fold [R-9, BACK-08].\n\n**Examples**\n\n5. `sum_sat` over `I8` depends on the order of the contributions. In ascending order, `120, 120, -120` gives 120, then 127 by saturation, then 7; `120, -120, 120` gives 120:"
  },
  {
   "id": "spec-02p:order-of-evaluation-p1",
   "edition": "SPEC-02P.1",
   "title": "9.2 Order of evaluation (part 2)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#order-of-evaluation",
   "internal": 0,
   "content": "```cint sat.ci\nkernel total_sat[n](in I8[n] x, out I8 s) over [i: n] {\n    reduce s = sum_sat(x[i]);\n}\n\nvoid run() {\n    I8[3] a = [120, 120, -120];\n    I8[3] b = [120, -120, 120];\n    I8 s = 0;\n    total_sat(a, s);\n    \"{s}\\n\";\n    total_sat(b, s);\n    \"{s}\\n\";\n}\n\nrun();\n```\n\n```text\n7\n120\n```\n\n**Notes**\n\n6. The composition rule of paragraph 3, checked on `I8`: composing `+120` and then `-120` gives the map with `c = 0`, `L = -128` and `H = 7`, which sends 0 to 0 and 10 to 7, as the sequential fold does."
  },
  {
   "id": "spec-02p:fault-attribution",
   "edition": "SPEC-02P.1",
   "title": "9.3 Fault attribution",
   "clauses": "IM-83 R-6 R-7 R-8",
   "url": "/specifications/spec-02p/1/#fault-attribution",
   "internal": 0,
   "content": "### 9.3 Fault attribution\n\n**Semantics**\n\n1. A `fold_checked` overflow that occurs when contribution `k` is added is a fault of work-item `k`, at the step ordinal of its `reduce` statement, with the record that SPEC-04P.2 6.13.5 gives [SPEC-04P.2 R-6, IM-83].\n2. A fault of the epilogue, the final check of a `sum` or a `min` or `max` with no contributions, occurs only when no work-item faulted, and epilogue faults are ordered after every work-item and among themselves by the declaration order of their targets, as SPEC-04P.2 6.13.5 states [SPEC-04P.2 R-7].\n3. If the canonical fault is at work-item `k`, every work-item below `k` completed without a fault (SPEC-04P.2 6.13.6), so the partial result of a fold before `k`, which paragraph 1 uses, is fully defined [SPEC-04P.2 R-8].\n\n**Examples**\n\n4. The reduction comes before the division. At work-item 1 the fold overflows at step 1, before the division by `x[1] - 10 = 0` at step 4:\n\n```cint tie_a.ci\nkernel check[n](in I64[n] x, out I64[n] y, out I64 s) over [i: n] {\n    reduce s = fold_checked(add, 0, x[i]);\n    y[i] = div_round(100, x[i] - 10, floor);\n}\n\nvoid run() {\n    I64[3] x = [9223372036854775807, 10, 0];\n    I64[3] y;\n    I64 s = 0;\n    check(x, y, s);\n}\n\nrun();\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> tie_a.ci:2:16\n   |\n 2 |     reduce s = fold_checked(add, 0, x[i]);\n   |                ^ fold_checked.add.i64\n   |\n   = operation: fold_checked.add.i64\n   = operand-count: 3\n   = operand: I64 1\n   = operand: I64 9223372036854775807\n   = operand: I64 10\n   = exact:   9223372036854775817\n   = limit:   I64 9223372036854775807\n   ...\n   = address: tie_a.check, dispatch 0, phase 1, work-item 1, step 1\n   ...\n```\n\n5. This example puts the same statements in the other order. The division at step 3 now comes before the reduction at step 5:"
  },
  {
   "id": "spec-02p:fault-attribution-p1",
   "edition": "SPEC-02P.1",
   "title": "9.3 Fault attribution (part 2)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#fault-attribution",
   "internal": 0,
   "content": "```cint tie_b.ci\nkernel check[n](in I64[n] x, out I64[n] y, out I64 s) over [i: n] {\n    y[i] = div_round(100, x[i] - 10, floor);\n    reduce s = fold_checked(add, 0, x[i]);\n}\n\nvoid run() {\n    I64[3] x = [9223372036854775807, 10, 0];\n    I64[3] y;\n    I64 s = 0;\n    check(x, y, s);\n}\n\nrun();\n```\n\n```text\nfault[E_DIV_ZERO]: division by zero\n  --> tie_b.ci:2:12\n   |\n 2 |     y[i] = div_round(100, x[i] - 10, floor);\n   |            ^ div_round.checked.i64.floor\n   |\n   = operation: div_round.checked.i64.floor\n   = operand-count: 2\n   = operand: I64 100\n   = operand: I64 0\n   = exact:   none\n   = limit:   none\n   ...\n   = address: tie_b.check, dispatch 0, phase 1, work-item 1, step 3\n   ...\n```\n\n**Notes**\n\n6. When a `fold_checked` overflow and another fault fall on the same work-item, the step ordinal decides between them, as for any two faults of one work-item (5.5). Examples 4 and 5 show both orders."
  },
  {
   "id": "spec-02p:exact-or-refused",
   "edition": "SPEC-02P.1",
   "title": "10.1 Exact or refused",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#exact-or-refused",
   "internal": 0,
   "content": "### 10.1 Exact or refused\n\nAn executor computes every value at its declared width, with its declared behavior on overflow, or it does not run the program. This subclause states that obligation for every executor.\n\n**Semantics**"
  },
  {
   "id": "spec-02p:exact-or-refused-p1",
   "edition": "SPEC-02P.1",
   "title": "10.1 Exact or refused (part 2)",
   "clauses": "IM-123 IM-124 IM-125 IM-126 IM-129",
   "url": "/specifications/spec-02p/1/#exact-or-refused",
   "internal": 0,
   "content": "1. <a id=\"B-1\"></a>An executor shall implement every operation it admits at the declared width of its type and with its declared behavior on overflow. It shall not compute at fewer bits than the type has, substitute wrapping for checked arithmetic, substitute floating point for integers, round differently, drop a check or copy data into another layout without the program's request. Staging for publication (7.3) is part of publication, not a change of layout [B-1] [SPEC-04P.2 IM-129].\n2. An executor that cannot carry out an operation, a type, a width or a layout exactly refuses it with `E_UNSUPPORTED`, naming the operation, the type and the capability: during translation when the need is known then, and otherwise in the entry phase of the dispatch, before any work-item runs [B-1] [SPEC-04P.2 IM-129].\n3. <a id=\"B-2\"></a><a id=\"IM-123\"></a><a id=\"IM-126\"></a>A checked operation is carried out with operations whose result is defined for every input, and its check is made before any result that depends on it is stored: by testing the operands first, by instructions that give a carry or the high half of a product, or by the checked built-in operations of a C compiler. Computing a signed result that overflows, in a language where that is undefined, and testing it afterward does not conform [B-2, IM-123, IM-126].\n4. <a id=\"IM-124\"></a><a id=\"IM-125\"></a>A division or remainder tests for a divisor of 0, and for `MIN(T) / -1`, before any native division instruction. A shift tests its count before any native shift instruction [IM-124, IM-125].\n5. <a id=\"B-3\"></a>Where a target language or machine defines a result for a case that cint treats as a fault, such as a division by 0 that gives a value, the executor tests for the case itself and raises the fault that SPEC-04P.2 defines [B-3]."
  },
  {
   "id": "spec-02p:capability-profiles",
   "edition": "SPEC-02P.1",
   "title": "10.2 Capability profiles",
   "clauses": "BACK-04 BACK-05 BACK-06",
   "url": "/specifications/spec-02p/1/#capability-profiles",
   "internal": 0,
   "content": "### 10.2 Capability profiles\n\n**Semantics**\n\n1. <a id=\"B-4\"></a>Each executor has a capability profile, the capability table of SPEC-09P.1 5.5: for every family of operation, every form of it and every type, an entry that says the executor runs it natively, runs it by a named lowering, or refuses it [B-4] [SPEC-09P.1 BACK-04].\n2. A program that needs an entry the selected executor refuses fails to build, and a device that lacks a capability the build assumed fails to load, with `E_UNSUPPORTED`, as SPEC-09P.1 5.5 states; an executor never falls back to a narrower type [SPEC-09P.1 BACK-05].\n3. An entry that names a lowering is admitted only when the conformance cases of that lowering pass (SPEC-09P.1 5.5) [SPEC-09P.1 BACK-06]."
  },
  {
   "id": "spec-02p:cpu-c17",
   "edition": "SPEC-02P.1",
   "title": "10.3 `cpu-c17`",
   "clauses": "BACK-02",
   "url": "/specifications/spec-02p/1/#cpu-c17",
   "internal": 0,
   "content": "### 10.3 `cpu-c17`\n\n`cpu-c17` translates a program to C17 and compiles it with the system's C compiler. It runs every kernel on the host, one work-item at a time.\n\n**Semantics**\n\n1. <a id=\"B-5\"></a>`cpu-c17` implements every type and operation of `cint-core-1` in kernels as in sequential code: `Bool`, the signed integer types from 8 to 1024 bits, the unsigned ones from 8 to 512 bits, and fixed point, with the accumulators of 9.1 up to the internal 1088-bit one. It runs the work-items of a dispatch in ascending index order, stops at the first fault and produces the complete fault record directly [B-5].\n2. Its output is deterministic, as SPEC-09P.1 7.7 states: the same program gives the same C, with LF line endings, stable numbering and no time stamps or paths [SPEC-09P.1 BACK-02].\n3. <a id=\"B-7\"></a>The C it emits compiles without warnings under `-std=c17 -Wall -Wextra -Wconversion -Wsign-conversion -Wshadow -Wpedantic -Werror` with GCC and Clang, and under `/std:c17 /W4 /WX` with MSVC [B-7].\n\n**Examples**\n\n4. The kernel below uses operators and statements that `gpu-cuda` does not run (10.5): unary minus, the bitwise operators, `max`, a saturating addition, division, a shift, a wrapping conversion, `switch` and a local array. `cpu-c17` and the interpreter run it:\n\n```cint ops_kernel.ci\nkernel ops[n](in I64[n] a, out I64[n] b) over [i: n] {\n    I64 x = a[i];\n    I64 y = -x;\n    I64 z = (x & 6) | (x ^ 3);\n    I64 m = max(x, 2);\n    I64 s = x +| 1;\n    I64 d = x / 2;\n    I64 sh = x << 1;\n    I32 w = x as% I32;\n    I64 sw = 0;\n    switch (x) {\n        case 1: sw = 10;\n        default: sw = 20;\n    }\n    I64[2] loc = [x, x];\n    b[i] = y + z + m + s + d + sh + (w as I64) + sw + loc[1];\n}\n\nvoid go() {\n    I64[3] a = [1, 2, 3];\n    I64[3] b;\n    ops(a, b);\n    \"{b[0]} {b[1]} {b[2]}\\n\";\n}\ngo();\n```\n\n```text\n19 35 39\n```"
  },
  {
   "id": "spec-02p:cpu-c17-p1",
   "edition": "SPEC-02P.1",
   "title": "10.3 `cpu-c17` (part 2)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#cpu-c17",
   "internal": 0,
   "content": "5. The kernel below writes an output of 8-bit elements:\n\n```cint narrow_out.ci\nkernel half[n](in U8[n] a, out U8[n] b) over [i: n] {\n    b[i] = a[i] / 2;\n}\n\nvoid go() {\n    U8[3] a = [10, 20, 255];\n    U8[3] b;\n    half(a, b);\n    \"{b[0]} {b[1]} {b[2]}\\n\";\n}\ngo();\n```\n\n```text\n5 10 127\n```\n\n6. The kernel below computes over `I128`:\n\n```cint wide_kernel.ci\nkernel sq[n](in I128[n] a, out I128[n] b) over [i: n] {\n    b[i] = a[i] * a[i];\n}\n\nvoid go() {\n    I128[2] a = [9223372036854775807, 3];\n    I128[2] b;\n    sq(a, b);\n    \"{b[0]} {b[1]}\\n\";\n}\ngo();\n```\n\n```text\n85070591730234615847396907784232501249 9\n```\n\n7. The kernel below computes over the fixed-point type `Q16.16`:\n\n```cint fixed_kernel.ci\nkernel half[n](in Q16.16[n] a, out Q16.16[n] b) over [i: n] {\n    b[i] = a[i] * 0.5;\n}\n\nvoid go() {\n    Q16.16[2] a = [3.0, -1.5];\n    Q16.16[2] b;\n    half(a, b);\n    \"{b[0]} {b[1]}\\n\";\n}\ngo();\n```\n\n```text\n1.5 -0.75\n```\n\n8. The kernel below computes over `U128`:\n\n```cint u128_kernel.ci\nkernel inc[n](in U128[n] a, out U128[n] b) over [i: n] {\n    b[i] = a[i] + 1;\n}\n\nvoid go() {\n    U128[2] a = [18446744073709551615, 3];\n    U128[2] b;\n    inc(a, b);\n    \"{b[0]} {b[1]}\\n\";\n}\ngo();\n```\n\n```text\n18446744073709551616 4\n```"
  },
  {
   "id": "spec-02p:cpu-sir-interp",
   "edition": "SPEC-02P.1",
   "title": "10.4 `cpu-sir-interp`",
   "clauses": "BACK-01 BACK-01a",
   "url": "/specifications/spec-02p/1/#cpu-sir-interp",
   "internal": 0,
   "content": "### 10.4 `cpu-sir-interp`\n\n`cpu-sir-interp` is the interpreter, `cint-interp`. It runs a program from the text of its intermediate representation, with no C compiler.\n\n**Semantics**\n\n1. `cpu-sir-interp` reads the text of the intermediate representation that the compiler writes for each module, checks it and runs it, as SPEC-09P.1 5.3 states [SPEC-09P.1 BACK-01a].\n2. For every arithmetic operation, conversion and built-in operation, it calls the same run-time routine that the C of `cpu-c17` calls, so it adds no arithmetic of its own; it runs the work-items of each dispatch one at a time in ascending order, and counts step ordinals as 5.4 states [SPEC-09P.1 BACK-01a].\n3. It is not part of the compiler, while the code generators of the other executors are, as SPEC-09P.1 5.3 states [SPEC-09P.1 BACK-01].\n4. `cint-workbench`, `cint-repl` and `cint-debug` run programs on `cpu-sir-interp`, and `cint-workbench` can compare each entry with `cpu-c17` (8.4, example 9). SPEC-06P.1 describes these tools."
  },
  {
   "id": "spec-02p:gpu-cuda",
   "edition": "SPEC-02P.1",
   "title": "10.5 `gpu-cuda`",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#gpu-cuda",
   "internal": 0,
   "content": "### 10.5 `gpu-cuda`\n\n`gpu-cuda` runs the work-item phase of each dispatch on an NVIDIA GPU and everything else on the host. Its capability profile admits the 64-bit and narrower integer types and a subset of the operations; it refuses the rest during translation.\n\n**Semantics**"
  },
  {
   "id": "spec-02p:gpu-cuda-p1",
   "edition": "SPEC-02P.1",
   "title": "10.5 `gpu-cuda` (part 2)",
   "clauses": "BACK-04 BACK-16",
   "url": "/specifications/spec-02p/1/#gpu-cuda",
   "internal": 0,
   "content": "1. <a id=\"B-16a\"></a>A `gpu-cuda` program is the `cpu-c17` program together with device code for each kernel. The C that cint emits for a module carries that device code: compiled as it is, the C is the `cpu-c17` program and compiled with the macro `CINT_GPU_CUDA` defined and linked with the run-time files `rt/cint_cuda.c` and `rt/cint_cuda_dispatch.c`, it is the `gpu-cuda` program. The host runs the sequential code, the entry checks of 5.3, publication, the final fold of each reduction and the description of a fault by running one work-item again (10.6). The device runs only the bodies of work-items. Every kernel of a `gpu-cuda` program runs on the device [B-16a] [SPEC-09P.1 BACK-16].\n2. <a id=\"B-16\"></a>The device code is PTX text, version 6.0 for target `sm_52` with 64-bit addresses: one module for each cint module that defines kernels, held in that module's C as an array of string literals, one for each line and loaded through the CUDA driver API (section 6.27, Module Management) at the first dispatch of one of its kernels. No NVIDIA compiler takes part in a build [B-16].\n3. In the device code, every value is held in a 64-bit register. A checked operation of 8, 16 or 32 bits computes its exact result in 64 bits and tests that the result fits its type. A checked operation of 64 bits tests the signs of its operands and its result for addition and subtraction, and the high half of the product, from `mul.hi`, for multiplication. Each test branches to the work-item's fault path before any result that depends on it is stored. No CUDA C++ is generated, so the undefined signed overflow of CUDA C++ does not arise. Element addresses are formed only after the view is admitted, from checked `I64` index arithmetic [B-16].\n4. Work-item `i` runs in thread `i`: the block index times the block size plus the thread index, over a one-dimensional grid, plus the first index of the lau"
  },
  {
   "id": "spec-02p:gpu-cuda-p2",
   "edition": "SPEC-02P.1",
   "title": "10.5 `gpu-cuda` (part 3)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#gpu-cuda",
   "internal": 0,
   "content": "Table 3. The capability profile of `gpu-cuda`.\n\n| Field | Content |\n|---|---|\n| Native types | `Bool`, `I8` to `I64`, `U8` to `U64`, as values and as element types of `in` arrays |\n| Native operations | checked and wrapping `+`, `-` and `*`; comparisons; `&&`, `||` and `!` on `Bool`; the checked conversion `as` between the native types; `div_round` in every rounding mode; `if`, `else`, `for`, `while`, `break` and `continue`; fuel charges; element reads; element stores into outputs of `I32`, `U32`, `I64` and `U64`; `reduce` in every form over contributions of the native types |\n| Lowered | none |\n| Fault word | `U64` in device memory (10.6) |\n| Work-items per dispatch | up to `MAX(I64)`, in launches over ascending ranges |\n| Placements | host memory that the context owns and maps for the device, and device memory |\n\n11. The capabilities that `gpu-cuda` refuses, each with the name that its refusal gives:"
  },
  {
   "id": "spec-02p:gpu-cuda-p3",
   "edition": "SPEC-02P.1",
   "title": "10.5 `gpu-cuda` (part 4)",
   "clauses": "BACK-05",
   "url": "/specifications/spec-02p/1/#gpu-cuda",
   "internal": 0,
   "content": "| Capability | What needs it |\n|---|---|\n| `wide` | a value, element or operand of an integer type wider than 64 bits |\n| `sat` | a saturating operator |\n| `result` | a result form, or an error value |\n| `div` | `/` or `%` |\n| `shift` | a shift |\n| `bits` | `&`, `|`, `^` or `~` |\n| `neg` | unary minus |\n| `as.wrap` | the conversions `as%` and `as?` |\n| `builtin` | a built-in operation other than `div_round`, such as `min`, `max` or `abs` |\n| `switch` | a `switch` statement |\n| `store.narrow` | a store into an output whose elements are `Bool` or of 8 or 16 bits |\n| `array` | a local array |\n| `struct` | a struct value |\n| `view.make` | forming a view inside the body |\n| `reduce.view` | a reduction over a whole view inside the body |\n| `call` | a call of a function |\n| `print`, `assert` | printing or asserting inside the body |\n| `state` | a module-level variable |\n| `outer.write` | an assignment to a variable that the work-item body does not declare |\n| `params` | a kernel whose parameters need more than 4,096 bytes, or more than 61 parameters |\n| `node` | any other construct, fixed-point values included |\n\n12. A program that needs a refused capability does not build for `gpu-cuda`: the build fails with `E_UNSUPPORTED`, naming the first refused construct of the module's kernels, the kernel, the capability and the line and column of the construct (10.2). The same program builds and runs on `cpu-c17` [SPEC-09P.1 BACK-05].\n\n**Examples**\n\n13. The kernel `ops` of 10.3, example 4, does not build for `gpu-cuda`: its first refused construct is the unary minus at 3:13, capability `neg`. The kernel `half` of 10.3, example 5, is refused at its division at 2:17, capability `div`, and a kernel that copies a `U8` input to a `U8` output is refused at its store, capability `store.narrow`. The kernel `sq` of example 6 is refused with `wide`.\n\n**Notes**"
  },
  {
   "id": "spec-02p:gpu-cuda-p4",
   "edition": "SPEC-02P.1",
   "title": "10.5 `gpu-cuda` (part 5)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#gpu-cuda",
   "internal": 0,
   "content": "14. Table 3 is the profile of cint 0.2.0. Clause 12 names further lowerings, which this profile does not include."
  },
  {
   "id": "spec-02p:the-fault-protocol-on-a-gpu",
   "edition": "SPEC-02P.1",
   "title": "10.6 The fault protocol on a GPU",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#the-fault-protocol-on-a-gpu",
   "internal": 0,
   "content": "### 10.6 The fault protocol on a GPU\n\nOn a GPU, many work-items run at once and several may fault. The protocol of this subclause finds the canonical fault with one word of device memory per dispatch, and describes it by running one work-item again on the host.\n\n**Semantics**"
  },
  {
   "id": "spec-02p:the-fault-protocol-on-a-gpu-p1",
   "edition": "SPEC-02P.1",
   "title": "10.6 The fault protocol on a GPU (part 2)",
   "clauses": "BACK-13 IM-115 IM-116",
   "url": "/specifications/spec-02p/1/#the-fault-protocol-on-a-gpu",
   "internal": 0,
   "content": "1. <a id=\"F-9\"></a><a id=\"B-16b\"></a>For each dispatch, `gpu-cuda` keeps a fault word, a `U64` in device memory set to all ones, the value that stands for no fault, before the first launch [F-9, B-16b].\n2. <a id=\"F-10\"></a><a id=\"BACK-13\"></a>Each work-item `i` follows this protocol [F-10, BACK-13]:\n   1. When it starts, it reads the fault word and exits at once, writing nothing, if the word is below `i`: such a work-item cannot be canonical.\n   2. It runs the body, testing each checked operation before it computes it.\n   3. On a fault, it takes the atomic minimum of the fault word and `i` (`atom.global.min.u64`) and exits without any further write. Nothing else about the fault is kept on the device.\n   4. On completion, its writes are already in staging.\n3. A work-item below the final value of the fault word never exits early, because the word never falls below its final value. Every work-item below the canonical one therefore runs to its end, as 9.3 requires [F-10].\n4. <a id=\"F-11\"></a>After the device completes, the host takes `k_b`, the value of the fault word; `k_f`, the work-item of the first fuel fault (10.5, paragraph 6); and `k_r`, the work-item of the first `fold_checked` overflow, from its fold (10.5, paragraph 7). Let `k` be the least of the three that exists [F-11, B-16b].\n5. If `k` exists, the host runs work-item `k` again, in the `cpu-c17` code of the same kernel from the same program, with the inputs from before the dispatch, the uniform arguments, the partial result of each `fold_checked` before `k`, and the fuel consumed before `k`. The first fault of that run is the canonical fault, so its record, position, stack, operands and step ordinal are those that `cpu-c17` reports. Inputs in device memory are read back to the host for this run, and the read-back is listed in the entry's copy report (SPEC-03P.1). If none of `k_b`, `k_r` and `k_f` exists, the "
  },
  {
   "id": "spec-02p:the-fault-protocol-on-a-gpu-p2",
   "edition": "SPEC-02P.1",
   "title": "10.6 The fault protocol on a GPU (part 3)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#the-fault-protocol-on-a-gpu",
   "internal": 0,
   "content": "**Notes**\n\n9. Running one work-item again is sound because work-items are independent (8.1): its inputs are intact, since `in` arguments are never written and staged outputs are not published. The re-run is not charged fuel (8.4, paragraph 7)."
  },
  {
   "id": "spec-02p:worked-example-heat-diffusion",
   "edition": "SPEC-02P.1",
   "title": "11 Worked example: heat diffusion",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#worked-example-heat-diffusion",
   "internal": 0,
   "content": "## 11 Worked example: heat diffusion\n\nThis clause takes one kernel through the rules of this document: an explicit step of the heat equation on a grid of `I32` temperatures, in raw units. The diffusion number is the rational `kn / kd`. Cells on the edge of the grid are held at their values. Each interior update rounds once, to nearest with ties to even, and the kernel also reports the exact total of the new grid. Every example of this clause runs on `cpu-c17` and on the interpreter, and every operation of the kernel is in the profile of `gpu-cuda` (Table 3); the conformance suite of SPEC-09P.1 holds cases of this kernel and compares their outcomes with the reference on `cpu-c17` and on `gpu-cuda`."
  },
  {
   "id": "spec-02p:the-kernel-and-one-step",
   "edition": "SPEC-02P.1",
   "title": "11.1 The kernel and one step",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#the-kernel-and-one-step",
   "internal": 0,
   "content": "### 11.1 The kernel and one step\n\n1. Line numbers in the records of this clause refer to the kernel as listed, counted from its first line. The program below takes one step from a hot spot of 65536 at `(3, 4)` on an 8 by 8 grid, with `kn = 1` and `kd = 8`. At the center the Laplacian is `-4 * 65536` and the flux `-32768`, so the center keeps 32768, and each of the four neighbors receives 8192. The total is unchanged:\n\n```cint heat_spot.ci\nkernel diffuse[h, w](\n    in  I32[h, w] u,\n    in  I64       kn,\n    in  I64       kd,\n    out I32[h, w] v,\n    out I64       total\n) over [y: h, x: w] {\n    I64 c = u[y, x] as I64;\n    I32 r = u[y, x];\n    if (y > 0 && y < h - 1 && x > 0 && x < w - 1) {\n        I64 lap = (u[y - 1, x] as I64) + (u[y + 1, x] as I64)\n                + (u[y, x - 1] as I64) + (u[y, x + 1] as I64) - 4 * c;\n        I64 flux = div_round(kn * lap, kd, half_even);\n        r = (c + flux) as I32;\n    }\n    v[y, x] = r;\n    reduce total = sum(r);\n}\n\nvoid step(I32 spot, I32 level) {\n    I32[8, 8] a;\n    I32[8, 8] b;\n    if (level != 0) {\n        for y in 0..8 {\n            for x in 0..8 {\n                a[y, x] = level;\n            }\n        }\n    }\n    a[3, 4] = spot;\n    I64 total = 0;\n    diffuse(a, 1, 8, b, total);\n    \"center {b[3, 4]}, neighbors {b[2, 4]} {b[4, 4]} {b[3, 3]} {b[3, 5]}, total {total}\\n\";\n}\n\nstep(65536, 0);\nstep(12, 0);\nstep(-4, 0);\nstep(2147483647, 2147483647);\n```\n\n```text\ncenter 32768, neighbors 8192 8192 8192 8192, total 65536\ncenter 6, neighbors 2 2 2 2, total 14\ncenter -2, neighbors 0 0 0 0, total -2\ncenter 2147483647, neighbors 2147483647 2147483647 2147483647 2147483647, total 137438953408\n```"
  },
  {
   "id": "spec-02p:the-kernel-and-one-step-p1",
   "edition": "SPEC-02P.1",
   "title": "11.1 The kernel and one step (part 2)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#the-kernel-and-one-step",
   "internal": 0,
   "content": "2. The second and third lines show the rounding. From a spot of 12, each neighbor's exact flux is 12 / 8 = 1.5, which rounds to the even 2, and the total grows to 14. From a spot of -4, each neighbor's exact flux is -0.5, which rounds to 0, and the total is -2. Rounding can add or remove heat; the result is exact and the same on every executor.\n3. In the last line every cell holds `MAX(I32)`, so every Laplacian is 0 and every cell keeps its value. The total, 64 times 2147483647, is 137438953408, which is held exactly in the `I128` accumulator of the `sum` (9.1) and fits the `I64` target."
  },
  {
   "id": "spec-02p:step-ordinals-of-a-work-item",
   "edition": "SPEC-02P.1",
   "title": "11.2 Step ordinals of a work-item",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#step-ordinals-of-a-work-item",
   "internal": 0,
   "content": "### 11.2 Step ordinals of a work-item\n\n1. An interior work-item evaluates 28 counted operations (5.4); the widening conversions `as I64` count:\n\n| Step | Line | Operation | Step | Line | Operation |\n|---|---|---|---|---|---|\n| 0 | 8 | read `u[y, x]` | 14 | 12 | `as I64` |\n| 1 | 8 | `as I64` | 15 | 12 | `+` |\n| 2 | 9 | read `u[y, x]` | 16 | 12 | `x + 1` |\n| 3 | 10 | `h - 1` | 17 | 12 | read `u[y, x + 1]` |\n| 4 | 10 | `w - 1` | 18 | 12 | `as I64` |\n| 5 | 11 | `y - 1` | 19 | 12 | `+` |\n| 6 | 11 | read `u[y - 1, x]` | 20 | 12 | `4 * c` |\n| 7 | 11 | `as I64` | 21 | 12 | `-` |\n| 8 | 11 | `y + 1` | 22 | 13 | `kn * lap` |\n| 9 | 11 | read `u[y + 1, x]` | 23 | 13 | `div_round` |\n| 10 | 11 | `as I64` | 24 | 14 | `c + flux` |\n| 11 | 11 | `+` | 25 | 14 | `as I32` |\n| 12 | 12 | `x - 1` | 26 | 16 | place `v[y, x]` |\n| 13 | 12 | read `u[y, x - 1]` | 27 | 17 | `reduce` (`sum`) |\n\n2. A work-item in row 0 stops the condition at `y > 0` and evaluates steps 0 to 2, then the place `v[y, x]` as step 3 and the `reduce` as step 4. The kernel has no loop and no call, so a dispatch over an `h` by `w` grid consumes `h * w` units of fuel, its dispatch charge."
  },
  {
   "id": "spec-02p:faults",
   "edition": "SPEC-02P.1",
   "title": "11.3 Faults",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#faults",
   "internal": 0,
   "content": "### 11.3 Faults\n\n1. The first case is an overflow. With `u[3, 4] = 1000`, `kn = 2^61` and `kd = MAX(I64)`, the interior work-items with a nonzero Laplacian are 20, 27, 28, 29 and 36: the spot and its four neighbors. Work-item 20, `(2, 4)`, is the least and its product `kn * lap` (step 22) overflows before `div_round` (step 23):\n\n```cint heat_e1.ci\nkernel diffuse[h, w](\n    in  I32[h, w] u,\n    in  I64       kn,\n    in  I64       kd,\n    out I32[h, w] v,\n    out I64       total\n) over [y: h, x: w] {\n    I64 c = u[y, x] as I64;\n    I32 r = u[y, x];\n    if (y > 0 && y < h - 1 && x > 0 && x < w - 1) {\n        I64 lap = (u[y - 1, x] as I64) + (u[y + 1, x] as I64)\n                + (u[y, x - 1] as I64) + (u[y, x + 1] as I64) - 4 * c;\n        I64 flux = div_round(kn * lap, kd, half_even);\n        r = (c + flux) as I32;\n    }\n    v[y, x] = r;\n    reduce total = sum(r);\n}\n\nvoid step() {\n    I32[8, 8] a;\n    I32[8, 8] b;\n    a[3, 4] = 1000;\n    I64 total = 0;\n    diffuse(a, 2305843009213693952, 9223372036854775807, b, total);\n    \"{total}\\n\";\n}\n\nstep();\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> heat_e1.ci:13:33\n   |\n13 |         I64 flux = div_round(kn * lap, kd, half_even);\n   |                                 ^ mul.checked.i64\n   |\n   = operation: mul.checked.i64\n   = operand-count: 2\n   = operand: I64 2305843009213693952\n   = operand: I64 1000\n   = exact:   2305843009213693952000\n   = limit:   I64 9223372036854775807\n   ...\n   = address: heat_e1.diffuse, dispatch 0, phase 1, work-item 20, step 22\n   ...\n```\n\n2. The second case is a narrowing. With `u[3, 4] = MAX(I32)` and `kn = kd = 1`, work-items 20 and 27 compute `r = 2147483647`, which fits. At work-item 28, the spot, the Laplacian is `-4 * 2147483647`, the flux equals it, and `c + flux = -6442450941` does not fit `I32`:"
  },
  {
   "id": "spec-02p:faults-p1",
   "edition": "SPEC-02P.1",
   "title": "11.3 Faults (part 2)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#faults",
   "internal": 0,
   "content": "```cint heat_e2.ci\nkernel diffuse[h, w](\n    in  I32[h, w] u,\n    in  I64       kn,\n    in  I64       kd,\n    out I32[h, w] v,\n    out I64       total\n) over [y: h, x: w] {\n    I64 c = u[y, x] as I64;\n    I32 r = u[y, x];\n    if (y > 0 && y < h - 1 && x > 0 && x < w - 1) {\n        I64 lap = (u[y - 1, x] as I64) + (u[y + 1, x] as I64)\n                + (u[y, x - 1] as I64) + (u[y, x + 1] as I64) - 4 * c;\n        I64 flux = div_round(kn * lap, kd, half_even);\n        r = (c + flux) as I32;\n    }\n    v[y, x] = r;\n    reduce total = sum(r);\n}\n\nvoid step() {\n    I32[8, 8] a;\n    I32[8, 8] b;\n    a[3, 4] = 2147483647;\n    I64 total = 0;\n    diffuse(a, 1, 1, b, total);\n    \"{total}\\n\";\n}\n\nstep();\n```\n\n```text\nfault[E_NARROW]: the value does not fit the destination type\n  --> heat_e2.ci:14:24\n   |\n14 |         r = (c + flux) as I32;\n   |                        ^ as.checked.i64.i32\n   |\n   = operation: as.checked.i64.i32\n   = operand-count: 1\n   = operand: I64 -6442450941\n   = exact:   -6442450941\n   = limit:   I32 -2147483648\n   ...\n   = address: heat_e2.diffuse, dispatch 0, phase 1, work-item 28, step 25\n   ...\n```\n\n3. The third case is a division by 0. With `kd = 0`, the first interior work-item, 9, faults in `div_round` although its Laplacian is 0: the divisor is checked whatever the dividend:\n\n```cint heat_e9.ci\nkernel diffuse[h, w](\n    in  I32[h, w] u,\n    in  I64       kn,\n    in  I64       kd,\n    out I32[h, w] v,\n    out I64       total\n) over [y: h, x: w] {\n    I64 c = u[y, x] as I64;\n    I32 r = u[y, x];\n    if (y > 0 && y < h - 1 && x > 0 && x < w - 1) {\n        I64 lap = (u[y - 1, x] as I64) + (u[y + 1, x] as I64)\n                + (u[y, x - 1] as I64) + (u[y, x + 1] as I64) - 4 * c;\n        I64 flux = div_round(kn * lap, kd, half_even);\n        r = (c + flux) as I32;\n    }\n    v[y, x] = r;\n    reduce total = sum(r);\n}"
  },
  {
   "id": "spec-02p:faults-p2",
   "edition": "SPEC-02P.1",
   "title": "11.3 Faults (part 3)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#faults",
   "internal": 0,
   "content": "void step() {\n    I32[8, 8] a;\n    I32[8, 8] b;\n    a[3, 4] = 1;\n    I64 total = 0;\n    diffuse(a, 1, 0, b, total);\n    \"{total}\\n\";\n}\n\nstep();\n```\n\n```text\nfault[E_DIV_ZERO]: division by zero\n  --> heat_e9.ci:13:20\n   |\n13 |         I64 flux = div_round(kn * lap, kd, half_even);\n   |                    ^ div_round.checked.i64.half_even\n   |\n   = operation: div_round.checked.i64.half_even\n   = operand-count: 2\n   = operand: I64 0\n   = operand: I64 0\n   = exact:   none\n   = limit:   none\n   ...\n   = address: heat_e9.diffuse, dispatch 0, phase 1, work-item 9, step 23\n   ...\n```"
  },
  {
   "id": "spec-02p:three-reductions-of-the-same-data",
   "edition": "SPEC-02P.1",
   "title": "11.4 Three reductions of the same data",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#three-reductions-of-the-same-data",
   "internal": 0,
   "content": "### 11.4 Three reductions of the same data\n\n1. With every cell at `MAX(I32)`, the `I64` total of 11.1 succeeds. The same data with the target `total` declared `I32` gives two other outcomes, because the programs ask for two other operations. With `sum`, no work-item faults, and the epilogue finds that the exact total 137438953408 of 64 contributions does not fit `I32`:\n\n```cint heat_sum32.ci\nkernel diffuse[h, w](\n    in  I32[h, w] u,\n    in  I64       kn,\n    in  I64       kd,\n    out I32[h, w] v,\n    out I32       total\n) over [y: h, x: w] {\n    I64 c = u[y, x] as I64;\n    I32 r = u[y, x];\n    if (y > 0 && y < h - 1 && x > 0 && x < w - 1) {\n        I64 lap = (u[y - 1, x] as I64) + (u[y + 1, x] as I64)\n                + (u[y, x - 1] as I64) + (u[y, x + 1] as I64) - 4 * c;\n        I64 flux = div_round(kn * lap, kd, half_even);\n        r = (c + flux) as I32;\n    }\n    v[y, x] = r;\n    reduce total = sum(r);\n}\n\nvoid step() {\n    I32[8, 8] a;\n    I32[8, 8] b;\n    for y in 0..8 {\n        for x in 0..8 {\n            a[y, x] = 2147483647;\n        }\n    }\n    I32 total = 0;\n    diffuse(a, 1, 8, b, total);\n    \"{total}\\n\";\n}\n\nstep();\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> heat_sum32.ci:17:20\n   |\n17 |     reduce total = sum(r);\n   |                    ^ sum.checked.i32.i32\n   |\n   = operation: sum.checked.i32.i32\n   = operand-count: 1\n   = operand: I64 64\n   = exact:   137438953408\n   = limit:   I32 2147483647\n   ...\n   = address: heat_sum32.diffuse, dispatch 0, phase 2, work-item none, step none\n   ...\n```\n\n2. With `fold_checked`, the fold overflows when the contribution of work-item 1, `(0, 1)`, is added. Work-item 1 is in row 0, so its `reduce` is step 4 (11.2, paragraph 2):"
  },
  {
   "id": "spec-02p:three-reductions-of-the-same-data-p1",
   "edition": "SPEC-02P.1",
   "title": "11.4 Three reductions of the same data (part 2)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#three-reductions-of-the-same-data",
   "internal": 0,
   "content": "```cint heat_fold32.ci\nkernel diffuse[h, w](\n    in  I32[h, w] u,\n    in  I64       kn,\n    in  I64       kd,\n    out I32[h, w] v,\n    out I32       total\n) over [y: h, x: w] {\n    I64 c = u[y, x] as I64;\n    I32 r = u[y, x];\n    if (y > 0 && y < h - 1 && x > 0 && x < w - 1) {\n        I64 lap = (u[y - 1, x] as I64) + (u[y + 1, x] as I64)\n                + (u[y, x - 1] as I64) + (u[y, x + 1] as I64) - 4 * c;\n        I64 flux = div_round(kn * lap, kd, half_even);\n        r = (c + flux) as I32;\n    }\n    v[y, x] = r;\n    reduce total = fold_checked(add, 0, r);\n}\n\nvoid step() {\n    I32[8, 8] a;\n    I32[8, 8] b;\n    for y in 0..8 {\n        for x in 0..8 {\n            a[y, x] = 2147483647;\n        }\n    }\n    I32 total = 0;\n    diffuse(a, 1, 8, b, total);\n    \"{total}\\n\";\n}\n\nstep();\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> heat_fold32.ci:17:20\n   |\n17 |     reduce total = fold_checked(add, 0, r);\n   |                    ^ fold_checked.add.i32\n   |\n   = operation: fold_checked.add.i32\n   = operand-count: 3\n   = operand: I64 1\n   = operand: I32 2147483647\n   = operand: I32 2147483647\n   = exact:   4294967294\n   = limit:   I32 2147483647\n   ...\n   = address: heat_fold32.diffuse, dispatch 0, phase 1, work-item 1, step 4\n   ...\n```"
  },
  {
   "id": "spec-02p:forty-steps-by-double-buffering",
   "edition": "SPEC-02P.1",
   "title": "11.5 Forty steps by double buffering",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#forty-steps-by-double-buffering",
   "internal": 0,
   "content": "### 11.5 Forty steps by double buffering\n\n1. A run of 40 steps on a 16 by 16 grid alternates two arrays, as 7.4 describes: each dispatch reads one and writes the other. The total falls from 65536 because the edge cells are held at 0, so heat that reaches the edge leaves the grid, and rounding adds or removes a unit here and there:\n\n```cint heat_tour.ci\nkernel diffuse[h, w](\n    in  I32[h, w] u,\n    in  I64       kn,\n    in  I64       kd,\n    out I32[h, w] v,\n    out I64       total\n) over [y: h, x: w] {\n    I64 c = u[y, x] as I64;\n    I32 r = u[y, x];\n    if (y > 0 && y < h - 1 && x > 0 && x < w - 1) {\n        I64 lap = (u[y - 1, x] as I64) + (u[y + 1, x] as I64)\n                + (u[y, x - 1] as I64) + (u[y, x + 1] as I64) - 4 * c;\n        I64 flux = div_round(kn * lap, kd, half_even);\n        r = (c + flux) as I32;\n    }\n    v[y, x] = r;\n    reduce total = sum(r);\n}\n\nvoid tour() {\n    I32[16, 16] a;\n    I32[16, 16] b;\n    a[8, 8] = 65536;\n    I64 heat = 0;\n    for t in 0..20 {\n        diffuse(a, 1, 8, b, heat);\n        diffuse(b, 1, 8, a, heat);\n    }\n    \"after 40 steps: total={heat} center={a[8, 8]} edge={a[1, 8]}\\n\";\n}\n\ntour();\n```\n\n```text\nafter 40 steps: total=60150 center=1042 edge=72\n```\n\n2. The interpreter prints the same line from the same program. Every operation of the kernel is in the profile of `gpu-cuda` (Table 3), so the program also builds for `gpu-cuda`, which runs the 40 dispatches on the device and is required by clause 4 to print the same line."
  },
  {
   "id": "spec-02p:future-directions",
   "edition": "SPEC-02P.1",
   "title": "12 Future directions",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#future-directions",
   "internal": 0,
   "content": "## 12 Future directions\n\nThis clause is informative. It names work that cint 0.2.0 does not implement, in one or two sentences each, and makes no promise about any of it."
  },
  {
   "id": "spec-02p:future-directions-p1",
   "edition": "SPEC-02P.1",
   "title": "12 Future directions (part 2)",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#future-directions",
   "internal": 0,
   "content": "1. In-place dispatch. A dispatch that writes its `inout` arguments directly, without staging, with a stated contract for what a fault leaves in them and no rollback.\n2. Schedules. A separate declaration that asks an executor to tile, vectorize, parallelize or place a kernel on a device, or requires it to, and that cannot change any outcome of a dispatch, including fuel.\n3. Declared lower bounds. Array parameters indexed from a declared lower bound, such as `1..=n`, which change only the translation from index to offset.\n4. Workgroup memory and barriers. Memory shared within a group of work-items, with barriers whose meaning is deterministic, and a fault order extended to the group and the phase between barriers.\n5. Calls in kernel bodies. Calls of functions that read no mutable state, perform no I/O and do not recurse, with their counted operations in the caller's step sequence.\n6. `fold_checked(mul, ...)` in kernels, which needs exact prefix products to locate its first overflow in parallel.\n7. Publication without copying. Publication by exchanging the storage of an output that covers its whole buffer, a requirement that a dispatch publish without copying, and the listing of every copy of a dispatch issued from cint source.\n8. Other executors. A C executor with SIMD lanes; executors for other kinds of device; and evaluation of a narrow type in place of `I64` where a bound checked at entry shows that every intermediate value fits.\n9. Lowerings for `gpu-cuda`. The capabilities that Table 3 refuses, wide integers by limb sequences, fixed point with 128-bit intermediates, outputs of 8- and 16-bit elements and reductions evaluated on the device.\n10. Diagnostic orders. Running the work-items of a dispatch in descending or permuted order, without stopping at the first fault, to test that the canonical fault does not depend on the order.\n11. Counter-based random numbers. A p"
  },
  {
   "id": "spec-02p:bibliography",
   "edition": "SPEC-02P.1",
   "title": "Bibliography",
   "clauses": "",
   "url": "/specifications/spec-02p/1/#bibliography",
   "internal": 0,
   "content": "## Bibliography\n\n- Guy E. Blelloch. *Prefix Sums and Their Applications*. Technical Report CMU-CS-90-190, School of Computer Science, Carnegie Mellon University, November 1990. The prefix sums of 9.2 and 10.5.\n- NumPy Developers. \"numpy.shares_memory.\" *NumPy Reference* (NumPy v2.5 Manual). https://numpy.org/doc/stable/reference/generated/numpy.shares_memory.html. The overlap question of 6.3.\n- Matt Pharr and William R. Mark. \"ispc: A SPMD Compiler for High-Performance CPU Programming.\" *2012 Innovative Parallel Computing (InPar)*, pages 1-13, May 2012. DOI 10.1109/InPar.2012.6339601. The uniform and varying values of 8.2."
  },
  {
   "id": "spec-02p:annex-a-informative-clause-identifiers-stated-in",
   "edition": "SPEC-02P.1",
   "title": "Annex A (informative) Clause identifiers stated in other editions",
   "clauses": "K-1 K-10 K-10a K-11 K-12 K-2 K-3 K-4 K-5 K-6 K-8 R-1",
   "url": "/specifications/spec-02p/1/#annex-a-informative-clause-identifiers-stated-in-other-editions",
   "internal": 0,
   "content": "## Annex A (informative) Clause identifiers stated in other editions\n\nA tool message, or an earlier edition, may cite a clause identifier of this document's series whose rule a 0.2.0 edition states elsewhere. Each such identifier is listed here with the edition and section that state it, or, where no 0.2.0 edition states its rule, with the section that describes the topic.\n\n| Identifier | Stated in |\n|---|---|\n| <a id=\"K-1\"></a>K-1 | [SPEC-04P.2 6.13.2](SPEC-04P.2-LANGUAGE.md#K-1) |\n| <a id=\"K-2\"></a>K-2 | [SPEC-04P.2 6.13.2](SPEC-04P.2-LANGUAGE.md#K-2) |\n| <a id=\"K-3\"></a>K-3 | [SPEC-04P.2 6.13.1](SPEC-04P.2-LANGUAGE.md#K-3) |\n| <a id=\"K-4\"></a>K-4 | [SPEC-04P.2 6.13.2](SPEC-04P.2-LANGUAGE.md#K-4) |\n| <a id=\"K-5\"></a>K-5 | [SPEC-04P.2 6.13.1](SPEC-04P.2-LANGUAGE.md#K-5) |\n| <a id=\"K-6\"></a>K-6 | [SPEC-04P.2 6.13.2](SPEC-04P.2-LANGUAGE.md#K-6) |\n| <a id=\"K-8\"></a>K-8 | [SPEC-04P.2 6.13.1](SPEC-04P.2-LANGUAGE.md#K-8) |\n| <a id=\"K-10\"></a>K-10 | [SPEC-04P.2 6.13.3](SPEC-04P.2-LANGUAGE.md#K-10) |\n| <a id=\"K-10a\"></a>K-10a | [SPEC-04P.2 6.13.3](SPEC-04P.2-LANGUAGE.md#K-10a) |\n| <a id=\"K-11\"></a>K-11 | [SPEC-04P.2 6.13.3](SPEC-04P.2-LANGUAGE.md#K-11) |\n| <a id=\"K-12\"></a>K-12 | [SPEC-04P.2 6.13.3](SPEC-04P.2-LANGUAGE.md#K-12) |\n| <a id=\"R-1\"></a>R-1 | [SPEC-04P.2 6.13.5](SPEC-04P.2-LANGUAGE.md#R-1) |\n| <a id=\"R-4\"></a>R-4 | [SPEC-04P.2 7.3](SPEC-04P.2-LANGUAGE.md#R-4) |\n| <a id=\"V-2\"></a>V-2 | [SPEC-04P.2 6.12.1](SPEC-04P.2-LANGUAGE.md#V-2) |\n| <a id=\"V-4\"></a>V-4 | [SPEC-04P.2 6.12.4](SPEC-04P.2-LANGUAGE.md#V-4) |\n| <a id=\"V-5\"></a>V-5 | [SPEC-04P.2 6.12.4](SPEC-04P.2-LANGUAGE.md#V-5) |\n| <a id=\"V-11\"></a>V-11 | [SPEC-04P.2 6.12.4](SPEC-04P.2-LANGUAGE.md#V-11) |\n| <a id=\"X-8\"></a>X-8 | [SPEC-04P.2 6.13.6](SPEC-04P.2-LANGUAGE.md#X-8) |\n| <a id=\"P-6\"></a>P-6 | [Not a rule of this edition; SPEC-02P.1 12, paragraph 1](SPEC-02P.1-KERNELS.md#future-directions) |"
  },
  {
   "id": "spec-03p:spec-03p-1",
   "edition": "SPEC-03P.1",
   "title": "SPEC-03P.1",
   "clauses": "",
   "url": "/specifications/spec-03p/1/",
   "internal": 0,
   "content": "# SPEC-03P.1: The host interface: C and Python\n\nSPEC-03P.1, edition 1 of the cint host interface specification, cint v0.2.0, 2026-10-11."
  },
  {
   "id": "spec-03p:foreword",
   "edition": "SPEC-03P.1",
   "title": "Foreword",
   "clauses": "A-12",
   "url": "/specifications/spec-03p/1/#foreword",
   "internal": 0,
   "content": "## Foreword\n\nThis document specifies how a program written in C or Python calls cint code, as cint 0.2.0 implements it: the libraries that `cint build --lib` writes, the C interface of those libraries, and the Python package `cint` that is built on them.\n\nEach rule ends with one or more clause identifiers in brackets. An identifier, such as A-12 or P-20a, names one rule across editions and documents, and it is never reused. The letter says where the rule belongs: `M` memory, `H` the boundary between a host and its contexts, `A` the C interface, `P` the Python package, `X` the conversion of floating-point values and `RT` the runtime contract. In SPEC-02P.1 and SPEC-04P.2, identifiers that begin with `A`, `P` or `X` name rules of kernels, which are not the rules of this document that have the same identifiers. A rule that another edition states is cited in brackets with that edition's name, such as [SPEC-09P.1 RT-10]. Section numbers belong to this edition only."
  },
  {
   "id": "spec-03p:introduction",
   "edition": "SPEC-03P.1",
   "title": "Introduction",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#introduction",
   "internal": 0,
   "content": "## Introduction\n\nA cint program can be a library as well as a script. A module that declares `export` functions and kernels, and has no `main` and no top-level statements, is built by `cint build --lib` into one shared library. A host program loads that library, creates a *context* for it and calls its exports. The exports run exactly as they would if cint code called them: every plain operator is checked, a fault stops the call with a fault record, and fuel is counted.\n\nThe running example of this document is a kernel that advances positions by velocities, and a function that totals an array:\n\n```cint\n// advance.ci: one kernel and one function, built as a library.\nexport kernel advance[n](in I64[n] pos, in I64[n] vel, in I64 dt, out I64[n] next) over [i: n] {\n    next[i] = pos[i] + vel[i] * dt;\n}\n\nexport I64 total[n](in I64[n] x) {\n    return sum(x);\n}\n```\n\nFrom Python, the exchange reads as follows (8.6 runs it in full):\n\n```python\nmod = cint.load(\"advance.ci\")\nctx = mod.context()\nctx.advance(pos, vel, 16, next=nxt)\n```\n\nThree things cross the boundary, and this document is about each of them. Memory crosses as *buffers* that the host registers with the context and *views* of them; cint code never sees an address. Control crosses as calls through typed C functions, one for each export, which check every argument before any cint code runs. Outcomes cross as a status, a result, and, when the call faults, the same fault record that a cint caller would get."
  },
  {
   "id": "spec-03p:how-this-document-is-organized",
   "edition": "SPEC-03P.1",
   "title": "How this document is organized",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#how-this-document-is-organized",
   "internal": 0,
   "content": "### How this document is organized\n\nClauses 1 to 4 state what the document covers, the documents it relies on, its terms and what conformance means. Clause 5 describes how the state of a context is represented, and what a native pointer may be. Clause 6 describes buffers: the registry, ownership, leases, how outputs are published and views. Clause 7 is the C interface: statuses, the runtime header, the calling sequence with a complete C program, the reflection table and type signatures. Clause 8 is the Python package: loading and calling, borrowing arrays without a copy, DLPack, outputs and the hazards around them, the values that cross and a complete NumPy program. Clause 9 covers output effects, checkpoints, recordings and replay as a host sees them. Clause 10 works through further cases that run. Clause 11 lists future directions.\n\nSubclauses of clauses 5 to 9 open with a short summary and then have some of these parts:\n\n- **Synopsis**: the C declarations or Python signatures of the subclause.\n- **Constraints**: rules a host program shall follow.\n- **Semantics**: what the interface does.\n- **Faults**: the faults the interface itself can raise, and what each record holds.\n- **Examples** and **Notes**: informative.\n\nEvery example is a complete file. A C or Python file is shown once, with its name in its first line, and the commands that build and run it are shown in a `console` block with their output exactly as the cint 0.2.0 tools and Python 3.13 with NumPy 2.5.3 printed it on Linux x86-64 with gcc 13.3.0. A library file is named `libNAME.so` on Linux; other systems use their own suffix. A line `...` in shown output stands for lines left out."
  },
  {
   "id": "spec-03p:scope",
   "edition": "SPEC-03P.1",
   "title": "1 Scope",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#scope",
   "internal": 0,
   "content": "## 1 Scope\n\n1. This document specifies, for profile `cint-core-1` as cint 0.2.0 implements it:\n   - the canonical and the runtime representation of a context's state, and what a native pointer may be;\n   - the buffer registry, the ownership of memory, leases and the publication of outputs;\n   - the C interface of a library that `cint build --lib` writes: the status results, the context, the registry functions, the calling sequence, the reflection table and the canonical type signature;\n   - the Python package `cint`: loading, contexts, calls, borrowing through the buffer protocol and DLPack, outputs, the values that cross, the conversion of floating-point values and the exceptions;\n   - output effects, checkpoints, recordings and replay, as a host program uses them.\n2. This document does not specify:\n   - the language, including what a view, a kernel, a dispatch, a fault and fuel mean, which SPEC-04P.2 specifies;\n   - the byte encodings of fault records, states, checkpoints and recordings and the revision identity, which SPEC-01P.2 specifies;\n   - how an executor carries out a dispatch, which SPEC-02P.1 specifies;\n   - the `cint build` command and its options, which SPEC-06P.1 specifies;\n   - the encoding of generated symbol names, which SPEC-09P.1 specifies;\n   - what a host program does with memory it shares, and the behavior of host code."
  },
  {
   "id": "spec-03p:normative-references",
   "edition": "SPEC-03P.1",
   "title": "2 Normative references",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#normative-references",
   "internal": 0,
   "content": "## 2 Normative references\n\nThe following documents are referred to in the text in such a way that some or all of their content constitutes requirements of this document. For dated references, only the edition cited applies.\n\n- ISO/IEC 9899:2018, *Information technology: Programming languages: C* (C17). Used for the C interface: `<stdint.h>`, `static_assert`, and `atomic_exchange`.\n- Travis Oliphant and Carl Banks. *PEP 3118: Revising the buffer protocol*. Python Enhancement Proposal, created 2006-08-28. Used for the buffer protocol: `Py_buffer`, its request flags and its format strings.\n- Python Software Foundation. \"Buffer Protocol.\" *Python/C API Reference Manual*, Python 3.14. Used for the buffer protocol as Python 3.14 defines it.\n- Python Software Foundation. \"struct: Interpret bytes as packed binary data,\" section \"Format Characters.\" *The Python standard library*, Python 3.14. Used for the format characters that a buffer's format string takes from the `struct` module.\n- DLPack contributors. *DLPack: Open In Memory Tensor Structure*, release v1.3, 2026-01-26: `dlpack.h` version 1.3 and the DLPack Python specification. Used for `DLManagedTensorVersioned`, its flags and the capsule protocol.\n- Consortium for Python Data API Standards. *Python array API standard*, version 2023.12, `array.__dlpack__`. Used for the arguments of a DLPack exchange.\n- National Institute of Standards and Technology. *Secure Hash Standard (SHS)*. FIPS PUB 180-4, August 2015. Used for SHA-256.\n- IEEE. *IEEE Std 754-2019, IEEE Standard for Floating-Point Arithmetic*, 2019. Used for binary32 and binary64 and for roundTiesToEven."
  },
  {
   "id": "spec-03p:terms-definitions-and-symbols",
   "edition": "SPEC-03P.1",
   "title": "3 Terms, definitions and symbols",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "## 3 Terms, definitions and symbols\n\nThe terms of SPEC-04P.2 clause 3 apply, in particular value, type, fault, fault record, operation identifier, error, refusal, executor, entry, fuel, call depth, frame arena, semantic input, module, array, view, kernel, dispatch, arena, pool, handle and revision. The following terms are added. Other terms are defined where they first appear, in italic type.\n\n<a id=\"term-host-program\"></a>**3.1 host program**: a program written in another language, here C or Python, that calls cint code through the interface of this document.\n\n<a id=\"term-library\"></a>**3.2 library**: the shared library that `cint build --lib` writes for a program whose root module has no `main` and no top-level statements. It holds the program's compiled code and a copy of the runtime.\n\n<a id=\"term-runtime\"></a>**3.3 runtime**: the C code, declared in `rt/cint_rt.h` and `rt/cint_rt_host.h` and built as the library `cint_rt`, that holds contexts, buffers and fault records for compiled cint code, and that emitted C and the executor `cpu-sir-interp` call for checked arithmetic, fuel and call depth. Its interface is the runtime contract `cint-rt-3`.\n\n<a id=\"term-context\"></a>**3.4 context**: one instance of a program's state, held by a host program, in which entries run one at a time: its module variables, arenas and pools, its buffer registry, its counters and its fault record. A context persists across entries until the host destroys it.\n\n<a id=\"term-export\"></a>**3.5 export**: an exported function or kernel of the root module, which a host program calls through its wrapper.\n\n<a id=\"term-wrapper\"></a>**3.6 wrapper**: the C function of a library that checks a host's arguments, runs one export as one entry, and returns a status.\n\n<a id=\"term-status\"></a>**3.7 status**: the `int32_t` value a function of the C interface returns to say how a call ended."
  },
  {
   "id": "spec-03p:terms-definitions-and-symbols-p1",
   "edition": "SPEC-03P.1",
   "title": "3 Terms, definitions and symbols (part 2)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "<a id=\"term-refused-call\"></a>**3.8 refused call**: a call whose arguments cannot be formed into cint values. Nothing runs, no fuel is charged, and the context is unchanged. A refused call is not a refusal in the sense of SPEC-04P.2 3.16, which concerns programs that an implementation cannot execute.\n\n<a id=\"term-entry-fault\"></a>**3.9 entry fault**: a fault raised by the checks an entry makes on its arguments after they were formed and before any of its code runs.\n\n<a id=\"term-buffer\"></a>**3.10 buffer**: a run of elements of one type in one placement, registered with a context. A *registration* records a buffer in the registry under a *buffer identifier*, and a *generation* that tells one lifetime of the registration from the next.\n\n<a id=\"term-ownership\"></a>**3.11 ownership**: which party frees a buffer's storage: the context, the runtime for a buffer it created, the Python package for a `Buffer`, or the host program for borrowed memory.\n\n<a id=\"term-borrow\"></a>**3.12 borrow**: the use of host memory by cint code without a copy. The host keeps the memory alive while it is registered.\n\n<a id=\"term-lease\"></a>**3.13 lease**: a period during which the runtime hands the host a read-only address of storage the runtime owns. In Python the same role is played by an *export* of a `Buffer` through the buffer protocol or DLPack.\n\n<a id=\"term-publication\"></a>**3.14 publication**: the moment at which the new contents of a dispatch's outputs become visible, which is when the dispatch completes without a fault.\n\n<a id=\"term-copy-report\"></a>**3.15 copy report**: the list of every copy an entry made: which argument, why, its element type and its element count."
  },
  {
   "id": "spec-03p:terms-definitions-and-symbols-p2",
   "edition": "SPEC-03P.1",
   "title": "3 Terms, definitions and symbols (part 3)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "<a id=\"term-canonical-representation\"></a>**3.16 canonical representation**: the machine-independent form of a context's state, built from identifiers, typed values and declared lengths. The *runtime representation* is the in-process form: addresses, allocations and synchronization objects.\n\n<a id=\"term-state-hash\"></a>**3.17 state hash**: the SHA-256 digest of the canonical representation of a context's state (5.1), as defined in SPEC-01P.2, 3.12.\n\n<a id=\"term-checkpoint\"></a>**3.18 checkpoint**: the canonical bytes of a context's state, in an envelope that names the runtime contract, from which a context can be restored (9.2), as defined in SPEC-01P.2, 3.11.\n\n<a id=\"term-recording\"></a>**3.19 recording**: a file that holds a program's identity and code, a checkpoint of a context when recording began and the events that followed, from which the run can be replayed (9.3), as defined in SPEC-01P.2, 3.14.\n\n<a id=\"term-reflection-table\"></a>**3.20 reflection table**: the table a library carries that describes each export: its name, kind, effect class, parameter names and type signature, and its wrapper.\n\n<a id=\"term-type-signature\"></a>**3.21 type signature**: the canonical bytes that describe the parameter modes, parameter types and result type of an export."
  },
  {
   "id": "spec-03p:conformance",
   "edition": "SPEC-03P.1",
   "title": "4 Conformance",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#conformance",
   "internal": 0,
   "content": "## 4 Conformance\n\n1. In this document, \"shall\" states a requirement on a host program or on an implementation, and \"shall not\" a prohibition. \"May\" states a permission.\n2. A conforming implementation of this interface shall give each entry that a host program makes the outcome that SPEC-04P.2 specifies for it: the same output bytes, the same fault record and the same fuel as every other conforming implementation. A dispatch issued by a host call has the same meaning, checks and fault records as the same dispatch issued from cint code (7.1 paragraph 3; 10.3 shows one).\n3. The interface is defined for little-endian hosts with 64-bit pointers: x86-64 and AArch64. A host program that breaks a constraint of this document, or that changes memory it has lent to a context while an entry runs, gets no outcome this document specifies.\n4. An implementation may refuse a construct that it does not implement, with a diagnostic whose code begins with `C9`. SPEC-09P.1 lists what the tools of each release refuse.\n5. No claim is made about host code itself: what it computes, whether it terminates, and what it does with memory it shares with a context."
  },
  {
   "id": "spec-03p:representations",
   "edition": "SPEC-03P.1",
   "title": "5 Representations",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#representations",
   "internal": 0,
   "content": "## 5 Representations"
  },
  {
   "id": "spec-03p:runtime-and-canonical-representation",
   "edition": "SPEC-03P.1",
   "title": "5.1 Runtime and canonical representation",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#runtime-and-canonical-representation",
   "internal": 0,
   "content": "### 5.1 Runtime and canonical representation\n\nA context's state has two forms. The runtime form is what a process holds: addresses, allocations, device handles. The canonical form is what a checkpoint, a recording and a state hash hold: identifiers, typed values and lengths, with no address in them. Two machines that run the same entries reach the same canonical state, whatever their addresses were.\n\n**Semantics**"
  },
  {
   "id": "spec-03p:runtime-and-canonical-representation-p1",
   "edition": "SPEC-03P.1",
   "title": "5.1 Runtime and canonical representation (part 2)",
   "clauses": "M-1 M-2 M-3 M-4 M-5",
   "url": "/specifications/spec-03p/1/#runtime-and-canonical-representation",
   "internal": 0,
   "content": "1. <a id=\"M-1\"></a>Every part of a context's state has a canonical representation. Two contexts are in the same state exactly when their canonical representations are the same bytes. The identifier counters (paragraph 3) are part of the state, so two contexts with the same values but different histories of registration are in different states [M-1].\n2. <a id=\"M-2\"></a>Nothing in the runtime representation enters the canonical representation, a state hash, the canonical fields of a fault record, or any value that cint code can read [M-2].\n3. <a id=\"M-3\"></a>The canonical representation of a context holds exactly these items, in the order and bytes that SPEC-01P.2 specifies [M-3]:\n   - the revision identity, the profile `cint-core-1` and the fuel model `fuel-v1`;\n   - the value of every module variable, by qualified name;\n   - each arena and each pool, with its identifier, capacity, generations and contents;\n   - each registration (6.1), with its identifier, generation, element type, extent, ownership, ceiling and publish mode, and none of the contents of its memory;\n   - the counters: the next buffer, arena and pool identifiers and the number of entries made;\n   - the fault record, or its absence;\n   - the number of effects completed.\n4. <a id=\"M-4\"></a>Every multi-byte integer of the canonical representation is little-endian. Hosts are little-endian too, so borrowed memory is used as it is and never byte-swapped [M-4].\n5. <a id=\"M-5\"></a>The state hash is SHA-256 over the canonical representation, framed with the domain string `cint-core-1/state/v1` [M-5].\n\n**Examples**\n\n6. The checkpoint that 9.2 takes holds the value of `counter.tally` by its qualified name, its type and its value and the registry entries of two borrowed arrays carry their identifier, generation, element type, extent and modes but none of their contents."
  },
  {
   "id": "spec-03p:what-a-native-pointer-may-be",
   "edition": "SPEC-03P.1",
   "title": "5.2 What a native pointer may be",
   "clauses": "M-6 M-7 M-8 M-9",
   "url": "/specifications/spec-03p/1/#what-a-native-pointer-may-be",
   "internal": 0,
   "content": "### 5.2 What a native pointer may be\n\nAn address is a fact about one process. It is used to reach memory and to decide whether two arrays overlap, and for nothing else.\n\n**Semantics**\n\n1. <a id=\"M-6\"></a>cint source has no pointer type, no address-of operator and no conversion between an integer and an address. A program cannot observe, compare or hash an address [M-6].\n2. <a id=\"M-7\"></a>A native pointer may be [M-7]:\n   - the base of a registered buffer, held by the runtime;\n   - a field of a buffer descriptor that the host passes when it registers memory (7.2);\n   - the read-only address of a lease of a buffer the runtime created, valid until the lease ends (6.3);\n   - compared by the runtime with another to decide whether two registrations overlap (6.5).\n3. <a id=\"M-8\"></a>A native pointer is never the identity of an allocation, which is its buffer identifier or its handle. It is never part of a canonical value, checkpoint, recording, fault record or state hash, never converted to or from a cint integer, and never used to order objects [M-8].\n4. <a id=\"M-9\"></a>The runtime may move storage it owns between entries. Buffer identifiers and handles are unaffected. A host program that keeps the address of such storage outside a lease has no assurance that it stays valid [M-9].\n\n**Examples**\n\n5. In 10.1, the host reads the output of `scale` through the address of a lease and ends the lease; it reads the next output with `cint_buffer_read`, into an array of its own, and keeps no address of the runtime's storage after `cint_lease_end`."
  },
  {
   "id": "spec-03p:buffers-and-ownership",
   "edition": "SPEC-03P.1",
   "title": "6 Buffers and ownership",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#buffers-and-ownership",
   "internal": 0,
   "content": "## 6 Buffers and ownership"
  },
  {
   "id": "spec-03p:the-buffer-registry",
   "edition": "SPEC-03P.1",
   "title": "6.1 The buffer registry",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-buffer-registry",
   "internal": 0,
   "content": "### 6.1 The buffer registry\n\nEach context keeps a table of the memory it may reach. A host program adds an entry, a registration and receives an identifier and a generation; views name the identifier and the generation, never an address.\n\n**Semantics**"
  },
  {
   "id": "spec-03p:the-buffer-registry-p1",
   "edition": "SPEC-03P.1",
   "title": "6.1 The buffer registry (part 2)",
   "clauses": "M-10 M-11 M-11a",
   "url": "/specifications/spec-03p/1/#the-buffer-registry",
   "internal": 0,
   "content": "1. <a id=\"M-10\"></a>Each context has one buffer registry. An entry of the registry holds [M-10]:\n   - `id`, a nonzero `U64` buffer identifier;\n   - `generation`, a `U64` that release advances and publication leaves unchanged;\n   - the element type and the extent, a count of elements of at least 0;\n   - the ownership: context, created by the runtime, or borrowed (3.11);\n   - the placement: host memory, or `device(1)` on a context with a device; placement is not canonical;\n   - the ceiling, `read` or `write`: the most any view of the buffer may do;\n   - the publish mode, `none` or `copy`, which says whether a borrowed buffer may receive a dispatch's output (6.4);\n   - the base address and the count of live leases, which are runtime representation only.\n2. <a id=\"M-11\"></a>Buffer identifiers count from 1 in the order of registration and are never reused while the context exists. Each registration starts at generation 1. An identifier depends only on the order of registrations, never on an address, a time or a thread. A restore (9.2) sets the next buffer, arena and pool identifiers each to the greater of the checkpoint's value and the context's own, so that no identifier is issued twice in the life of a context [M-11].\n3. <a id=\"M-11a\"></a>A restore (9.2) removes every registration of memory the context does not own, and its identifiers are not issued again. A C host registers such memory again; the Python package does it on the next use of the `View` or `Buffer` (8.2) [M-11a].\n4. A context holds at most `max_buffers` live registrations, a field of its configuration (7.2) whose default is 256. A registration beyond that returns `CINT_RESOURCE`.\n\n**Examples**"
  },
  {
   "id": "spec-03p:the-buffer-registry-p2",
   "edition": "SPEC-03P.1",
   "title": "6.1 The buffer registry (part 3)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-buffer-registry",
   "internal": 0,
   "content": "5. In 10.1, the text `\"123\"` is registered first and gets identifier 1; after it is released, the text `\"12x\"` gets identifier 2, not 1 again. A view that names identifier 99, which was never issued, is a refused call."
  },
  {
   "id": "spec-03p:ownership",
   "edition": "SPEC-03P.1",
   "title": "6.2 Ownership",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#ownership",
   "internal": 0,
   "content": "### 6.2 Ownership\n\nEvery piece of storage has one party that frees it, and that party never changes behind the host's back.\n\n**Semantics**\n\n1. Storage owned by the context, which is its module variables, arenas, pools and frame arena, lives and dies with the context. Its contents are part of the canonical state.\n2. Storage that the runtime creates for the host with `cint_buffer_create` is owned by the runtime. It is zero-filled when created, freed by `cint_buffer_release`, and freed with the context by `cint_ctx_destroy`.\n3. <a id=\"P-17\"></a>A `Buffer` of the Python package owns its storage. Each registration of it ends before the storage is freed, by `Buffer.release()` or by garbage collection. Destroying a context ends that context's registrations and leaves the storage with the `Buffer`, and storage never passes between the package and a context [P-17].\n4. Borrowed memory belongs to the host program. The runtime never frees it, and the host program shall keep it valid and in place until the registration ends.\n5. Ownership never moves implicitly. Only a copy that the host asks for, or one listed in the copy report (6.4), moves contents from the storage of one party to the storage of another.\n\n**Examples**\n\n6. In 10.1, the array `xs` is borrowed memory: the host program owns it, and releasing its registration leaves the memory with the host. The output `y` is created by `cint_buffer_create`, so the runtime owns it; it is zero-filled when created and freed by `cint_buffer_release` before the context is destroyed."
  },
  {
   "id": "spec-03p:leases-and-exports",
   "edition": "SPEC-03P.1",
   "title": "6.3 Leases and exports",
   "clauses": "A-9",
   "url": "/specifications/spec-03p/1/#leases-and-exports",
   "internal": 0,
   "content": "### 6.3 Leases and exports\n\nA lease gives a host program a read-only address for a bounded time, so that it can read an output that the runtime holds without copying it. In Python, an export through the buffer protocol or DLPack plays the same role.\n\n**Synopsis**\n\n```text\ncint_status cint_buffer_lease(cint_ctx *ctx, cint_buffer_id id, const void **out_ptr, uint64_t *out_lease);\ncint_status cint_lease_end(cint_ctx *ctx, uint64_t lease);\ncint_status cint_buffer_read(cint_ctx *ctx, cint_view view, void *dst, size_t dst_bytes);\n```\n\n**Constraints**\n\n1. A host program shall not write through a leased address, and shall not use it after `cint_lease_end`. Either is outside every assurance of this document.\n\n**Semantics**\n\n2. <a id=\"A-9\"></a>The C interface returns the address of storage the runtime owns only through a lease. `cint_buffer_lease` gives a read-only address of a created buffer's current storage and a lease number; lease numbers count from 1 and are never reused. The address stays valid until `cint_lease_end` of that number. Leasing borrowed memory, or ending an unknown lease, is refused with reason `CINT_REFUSAL_LEASE`. While a buffer has a live lease, an entry that binds it to an `out` or `inout` parameter returns `CINT_BUSY`, runs nothing and records nothing. A host that wants a copy instead calls `cint_buffer_read`, which copies a view's elements in row-major order of their indices into `dst`, which shall hold exactly their bytes [A-9].\n3. <a id=\"P-18\"></a>A `Buffer` of the Python package offers no writable export. Its buffer-protocol exports are read-only, its DLPack exports are versioned capsules marked `DLPACK_FLAG_BITMASK_READ_ONLY`, and the package counts them. Using a `Buffer` as an output while it has a live export raises `cint.Busy` with code `E_ALIAS` [P-18].\n\n**Examples**"
  },
  {
   "id": "spec-03p:leases-and-exports-p1",
   "edition": "SPEC-03P.1",
   "title": "6.3 Leases and exports (part 2)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#leases-and-exports",
   "internal": 0,
   "content": "4. In 10.1, a call that would write a leased buffer returns status 3, `CINT_BUSY`; after `cint_lease_end` the same call runs. In 8.4, a NumPy array made by `numpy.asarray(buf)` holds an export, and the next call that writes `buf` raises `Busy`.\n\n**Notes**\n\n5. The read-only mark is a request to the consumer, not a protection. A consumer that ignores it, through raw addresses, `__array_interface__`, or a DLPack consumer that has no read-only concept, can still write, and such a write is outside every assurance. NumPy 2.5.3 honors the mark: `numpy.from_dlpack` of a `Buffer` gives an array whose writes raise `ValueError` (8.3). CuPy 14.2.0 and PyTorch 2.14.1 accept a read-only DLPack capsule without honoring the mark, so a write through the array they return reaches the `Buffer`'s memory."
  },
  {
   "id": "spec-03p:outputs-and-publication",
   "edition": "SPEC-03P.1",
   "title": "6.4 Outputs and publication",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#outputs-and-publication",
   "internal": 0,
   "content": "### 6.4 Outputs and publication\n\nA kernel's outputs change all at once or not at all. A function's `inout` arrays change as its statements run. This subclause says how each reaches memory the host owns.\n\n**Semantics**"
  },
  {
   "id": "spec-03p:outputs-and-publication-p1",
   "edition": "SPEC-03P.1",
   "title": "6.4 Outputs and publication (part 2)",
   "clauses": "M-30 M-30a M-30b M-31",
   "url": "/specifications/spec-03p/1/#outputs-and-publication",
   "internal": 0,
   "content": "1. <a id=\"M-30\"></a>Publication is per dispatch. An array bound to an `out` or `inout` parameter of a dispatch is pending from the start of the dispatch until it ends. When the dispatch completes, its new contents are published and later dispatches of the same entry read them. When the dispatch faults, nothing is published: the array holds exactly what it held before the dispatch, whoever owns it. Arrays published by earlier dispatches of the same entry keep their published contents (SPEC-04P.2 6.13.6) [M-30].\n2. <a id=\"RT-19\"></a>The runtime computes every output of a dispatch into staging storage of its own, zero-filled, with an `inout` argument's elements copied in first, and copies the result into the argument's memory when the dispatch completes [RT-19].\n3. <a id=\"M-30a\"></a>A borrowed buffer may be bound to an `out` or `inout` parameter of a dispatch only when its registration declares the publish mode `copy`. A borrowed buffer registered with `none` faults at entry (Faults below). No executor writes a borrowed output directly during a dispatch [M-30a].\n4. <a id=\"M-30b\"></a>A function, which has no `out` parameter, writes an array bound to its `inout` parameter in place, as it writes its own memory, with no staging and no copy. After a fault the array holds the stores of the statements that completed, those of callees included; sequential stores are not rolled back. Such a binding needs a writable registration, and its publish mode is not consulted [M-30b].\n5. <a id=\"M-31\"></a>Every copy an entry makes is listed in its copy report, with the reason, the element type and the number of elements. The reasons are `staging` for the output of a dispatch, `publish-copy` for an output into borrowed memory, `snapshot` and `fault-readback`. An entry with no copies reports `no copies`. The report holds element counts, not bytes [M-31].\n6. <a id=\"P-15\"></a>In Python, a borro"
  },
  {
   "id": "spec-03p:outputs-and-publication-p2",
   "edition": "SPEC-03P.1",
   "title": "6.4 Outputs and publication (part 3)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#outputs-and-publication",
   "internal": 0,
   "content": "**Faults**\n\n7. `E_UNSUPPORTED`, operation `bind.limit`, is raised at entry when a borrowed buffer registered with publish mode `none` is bound to an `out` or `inout` parameter of a dispatch. The operand is the parameter's index as an `I64`, counted from 0 in declaration order. Nothing runs and the dispatch publishes nothing.\n\n**Examples**\n\n8. 8.4 shows each case from Python, and 10.2 shows an entry with two dispatches whose second faults: the first dispatch's output stays published, and the second's is not.\n\n**Notes**\n\n9. A caller that needs all or nothing from a function passes a copy and copies it back when the entry succeeds."
  },
  {
   "id": "spec-03p:views-and-scope",
   "edition": "SPEC-03P.1",
   "title": "6.5 Views and scope",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#views-and-scope",
   "internal": 0,
   "content": "### 6.5 Views and scope\n\nA view names a registered buffer and says which of its elements to use and how: its element type, rank, extents, strides and permission. What a view means inside cint code is SPEC-04P.2 6.12; this subclause covers what a host supplies.\n\n**Semantics**"
  },
  {
   "id": "spec-03p:views-and-scope-p1",
   "edition": "SPEC-03P.1",
   "title": "6.5 Views and scope (part 2)",
   "clauses": "A-8a H-13 M-28",
   "url": "/specifications/spec-03p/1/#views-and-scope",
   "internal": 0,
   "content": "1. A host passes each array argument as a view: a buffer identifier and generation, an element type, a rank from 1 to 4, an origin and for each dimension an extent, a stride in elements and a lower bound, with a permission, `read` or `write`. Its admission, indexing and lower bounds follow SPEC-04P.2 6.12.\n2. <a id=\"A-8a\"></a>Strided host memory whose first logical element is not its lowest address, as with negative strides, is registered from its lowest reachable byte, with an extent equal to the reachable span in elements, and the view's origin is the offset of the first logical element from that base. The Python package does this for every array it borrows, and a C host does the same [A-8a].\n3. <a id=\"H-13\"></a>Read-only views may overlap. A view bound to an `out` or `inout` parameter shall not overlap any other array argument of the entry. Overlap is decided by comparing the byte ranges of host memory across every registration, not only within one buffer identifier, so two registrations of the same memory, even with different element types, overlap. Memory that is mapped at two virtual addresses cannot be detected and is outside every assurance [H-13].\n4. A view of borrowed memory exists for one entry: cint code cannot keep it after the entry returns (SPEC-04P.2 6.12).\n5. <a id=\"M-28\"></a>Only device code indexes device memory. On a context with a device, an entry checks the placement of each view it is given (7.1): a kernel that the host calls takes views of device memory only, and a function takes views of host memory, except for a parameter that its body only passes, whole, to dispatches, which may be in either placement. A kernel that cint code dispatches on such a context also reaches host memory: for that dispatch the runtime maps into the device the host memory its views reach and the storage the context owns. A view in the wrong placement faults `E_UNSUPPO"
  },
  {
   "id": "spec-03p:views-and-scope-p2",
   "edition": "SPEC-03P.1",
   "title": "6.5 Views and scope (part 3)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#views-and-scope",
   "internal": 0,
   "content": "**Faults**\n\n6. `E_ALIAS`, operation `bind.alias`, is raised at entry when a written view overlaps another array argument. Its operands are the written parameter's index and the other parameter's index, as `I64`. 8.4 raises it by passing one NumPy array as both input and output.\n\n**Examples**\n\n7. In 8.2, example 14, a reversed array is registered from its lowest address with a negative stride in each dimension, and the copy report of that call lists no copies."
  },
  {
   "id": "spec-03p:the-c-interface",
   "edition": "SPEC-03P.1",
   "title": "7 The C interface",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-c-interface",
   "internal": 0,
   "content": "## 7 The C interface"
  },
  {
   "id": "spec-03p:status-results",
   "edition": "SPEC-03P.1",
   "title": "7.1 Status results",
   "clauses": "A-4 A-6",
   "url": "/specifications/spec-03p/1/#status-results",
   "internal": 0,
   "content": "### 7.1 Status results\n\nEvery function of the C interface that can fail returns a status. A status says whether the call ran, and when it ran, whether it completed; the fault record, the error result and the refusal reason give the detail.\n\n**Synopsis**\n\n```text\n#define CINT_OK        0   /* completed; an error result also completes */\n#define CINT_FAULT     1   /* faulted, at entry or while running */\n#define CINT_REFUSED   2   /* the arguments could not be formed; nothing ran */\n#define CINT_BUSY      3   /* another call is active, or an output is leased */\n#define CINT_FAULTED   4   /* the context holds a fault; nothing ran */\n#define CINT_RESOURCE  5   /* the allocator, the registry or a device had no room */\n#define CINT_DIVERGED       6   /* replay found a difference (9.3) */\n#define CINT_UNREPLAYABLE   7   /* replay cannot go on (9.3) */\n\ncint_status cint_ctx_fault(const cint_ctx *ctx, cint_fault_record *out);\ncint_status cint_fault_get(const cint_ctx *ctx, uint8_t *buf, size_t cap, size_t *len);\ncint_status cint_ctx_refusal(const cint_ctx *ctx, uint32_t *reason);\ncint_status cint_ctx_error(const cint_ctx *ctx, const cint_error_set **set, uint64_t *tag);\ncint_status cint_fuel_consumed(const cint_ctx *ctx, int64_t *out);\ncint_status cint_ctx_clear_fault(cint_ctx *ctx);\n```\n\n**Semantics**\n\n1. <a id=\"A-4\"></a>A function that can fail returns a `cint_status`, and writes its out parameters only when it returns `CINT_OK`. `cint_abi_version` and `cint_ctx_destroy` cannot fail and return no status. Reading the fault of a context that holds none returns `CINT_OK` with a record whose code is 0 [A-4].\n2. <a id=\"A-6\"></a>The statuses and the state of the context after each are [A-6]:"
  },
  {
   "id": "spec-03p:status-results-p1",
   "edition": "SPEC-03P.1",
   "title": "7.1 Status results (part 2)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#status-results",
   "internal": 0,
   "content": "| Status | Value | Meaning | Context afterwards |\n|---|---|---|---|\n| `CINT_OK` | 0 | The entry completed and every dispatch published. An entry that returns an error value completes too (7.3). | Ready |\n| `CINT_FAULT` | 1 | cint code faulted, at entry or while running. | Faulted |\n| `CINT_REFUSED` | 2 | The arguments could not be formed into cint values. | Unchanged |\n| `CINT_BUSY` | 3 | Another call is active on the context, or an output has a live lease. | Unchanged |\n| `CINT_FAULTED` | 4 | The context holds a fault and runs no entry until it is cleared or restored. | Unchanged |\n| `CINT_RESOURCE` | 5 | The allocator, the registry or a device had no room. It is not a cint fault. | Unchanged before an entry |\n| `CINT_DIVERGED` | 6 | Replay found a difference from the recording. | Replay stopped |\n| `CINT_UNREPLAYABLE` | 7 | Replay reached an event it cannot reproduce. | Replay stopped |"
  },
  {
   "id": "spec-03p:status-results-p2",
   "edition": "SPEC-03P.1",
   "title": "7.1 Status results (part 3)",
   "clauses": "A-17 A-7 A-7a A-7b H-11 H-12",
   "url": "/specifications/spec-03p/1/#status-results",
   "internal": 0,
   "content": "3. <a id=\"H-12\"></a>A refused call and an entry fault are told apart by when the check fails. A refused call is one whose arguments cannot be formed: an unknown or released buffer identifier, a descriptor or view with an invalid field, a view that reaches outside its registration, a `Bool` byte other than 0 or 1, a fuel budget below -1 (paragraph 9), or, in Python, an argument of a refused kind. It charges no fuel, consumes no dispatch number, makes no registration and leaves the context unchanged. An entry fault is one whose arguments were formed and then failed a check of the entry (Faults below). It charges no fuel, leaves the context Faulted and for a kernel consumes the dispatch number. A host-issued dispatch therefore has the same outcome as the same dispatch issued from cint code [H-12].\n4. <a id=\"A-7\"></a>After `CINT_FAULT`, the context holds the state that SPEC-04P.2 5.2.3 describes: stores of completed statements remain, the outputs of the faulting dispatch are not published, and outputs published by earlier dispatches remain. The context then answers every entry with `CINT_FAULTED` until the host calls `cint_ctx_clear_fault` or restores a checkpoint [A-7].\n5. The first fault of an entry writes the record once, and nothing after it in that entry changes it. Only the host clears it, as SPEC-09P.1 7.10 states [SPEC-09P.1 RT-10].\n6. <a id=\"A-7a\"></a>`cint_ctx_clear_fault` clears the fault record and changes nothing else: no registration, buffer, view, lease or counter. The fault record is part of the canonical state, so clearing it changes the state hash [A-7a].\n7. <a id=\"A-7b\"></a>A fault ends the entry without running its deferred statements, so state that a `defer` would have restored stays as the fault left it. The host releases what it acquired around an entry, such as registrations, borrowed memory and leases, in code that runs for every status. To bring "
  },
  {
   "id": "spec-03p:status-results-p3",
   "edition": "SPEC-03P.1",
   "title": "7.1 Status results (part 4)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#status-results",
   "internal": 0,
   "content": "| Reason | Value | The argument |\n|---|---|---|\n| `CINT_REFUSAL_BUFFER` | 1 | names no registration |\n| `CINT_REFUSAL_GENERATION` | 2 | names a released registration |\n| `CINT_REFUSAL_TYPE` | 3 | has an unknown type, nonzero reserved bytes or a type other than its registration's |\n| `CINT_REFUSAL_RANK` | 4 | has a rank outside 1 to 4 |\n| `CINT_REFUSAL_SIZE` | 6 | has an element offset beyond the `I64` range |\n| `CINT_REFUSAL_EXTENT` | 7 | has a negative origin or extent, or reaches outside its registration |\n| `CINT_REFUSAL_ALIGN` | 8 | starts at an address not aligned for its type |\n| `CINT_REFUSAL_PERMISSION` | 9 | is a write view of a read-only registration |\n| `CINT_REFUSAL_CALL` | 10 | is otherwise invalid, such as a descriptor of the wrong size |\n| `CINT_REFUSAL_BOOL` | 11 | holds a `Bool` byte other than 0 or 1 |\n| `CINT_REFUSAL_RESULT` | 12 | is a NULL result pointer |\n| `CINT_REFUSAL_LEASED` | 13 | is a leased output; the call returns `CINT_BUSY` |\n| `CINT_REFUSAL_UNSUPPORTED` | 14 | is device memory, or a synchronization object, the context cannot take |\n| `CINT_REFUSAL_LEASE` | 15 | asks for a lease of memory the runtime does not own, or ends an unknown lease |\n\n**Faults**"
  },
  {
   "id": "spec-03p:status-results-p4",
   "edition": "SPEC-03P.1",
   "title": "7.1 Status results (part 5)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#status-results",
   "internal": 0,
   "content": "11. Once its arguments are formed, a wrapper makes the entry checks over every array parameter in turn, in this order, and faults at the first that fails, with the parameter indices counted from 0 in declaration order and no fuel charged:\n    1. `E_STALE_HANDLE`, `bind.stale`: the view's generation is not the registration's. Operands: the parameter index (`I64`) and the view's generation (`U64`); limit: the registration's generation.\n    2. `E_ALIAS`, `bind.permission`: a `read` view for an `out` or `inout` parameter. Operand: the parameter index.\n    3. `E_UNSUPPORTED`, `bind.type`: an element type other than the parameter's; or `E_SHAPE`, `bind.type`: a rank other than the parameter's, with the view's rank as a second operand and the declared rank as the limit.\n    4. `E_SHAPE`, `bind.shape`: an extent that disagrees with the extent its shape variable already took. Operands: the parameter index, the dimension and the extent given; limit: the extent expected.\n    5. `E_UNSUPPORTED`, `bind.placement`: a view in the wrong placement for its parameter, on a context with a device.\n    6. `E_ALIAS`, `bind.injective`: a written view whose elements are not distinct.\n    7. `E_ALIAS`, `bind.alias`: a written view that overlaps another array argument (6.5).\n    8. `E_UNSUPPORTED`, `bind.limit`: a borrowed output registered with publish mode `none` (6.4).\n\n    Each such fault is positioned at the export's name, and a kernel's record carries the kernel address with phase `entry`. The checks are those of SPEC-04P.2 6.13 for a dispatch issued from cint code.\n\n**Examples**\n\n12. 10.1 runs one call of each kind: refused calls with reasons 1, 2, 7 and 9, a fuel budget of -2 and entry faults `bind.stale`, `bind.permission`, `bind.shape` and `bind.limit`."
  },
  {
   "id": "spec-03p:the-runtime-header",
   "edition": "SPEC-03P.1",
   "title": "7.2 The runtime header",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-runtime-header",
   "internal": 0,
   "content": "### 7.2 The runtime header\n\nA host program includes `cint_rt.h`, which includes `cint_rt_host.h`, and links the library. Everything it calls is a function of the runtime or a wrapper, and everything it passes is a fixed-layout C structure.\n\n**Synopsis**\n\n```text\nuint32_t    cint_abi_version(void);\ncint_status cint_ctx_create(const cint_ctx_config *config, cint_ctx **out);\nvoid        cint_ctx_destroy(cint_ctx *ctx);\ncint_status cint_buffer_register(cint_ctx *ctx, const cint_buffer_desc *desc,\n                                 cint_buffer_id *out_id, uint64_t *out_generation);\ncint_status cint_buffer_create(cint_ctx *ctx, cint_type type, int64_t extent, uint32_t device,\n                               cint_buffer_id *out_id, uint64_t *out_generation);\ncint_status cint_buffer_release(cint_ctx *ctx, cint_buffer_id id);\n\ntypedef struct cint_ctx_config {        /* 96 bytes */\n    uint32_t size;                      /* sizeof(cint_ctx_config) */\n    uint32_t max_buffers;               /* live registrations; 0 selects 256 */\n    const cint_program *program;        /* required */\n    cint_allocator allocator;           /* alloc NULL selects malloc and free */\n    int64_t depth_limit;                /* call depth of every entry; 0 selects 256 */\n    int64_t frame_arena_bytes;          /* frame arena; 0 selects 16777216 */\n    cint_output_fn output;              /* receives each print statement; NULL discards */\n    void *output_user;\n    const cint_module_info *module;     /* the root module's descriptor */\n    uint32_t device_count, reserved;    /* 0, or 1 for a gpu-cuda library */\n    const void *const *devices;\n} cint_ctx_config;"
  },
  {
   "id": "spec-03p:the-runtime-header-p1",
   "edition": "SPEC-03P.1",
   "title": "7.2 The runtime header (part 2)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-runtime-header",
   "internal": 0,
   "content": "typedef struct cint_buffer_desc {       /* 112 bytes */\n    uint32_t size;                      /* sizeof(cint_buffer_desc) */\n    uint32_t writable;                  /* the ceiling: 0 read, 1 write */\n    cint_type type;                     /* element type */\n    cint_mem mem;                       /* kind CINT_MEM_HOST and the lowest reachable byte */\n    int64_t extent;                     /* elements */\n    uint32_t device;                    /* 0 for host memory */\n    uint32_t publish;                   /* CINT_PUBLISH_NONE, or CINT_PUBLISH_COPY if writable */\n    cint_sync sync;                     /* kind 0 for host memory */\n} cint_buffer_desc;\n\ntypedef struct cint_view {              /* 144 bytes */\n    cint_buffer_id buffer;              /* uint64_t, never 0 */\n    uint64_t generation;\n    cint_type type;                     /* code: the element's type tag (7.5) */\n    uint8_t rank;                       /* 1 to 4 */\n    uint8_t perm;                       /* CINT_VIEW_READ 0, CINT_VIEW_WRITE 1 */\n    uint8_t reserved[6];\n    int64_t origin;                     /* elements from the buffer's base */\n    int64_t shape[4], stride[4], lower[4];\n} cint_view;\n```\n\n**Constraints**\n\n1. A host program shall zero every reserved field and every unused field, and shall set each `size` field to the size of its structure.\n2. A host program shall make at most one call on a context at a time, and shall not call into a context from the output callback of an entry of that context. A call that breaks this returns `CINT_BUSY` (paragraph 9).\n\n**Semantics**"
  },
  {
   "id": "spec-03p:the-runtime-header-p2",
   "edition": "SPEC-03P.1",
   "title": "7.2 The runtime header (part 3)",
   "clauses": "A-1 A-10 A-11 A-13a A-16 A-16a A-2 A-3 A-5 A-8 H-10",
   "url": "/specifications/spec-03p/1/#the-runtime-header",
   "internal": 0,
   "content": "3. <a id=\"A-1\"></a>The interface is C17 with the fixed-width integer types of `<stdint.h>`. Its structures hold no field of an `enum` type and no compiler-specific wide integer type; every field is a fixed-width integer, a data pointer, a function pointer or a `size_t` and `static_assert` checks every structure's size and the offsets of its fields. Wide integers cross as structures of `uint64_t` limbs, least significant first. The header refuses to compile for a big-endian target or for pointers other than 64 bits [A-1].\n4. <a id=\"A-2\"></a>All state is reached through the opaque context `cint_ctx`. A library holds no mutable static data, so one library serves any number of contexts in one process [A-2].\n5. A context is the scope of state, isolation, checkpointing and replay, and SPEC-09P.1 7.10 states what it holds. `cint_ctx_create` checks the configuration, allocates the context and creates its module variables, arenas and pools with their declared capacities; `cint_ctx_destroy` frees everything the context and the runtime own [SPEC-09P.1 RT-4].\n6. <a id=\"A-5\"></a>`cint_abi_version` returns the interface version as `(major << 16) | minor`, which is 3.2 in cint 0.2.0. Each module descriptor records the version it was built for, and `cint_ctx_create` refuses a module of another major version [A-5].\n7. <a id=\"A-10\"></a>`cint_ctx_create` returns `CINT_REFUSED` for an invalid configuration: a NULL argument, a wrong `size`, no program or an invalid one, an allocator with `alloc` but no `release`, a negative depth limit or frame-arena size, or a module of another interface version or of another program. It returns `CINT_RESOURCE` when the allocator cannot supply the context or the storage of the program's arenas and pools, whose declared capacities and element types fix their size; the host chooses no arena capacity [A-10].\n8. <a id=\"A-8\"></a>`cint_buffer_register` checks "
  },
  {
   "id": "spec-03p:the-runtime-header-p3",
   "edition": "SPEC-03P.1",
   "title": "7.2 The runtime header (part 4)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-runtime-header",
   "internal": 0,
   "content": "**Notes**\n\n15. `cint_library_desc` is defined by every library but not declared by the header, since its type is the same for every program; a host program declares it as `extern const cint_library cint_library_desc;`."
  },
  {
   "id": "spec-03p:the-calling-sequence",
   "edition": "SPEC-03P.1",
   "title": "7.3 The calling sequence",
   "clauses": "A-12 A-13",
   "url": "/specifications/spec-03p/1/#the-calling-sequence",
   "internal": 0,
   "content": "### 7.3 The calling sequence\n\nA host program creates a context, registers the memory it lends, calls wrappers, reads results and faults, and releases what it registered. This subclause gives the shape of a wrapper, the C form of each type and a complete program.\n\n**Synopsis**\n\n```text\ncint_status cx_<module>_<name>(cint_ctx *ctx, int64_t fuel, <parameters in declaration order>, <result pointer>);\n\ncint_status cx_7_advance_7_advance(cint_ctx *ctx, int64_t fuel, cint_view pos, cint_view vel,\n                                   int64_t dt, cint_view next);\ncint_status cx_7_advance_5_total(cint_ctx *ctx, int64_t fuel, cint_view x, int64_t *result);\n```\n\n**Semantics**\n\n1. <a id=\"A-12\"></a>Each export of the root module has one wrapper. Its name is `cx` followed by the encoded path of the module and the encoded name of the export, each a length and the text with some characters escaped, as SPEC-09P.1 specifies: `advance` in `advance.ci` is `cx_7_advance_7_advance`, and `parse_u` in `tour.ci` is `cx_4_tour_10_parse_x5Fu`. It takes the context, the fuel budget (7.1), the parameters in declaration order and last a pointer to the result when the export returns a value. Size parameters are not arguments: their values are taken from the views and checked for agreement (7.1, check 4). The depth limit and the frame-arena size come from the configuration [A-12].\n2. <a id=\"A-13\"></a>Each type crosses in one C form, and a result is written through the result pointer only when the status is `CINT_OK` [A-13]:"
  },
  {
   "id": "spec-03p:the-calling-sequence-p1",
   "edition": "SPEC-03P.1",
   "title": "7.3 The calling sequence (part 2)",
   "clauses": "A-18",
   "url": "/specifications/spec-03p/1/#the-calling-sequence",
   "internal": 0,
   "content": "| cint type | C parameter | C result |\n|---|---|---|\n| `I8`, `I16`, `I32`, `I64` | `int8_t` to `int64_t` | a pointer to the same type |\n| `U8`, `U16`, `U32`, `U64` | `uint8_t` to `uint64_t` | a pointer to the same type |\n| `I128` to `I1024` | a pointer to a structure of `uint64_t` limbs | a pointer to the same structure |\n| `Q<i>.<f>` | the storage integer, raw: 1.0 in `Q32.32` is 4294967296 | a pointer to the storage integer |\n| `Bool` | `uint8_t`, 0 or 1; any other byte is refused (`CINT_REFUSAL_BOOL`) | a pointer to `uint8_t` |\n| array, any mode | `cint_view` | none |\n| struct, `in` or `inout` | `cint_view` of rank 1 and extent 1 whose type code is `0x71` and whose `record_id` names the struct | a pointer to the C struct |\n| error union `E!T` | none | a pointer to a struct of the tag, in the set's underlying type and 0 for success, then the value of `T` |\n\n   A `Bool` element of an array, or a `Bool` field of a struct element, is checked as a byte before the body reads it, and any byte other than 0 or 1 is a refused call.\n3. <a id=\"A-18\"></a>An export whose function returns an error value completes. Its status is `CINT_OK`, the tag in its result is the error's tag in its set, counted from 1, and the value field is 0. The context is not faulted, and the outputs of its dispatches are published as for any completed entry. `cint_ctx_error` gives the error set, as a `cint_error_set` with its qualified name and value names, and the tag, or NULL and 0 when the last entry returned no error. The error is part of the result, never of the fault record [A-18].\n4. A print statement in an export reaches the configuration's `output` callback once per statement, with the statement's bytes whole. A callback that returns a status other than `CINT_OK` faults the entry. With `output` NULL, print statements are formed and their bytes discarded.\n\n**Examples**"
  },
  {
   "id": "spec-03p:the-calling-sequence-p2",
   "edition": "SPEC-03P.1",
   "title": "7.3 The calling sequence (part 3)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-calling-sequence",
   "internal": 0,
   "content": "5. This is a complete host program for `advance.ci` (Introduction). It registers three arrays of host memory, runs `advance`, totals the output, makes `advance` fault and recovers.\n\n```c\n/* host.c: calls advance.ci through the library that `cint build --lib` wrote. */\n#include <inttypes.h>\n#include <stdio.h>\n#include <string.h>\n#include \"cint_rt.h\"\n\n/* What the library exports for advance.ci. */\nextern const cint_module_info cm_7_advance;\ncint_status cx_7_advance_7_advance(cint_ctx *ctx, int64_t fuel, cint_view pos, cint_view vel,\n                                   int64_t dt, cint_view next);\ncint_status cx_7_advance_5_total(cint_ctx *ctx, int64_t fuel, cint_view x, int64_t *result);\n\nstatic const char *const fault_names[] = {\"\", \"E_OVERFLOW\", \"E_DIV_ZERO\", \"E_BOUNDS\", \"E_SHAPE\",\n    \"E_SHIFT\", \"E_NARROW\", \"E_ALIAS\", \"E_STALE_HANDLE\", \"E_FUEL\", \"E_UNSUPPORTED\", \"E_DOMAIN\",\n    \"E_DEPTH\", \"E_ASSERT\"};\n\n/* Registers n I64 elements of host memory and writes a view of all of them. */\nstatic cint_status share(cint_ctx *ctx, int64_t *p, int64_t n, int writable, cint_view *v)\n{\n    cint_buffer_desc d;\n    cint_status s;\n    memset(&d, 0, sizeof d);\n    d.size = sizeof d;\n    d.writable = writable ? 1u : 0u;\n    d.type.code = CINT_TAG_I64;\n    d.mem.kind = CINT_MEM_HOST;\n    d.mem.u.host.ptr = p;\n    d.extent = n;\n    d.publish = writable ? CINT_PUBLISH_COPY : CINT_PUBLISH_NONE;\n    memset(v, 0, sizeof *v);\n    s = cint_buffer_register(ctx, &d, &v->buffer, &v->generation);\n    v->type.code = CINT_TAG_I64;\n    v->rank = 1;\n    v->perm = writable ? CINT_VIEW_WRITE : CINT_VIEW_READ;\n    v->shape[0] = n;\n    v->stride[0] = 1;\n    return s;\n}\n\n/* An I64 operand of a fault record: its tag byte, then 8 bytes, little-endian. */\nstatic int64_t operand_i64(const cint_tvalue *t)\n{\n    uint64_t u = 0;\n    for (int k = 8; k >= 1; k--) u = (u << 8) | t->bytes[k];\n    return (int64_t)u;\n}"
  },
  {
   "id": "spec-03p:the-calling-sequence-p3",
   "edition": "SPEC-03P.1",
   "title": "7.3 The calling sequence (part 4)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-calling-sequence",
   "internal": 0,
   "content": "static void report(cint_ctx *ctx)\n{\n    static cint_fault_record r;\n    const cint_module *m;\n    const cint_site_info *at;\n    if (cint_ctx_fault(ctx, &r) != CINT_OK || r.code == 0) return;\n    m = r.program->modules[r.position.module];\n    at = &m->sites[r.position.index];\n    printf(\"fault %s %.*s at %.*s:%\" PRIu32 \":%\" PRIu32 \"\\n\", fault_names[r.code],\n           (int)r.operation_len, r.operation, (int)m->path_len, m->path, at->line, at->column);\n    printf(\"  operands:\");\n    for (unsigned k = 0; k < r.operand_count; k++) printf(\" %\" PRId64, operand_i64(&r.operands[k]));\n    printf(\"\\n\");\n    if (r.has_address)\n        printf(\"  kernel %.*s, dispatch %\" PRId64 \", work item %\" PRId64 \"\\n\",\n               (int)r.address.name_len, r.address.name, r.address.dispatch, r.address.work_item);\n}\n\nstatic void show(const char *name, const int64_t *a, int n)\n{\n    printf(\"%s =\", name);\n    for (int k = 0; k < n; k++) printf(\" %\" PRId64, a[k]);\n    printf(\"\\n\");\n}\n\nint main(void)\n{\n    int64_t pos[4] = {0, 1, 2, 3}, vel[4] = {16, 16, 16, 16}, next[4] = {0, 0, 0, 0}, total = 0;\n    cint_view vp, vv, vn;\n    cint_ctx_config config;\n    cint_ctx *ctx = NULL;\n    cint_status s;\n\n    memset(&config, 0, sizeof config);\n    config.size = sizeof config;\n    config.program = cm_7_advance.program;\n    config.module = &cm_7_advance;\n    if (cint_ctx_create(&config, &ctx) != CINT_OK) return 1;\n    if (share(ctx, pos, 4, 0, &vp) != CINT_OK || share(ctx, vel, 4, 0, &vv) != CINT_OK ||\n        share(ctx, next, 4, 1, &vn) != CINT_OK) return 1;\n\n    s = cx_7_advance_7_advance(ctx, CINT_FUEL_UNBOUNDED, vp, vv, 1, vn);\n    printf(\"advance: status %d\\n\", s);\n    show(\"next\", next, 4);\n    s = cx_7_advance_5_total(ctx, CINT_FUEL_UNBOUNDED, vn, &total);\n    printf(\"total: status %d, result %\" PRId64 \"\\n\", s, total);"
  },
  {
   "id": "spec-03p:the-calling-sequence-p4",
   "edition": "SPEC-03P.1",
   "title": "7.3 The calling sequence (part 5)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-calling-sequence",
   "internal": 0,
   "content": "    vel[2] = INT64_C(4611686018427387904);   /* 2^62: vel[2] * 2 overflows */\n    s = cx_7_advance_7_advance(ctx, CINT_FUEL_UNBOUNDED, vp, vv, 2, vn);\n    printf(\"advance: status %d\\n\", s);\n    report(ctx);\n    show(\"next\", next, 4);\n\n    s = cx_7_advance_5_total(ctx, CINT_FUEL_UNBOUNDED, vn, &total);\n    printf(\"total: status %d\\n\", s);\n    printf(\"clear_fault: status %d\\n\", cint_ctx_clear_fault(ctx));\n    s = cx_7_advance_5_total(ctx, 100, vn, &total);\n    printf(\"total: status %d, result %\" PRId64 \"\\n\", s, total);\n\n    cint_buffer_release(ctx, vp.buffer);\n    cint_buffer_release(ctx, vv.buffer);\n    cint_buffer_release(ctx, vn.buffer);\n    cint_ctx_destroy(ctx);\n    return 0;\n}\n```\n\nBuilt and run, with `CINT_RT` naming the directory that holds `cint_rt.h` (`rt/` in the source tree):\n\n```console\n$ cint build --lib --out out advance.ci\nbuilt: out/libadvance.so\n$ cc -std=c17 -Wall -Wextra -Wpedantic -I \"$CINT_RT\" host.c -L out -ladvance -Wl,-rpath,'$ORIGIN/out' -o host\n$ ./host\nadvance: status 0\nnext = 16 17 18 19\ntotal: status 0, result 70\nadvance: status 1\nfault E_OVERFLOW mul.checked.i64 at advance.ci:3:31\n  operands: 4611686018427387904 2\n  kernel advance.advance, dispatch 0, work item 2\nnext = 16 17 18 19\ntotal: status 4\nclear_fault: status 0\ntotal: status 0, result 70\n```\n\n6. The second `advance` faults at work-item 2, where `vel[i] * dt` is 2^63. The output `next` keeps the contents the first call published, because the faulting dispatch publishes nothing. `total` then answers `CINT_FAULTED` (4) without running, and after `cint_ctx_clear_fault` it runs again with a budget of 100 fuel.\n\n**Notes**\n\n7. The wrapper names above are written out for clarity. A host that does not want to depend on the encoding finds each wrapper by its export name in the reflection table (7.4), as `tour.c` does in 10.1."
  },
  {
   "id": "spec-03p:the-reflection-table",
   "edition": "SPEC-03P.1",
   "title": "7.4 The reflection table",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-reflection-table",
   "internal": 0,
   "content": "### 7.4 The reflection table\n\nA library describes itself. From one symbol whose name is the same for every program, a host program finds every module, every export, its parameters, its type signature and its wrapper.\n\n**Synopsis**\n\n```text\ntypedef struct cint_name { const char *bytes; uint32_t len; uint32_t reserved; } cint_name;  /* UTF-8, no NUL */\n\ntypedef struct cint_export {            /* 72 bytes */\n    cint_name name;\n    uint32_t kind;                      /* CINT_EXPORT_FUNCTION 1, CINT_EXPORT_KERNEL 2 */\n    uint32_t effect;                    /* CINT_PURE 1, CINT_OBSERVE 2, CINT_UNRESTRICTED 3 */\n    uint32_t size_count, param_count;\n    const cint_name *size_names;        /* declaration order; NULL when size_count is 0 */\n    const cint_name *param_names;       /* declaration order; NULL when param_count is 0 */\n    const uint8_t *type_signature;      /* 7.5 */\n    uint64_t type_signature_len;\n    cint_entry_fn call;                 /* the wrapper, cast to void (*)(void) */\n} cint_export;\n\ntypedef struct cint_module_table {      /* 32 bytes */\n    const cint_module_info *info;       /* the module's descriptor */\n    uint32_t module;                    /* its index in info->program->modules */\n    uint32_t export_count;\n    const cint_export *exports;         /* declaration order */\n    const cint_name *record_names;      /* the qualified name of each record row of info */\n} cint_module_table;\n\ntypedef struct cint_library {           /* 16 bytes */\n    uint32_t abi;                       /* the interface version of 7.2 */\n    uint32_t module_count;\n    const cint_module_table *const *modules;\n} cint_library;\n\nextern const cint_library cint_library_desc;\n```\n\n**Semantics**"
  },
  {
   "id": "spec-03p:the-reflection-table-p1",
   "edition": "SPEC-03P.1",
   "title": "7.4 The reflection table (part 2)",
   "clauses": "A-14 A-19 H-2",
   "url": "/specifications/spec-03p/1/#the-reflection-table",
   "internal": 0,
   "content": "1. <a id=\"A-14\"></a>Each module of a program has a descriptor, `cm` followed by its encoded path, which holds the interface version, the program with its site tables and revision identity, and the module's table of record layouts. The descriptor of the root module is the one a host passes to `cint_ctx_create` [A-14].\n2. <a id=\"A-19\"></a>The library descriptor `cint_library_desc` leads to one table per module, in the order of the program's module table. A module's table holds its descriptor and one row per export that has a wrapper, in declaration order; only the root module's table has rows. A row gives the export's name, its kind, its effect class, the names of its size parameters and of its parameters, its type signature and its wrapper, which a host casts to the prototype the type signature gives. A struct parameter's view carries as `record_id` the index of the row of the root module's record layout table whose qualified name is the struct's [A-19].\n3. <a id=\"H-2\"></a>The effect class of an export is `CINT_PURE` (1) when it neither prints nor reaches a host function, and `CINT_OBSERVE` (2) when it, or a function it calls, prints, since a print statement is an output effect (9.1). A kernel is always pure [H-2].\n\n**Examples**\n\n4. This program lists the exports of `tour.ci` (10.1) and the bytes of each type signature after its 33-byte domain string:\n\n```c\n/* reflect.c: lists the exports of a library from its reflection table. */\n#include <inttypes.h>\n#include <stdio.h>\n#include \"cint_rt.h\"\n\nextern const cint_library cint_library_desc;\n\nstatic void names(const cint_name *n, uint32_t count)\n{\n    for (uint32_t k = 0; k < count; k++) printf(\"%s%.*s\", k ? \" \" : \"\", (int)n[k].len, n[k].bytes);\n}"
  },
  {
   "id": "spec-03p:the-reflection-table-p2",
   "edition": "SPEC-03P.1",
   "title": "7.4 The reflection table (part 3)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-reflection-table",
   "internal": 0,
   "content": "int main(void)\n{\n    printf(\"abi %\" PRIu32 \".%\" PRIu32 \", %\" PRIu32 \" module\\n\", cint_library_desc.abi >> 16,\n           cint_library_desc.abi & 0xFFFFu, cint_library_desc.module_count);\n    for (uint32_t m = 0; m < cint_library_desc.module_count; m++) {\n        const cint_module_table *t = cint_library_desc.modules[m];\n        const cint_module *mod = t->info->program->modules[t->module];\n        printf(\"module %.*s: %\" PRIu32 \" exports\\n\", (int)mod->path_len, mod->path, t->export_count);\n        for (uint32_t k = 0; k < t->export_count; k++) {\n            const cint_export *e = &t->exports[k];\n            printf(\"  %.*s: %s, effect %\" PRIu32 \", sizes [\", (int)e->name.len, e->name.bytes,\n                   e->kind == CINT_EXPORT_KERNEL ? \"kernel\" : \"function\", e->effect);\n            names(e->size_names, e->size_count);\n            printf(\"], parameters [\");\n            names(e->param_names, e->param_count);\n            printf(\"], signature %\" PRIu64 \" bytes\\n\", e->type_signature_len);\n            /* The bytes after the 33 of the domain string, 16 to a line. */\n            for (uint64_t j = 33; j < e->type_signature_len; j++)\n                printf(\"%s%02x%s\", (j - 33) % 16 == 0 ? \"    \" : \" \", e->type_signature[j],\n                       (j - 33) % 16 == 15 || j + 1 == e->type_signature_len ? \"\\n\" : \"\");\n        }\n    }\n    return 0;\n}\n```"
  },
  {
   "id": "spec-03p:the-reflection-table-p3",
   "edition": "SPEC-03P.1",
   "title": "7.4 The reflection table (part 4)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-reflection-table",
   "internal": 0,
   "content": "```console\n$ cint build --lib --out out tour.ci\nbuilt: out/libtour.so\n$ cc -std=c17 -Wall -Wextra -Wpedantic -I \"$CINT_RT\" reflect.c -L out -ltour -Wl,-rpath,'$ORIGIN/out' -o reflect\n$ ./reflect\nabi 3.2, 1 module\nmodule tour.ci: 3 exports\n  parse_u: function, effect 1, sizes [], parameters [s], signature 117 bytes\n    01 00 00 00 73 0f 00 00 00 74 6f 75 72 2e 50 61\n    72 73 65 45 72 72 6f 72 22 00 03 00 00 00 05 00\n    00 00 65 6d 70 74 79 09 00 00 00 62 61 64 5f 64\n    69 67 69 74 09 00 00 00 74 6f 6f 5f 6c 61 72 67\n    65 00 00 00 00 01 00 00 00 00 52 21 01 00 74 00\n    00 00 00 14\n  scale: kernel, effect 1, sizes [n], parameters [x k y], signature 82 bytes\n    00 00 00 00 01 00 00 00 03 00 00 00 00 52 14 01\n    01 00 00 00 00 00 00 00 00 00 00 00 00 00 14 02\n    52 14 01 01 00 00 00 00 00 00 00 00 00 00 00 00\n    00\n  greet: function, effect 2, sizes [], parameters [times], signature 48 bytes\n    00 00 00 00 00 00 00 00 01 00 00 00 00 14 14\n```\n\n5. `greet` prints, so its effect class is 2, `CINT_OBSERVE`. 7.5 reads the bytes."
  },
  {
   "id": "spec-03p:type-signatures",
   "edition": "SPEC-03P.1",
   "title": "7.5 Type signatures",
   "clauses": "A-20",
   "url": "/specifications/spec-03p/1/#type-signatures",
   "internal": 0,
   "content": "### 7.5 Type signatures\n\nA type signature is the exact description of an export's interface, in bytes a host can decode without the source: the mode and type of each parameter and the type of the result, with every struct and error set it names written out in full.\n\n**Syntax**\n\n```text\ntype_signature = domain       U32 29, then the ASCII bytes \"cint-core-1/type-signature/v1\"\n                 def_count    U32\n                 definitions  def_count definitions\n                 size_count   U32            the size parameters or shape symbols\n                 param_count  U32\n                 params       for each parameter: mode U8 (00 in, 01 inout, 02 out), then a type\n                 result       a type, or 00 for none\n```\n\n**Semantics**\n\n1. <a id=\"A-20\"></a>All integers of a type signature are little-endian. A type is a tag byte followed by its parameters [A-20]:\n\n| Tag | Form | Following bytes |\n|---|---|---|\n| `01` | `Bool` | none |\n| `11` to `18` | `I8`, `I16`, `I32`, `I64`, `I128`, `I256`, `I512`, `I1024` | none |\n| `21` to `24` | `U8`, `U16`, `U32`, `U64` | none |\n| `31` | `Q<i>.<f>` | the storage tag, `11` to `14`, then `f` as `U16` |\n| `52` | array | the element type; the rank as `U8`, 1 to 4; then one shape per dimension |\n| `71` | struct | the index of its definition, `U32` |\n| `73` | error-set value | the index of its definition, `U32` |\n| `74` | error union `E!T` | the index of the set's definition, `U32`; then `00` for `void` or the type `T` |"
  },
  {
   "id": "spec-03p:type-signatures-p1",
   "edition": "SPEC-03P.1",
   "title": "7.5 Type signatures (part 2)",
   "clauses": "A-21 A-22 A-24 A-25 A-26",
   "url": "/specifications/spec-03p/1/#type-signatures",
   "internal": 0,
   "content": "   A shape is a form byte and its values. Form `00` is any extent (`_`), form `01` an extent `B`, form `02` the range `L ..= B` with lower bound `L` as an `I64` then `B`. An extent or bound `B` is a size-symbol index as `U32` (`FF FF FF FF` for none) followed by an offset as `I64`, and its value is the symbol's value plus the offset: `n` is (0, 0) when `n` is the first size symbol, and `8` is (none, 8). An array occurs only as a parameter, or as a struct field with literal extents. An error union occurs only as a result.\n2. <a id=\"A-21\"></a>A struct or an error set is defined once in the signature and named by its index. A struct definition is `71`, the qualified name, a layout byte, the field count as `U32` and for each field its name, a bit width as `U8` (0 when not a bit field) and its type. An error-set definition is `73`, the qualified name, the underlying unsigned tag (`21` to `24`), the form `00`, the value count as `U32` and each value's name in tag order; a set that combines others has the form `01` and lists its member sets by definition index. A name is a `U32` length and UTF-8 bytes; a qualified name is the module's dotted name, a full stop and the declared name, such as `tour.ParseError`. Definitions are listed in the order in which a depth-first walk of the parameters, then the result, completes them, so a definition refers only to earlier ones [A-21].\n3. <a id=\"A-22\"></a>A type signature holds the modes, the types and the full definitions of named types, including the names of struct fields and error values. It holds no parameter name, size name, kind or effect class, which are fields of the table row, and no kernel `over` clause. Renaming a parameter therefore leaves the signature unchanged, and renaming a struct field changes it. A host passes every argument, since a default argument is filled in only by a cint caller [A-22].\n4. <a id=\"A-24\"></a>A typ"
  },
  {
   "id": "spec-03p:type-signatures-p2",
   "edition": "SPEC-03P.1",
   "title": "7.5 Type signatures (part 3)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#type-signatures",
   "internal": 0,
   "content": "**Examples**\n\n7. The signature of `scale` (10.1), `kernel scale[n](in I64[n] x, in I64 k, out I64[n] y)`, is shown below after its domain string, as 7.4 printed it:\n\n```text\n00 00 00 00                                         no definitions\n01 00 00 00  03 00 00 00                            one size symbol, three parameters\n00 52 14 01  01 00 00 00 00  00 00 00 00 00 00 00 00   in I64[n] x: array of I64, rank 1, extent (n, 0)\n00 14                                               in I64 k\n02 52 14 01  01 00 00 00 00  00 00 00 00 00 00 00 00   out I64[n] y\n00                                                  no result\n```\n\n8. The signature of `parse_u`, `ParseError!I64 parse_u(in U8[_] s)`, defines the error set first:\n\n```text\n01 00 00 00                                         one definition\n73 0f 00 00 00 \"tour.ParseError\" 22 00              0: error set, underlying U16, declared\n   03 00 00 00  05 00 00 00 \"empty\"  09 00 00 00 \"bad_digit\"  09 00 00 00 \"too_large\"\n00 00 00 00  01 00 00 00                            no size symbols, one parameter\n00 52 21 01 00                                      in U8[_] s: any extent\n74 00 00 00 00 14                                   result: error union of definition 0 and I64\n```"
  },
  {
   "id": "spec-03p:the-python-package",
   "edition": "SPEC-03P.1",
   "title": "8 The Python package",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-python-package",
   "internal": 0,
   "content": "## 8 The Python package"
  },
  {
   "id": "spec-03p:the-package-surface",
   "edition": "SPEC-03P.1",
   "title": "8.1 The package surface",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-package-surface",
   "internal": 0,
   "content": "### 8.1 The package surface\n\nThe package `cint` loads a library, or builds one from a `.ci` source, and makes each export a method of a context. It needs CPython 3.11 or later and nothing outside the standard library; a call that returns a NumPy array needs NumPy only when it is made.\n\n**Synopsis**\n\n```text\ncint.load(source, *, backend=\"cpu\") -> Module\nModule.context(*, device=None, record=None, fuel=10**9, depth=256,\n               frame_arena_elements=2_097_152) -> Context\nContext.<export>(*args, fuel=..., **written) -> result\nContext.entry(name) -> callable\nContext.fault() -> Fault | None             Context.clear_fault() -> None\nContext.fuel_consumed() -> int               Context.last_entry() -> EntryReport\nContext.checkpoint() -> bytes                Context.restore(data) -> None\nContext.state_hash() -> bytes                Context.entry_scope() -> context manager\ncint.borrow(obj, *, elem=None, writable=False, publish=None, layout=\"any\", context=None) -> View\ncint.copy(obj, *, elem=None, device=None, from_float=None) -> Buffer\ncint.empty(shape, elem, *, device=None) -> Buffer\ncint.from_float(obj, elem, *, rounding=\"half_even\", overflow=\"refuse\") -> Buffer\ncint.to_float(view_or_buffer, *, dtype=\"float64\") -> numpy.ndarray\ncint.Recorder(path, *, mode=\"full\")          cint.replay(module, path, *, backend=\"ref\", stop=None)\ncint.read_checkpoint(data) -> CheckpointView\n```\n\n**Semantics**"
  },
  {
   "id": "spec-03p:the-package-surface-p1",
   "edition": "SPEC-03P.1",
   "title": "8.1 The package surface (part 2)",
   "clauses": "BACK-15",
   "url": "/specifications/spec-03p/1/#the-package-surface",
   "internal": 0,
   "content": "1. `cint.load(path)` with a path to a `.ci` file builds the program with `cint build --lib` into a build directory keyed by the digests of its modules and the identity of the toolchain, so loading unchanged source again builds nothing; with a path to a library file it loads that file. The library a load builds from source also holds the checkpoint, recording and replay functions of the runtime, which 9.2 and 9.3 need; a library written by `cint build --lib` directly does not, and those calls on its contexts raise `NotImplementedError`. The `cint` command is the one the environment variable `CINT_EXE` names, else `cint` on the search path. `backend` is `\"cpu\"` for the executor `cpu-c17` or `\"cuda\"` for `gpu-cuda`; SPEC-09P.1 5.3 names every backend [SPEC-09P.1 BACK-15].\n2. `Module.context()` creates a context. `fuel` is the budget of each entry, `None` for no budget; `depth` is the call-depth limit; `frame_arena_elements` is the frame-arena capacity in 8-byte elements. Print statements of a context are discarded unless it records (9.3).\n3. Each export with a row in the reflection table is a method of the context, and `ctx.entry(name)` reaches the same call by name, which serves a name that is a Python keyword or a method of `Context`. A call builds its arguments from the row's parameter names, modes, element types and ranks. An argument the entry may write, which is a function's `inout` and a kernel's `out` and `inout`, is passed by name, as in `ctx.advance(p, v, 16, next=out)`, and the caller supplies every such array; other arguments are positional or named. A keyword `fuel=` sets the budget of one call. An export whose signature holds a struct is listed and reachable through `ctx.entry`, and calling it raises `NotImplementedError` naming the parameter.\n4. A completed call returns the export's result: a Python `int` for an integer, a `bool` for `Bool`, `None` for `vo"
  },
  {
   "id": "spec-03p:the-package-surface-p2",
   "edition": "SPEC-03P.1",
   "title": "8.1 The package surface (part 3)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-package-surface",
   "internal": 0,
   "content": "| Exception | Raised for |\n|---|---|\n| `cint.Fault` | `CINT_FAULT`. One subclass per code: `OverflowFault`, `DivZeroFault`, `BoundsFault`, `ShapeFault`, `ShiftFault`, `NarrowFault`, `AliasFault`, `StaleHandleFault`, `FuelFault`, `UnsupportedFault`, `DomainFault`, `DepthFault`, `AssertFault`. Its attributes are those of the fault record: `code`, `operation`, `operands`, `exact`, `limit`, `file`, `line`, `column`, `stack`, `revision`, `kernel`, `dispatch`, `phase`, `work_item`, `work_index`, `step`, `reason`, and `record`, the canonical bytes. |\n| `cint.Refused` | `CINT_REFUSED`: a refused call. It carries `code` and the operand fields, and no position. |\n| `cint.BorrowRefused` | A borrow that `cint.borrow` cannot make (8.2); a subclass of `Refused`. |\n| `cint.Busy` | `CINT_BUSY`, including an output with a live export. |\n| `cint.Faulted` | An entry on a context that holds a fault. `held` is that fault, and `nothing_ran` says whether it happened before any code of its entry ran, in which case `clear_fault()` alone restores the state. |\n| `cint.Unpublished` | Reading a `Buffer` that has never been published. |\n| `cint.StaleHandle` | Using a `View` or `Buffer` after its release. |\n| `cint.ResourceError` | `CINT_RESOURCE` during an entry. |\n| `cint.ReplayDivergence`, `cint.Unreplayable` | `CINT_DIVERGED` and `CINT_UNREPLAYABLE` from `cint.replay`. |\n| `cint.ErrorResult` | An entry that returned an error value. It is not a `Fault`. |\n| `cint.LoadError`, `cint.BuildError` | A library that cannot be loaded, or a source that cannot be built. |\n\n8. <a id=\"P-16\"></a>Each call releases the GIL while the entry runs. A second call on a context that is running an entry raises `cint.Busy`, and separate contexts may run in separate threads [P-16]."
  },
  {
   "id": "spec-03p:borrowing-cpu-arrays-without-a-copy",
   "edition": "SPEC-03P.1",
   "title": "8.2 Borrowing CPU arrays without a copy",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#borrowing-cpu-arrays-without-a-copy",
   "internal": 0,
   "content": "### 8.2 Borrowing CPU arrays without a copy\n\n`cint.borrow` lends the memory of a NumPy array, or of any object with the buffer protocol or DLPack, to cint code as it is. It copies nothing; what it cannot take as it is, it refuses, and says what to do instead.\n\n**Semantics**\n\n1. <a id=\"P-1\"></a>`cint.borrow` chooses a protocol. An object with the buffer protocol, whose `__dlpack_device__`, if it has one, reports `kDLCPU`, is borrowed through the buffer protocol: the package asks for `PyBUF_STRIDES | PyBUF_FORMAT`, with `PyBUF_WRITABLE` when `writable=True`, and never for indirect buffers. An object without the buffer protocol whose `__dlpack__` reports `kDLCPU` is borrowed through DLPack (8.3). Any other object is refused [P-1].\n2. <a id=\"P-2\"></a>The `View` holds the `Py_buffer` or the DLPack capsule, and with it a reference to the exporter, until it is released by `View.release()`, by the end of a `with` block, or by garbage collection. Holding the exporter keeps the memory alive; it does not keep it from changing (8.4) [P-2].\n3. <a id=\"P-3\"></a>The element type comes from the signedness of the format character and the reported item size, not from the character's nominal C type, so NumPy's `int64` maps to `I64` whether its format is `l` or `q`. The prefixes `@`, `=` and `<` mean native order, which is little-endian on every host [P-3]:\n\n| Format | Item size | Element |\n|---|---|---|\n| `b`, `h`, `i`, `l`, `q`, `n` | 1, 2, 4, 8 | `I8`, `I16`, `I32`, `I64` |\n| `B`, `H`, `I`, `L`, `Q`, `N` | 1, 2, 4, 8 | `U8`, `U16`, `U32`, `U64` |\n| `?` | 1 | `Bool`; each byte shall be 0 or 1, and is checked at entry |\n| `c` | 1 | refused; use `B` |\n| `e`, `f`, `d`, `g`, `Z...` | any | refused: floating-point data is converted explicitly (8.5) |\n| any, with the prefix `>` or `!` | any | refused; `cint.copy` takes it |\n| struct formats, `x`, `s`, `P`, `O` | any | refused |"
  },
  {
   "id": "spec-03p:borrowing-cpu-arrays-without-a-copy-p1",
   "edition": "SPEC-03P.1",
   "title": "8.2 Borrowing CPU arrays without a copy (part 2)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#borrowing-cpu-arrays-without-a-copy",
   "internal": 0,
   "content": "4. <a id=\"P-3a\"></a>`cint.copy` of a big-endian integer array converts each element's byte order exactly as it copies [P-3a].\n5. <a id=\"P-4\"></a>When `elem` is given, it shall equal the mapped element, except that a fixed-point `elem` whose storage type is the mapped element, such as `\"Q32.32\"` over `I64`, registers the buffer with that fixed-point type. Any other difference is refused. The package never converts [P-4].\n6. <a id=\"P-5\"></a>Byte strides shall be multiples of the item size, and the data pointer shall be aligned for the element type (7.2). Negative strides are accepted and registered as 6.5 describes [P-5].\n7. <a id=\"P-6\"></a>Rank 0 and ranks above 4 are refused. A scalar is passed as a Python `int` [P-6].\n8. <a id=\"P-7\"></a>`writable=True` over a read-only export is refused, and `writable=False` over a writable export gives a `read` view [P-7].\n9. <a id=\"P-8\"></a>`layout=\"C\"` or `layout=\"F\"` refuses an export that is not contiguous in that order; `layout=\"any\"` accepts any strided layout that passes paragraph 6 [P-8].\n10. <a id=\"P-9\"></a>`cint.borrow` never copies an input, under any combination of arguments. Every condition it cannot meet raises `BorrowRefused`, which names the condition and the alternative, usually `cint.copy`. The only copies that involve a borrowed `View` are the output copy that `publish=\"copy\"` asks for (6.4) and the snapshot of an input taken while recording [P-9].\n11. <a id=\"P-20\"></a>A `View` or `Buffer` is registered with a context on its first use there, after every argument of the entry has passed the checks of a refused call, and keeps that registration until it is released or the context is restored. After a restore, its next use registers it again under a new identifier [P-20].\n12. <a id=\"P-20a\"></a>An argument that is not a `View` or a `Buffer` but that `cint.borrow(obj)` would accept with its defaults, passed to an `in` "
  },
  {
   "id": "spec-03p:borrowing-cpu-arrays-without-a-copy-p2",
   "edition": "SPEC-03P.1",
   "title": "8.2 Borrowing CPU arrays without a copy (part 3)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#borrowing-cpu-arrays-without-a-copy",
   "internal": 0,
   "content": "**Examples**\n\n13. Transposed, Fortran-ordered and reversed arrays are borrowed as they are, and what cannot be borrowed is refused:\n\n```cint\n// grid.ci: views of rank 2, and two dispatches in one entry.\nexport I64 corner[h, w](in I64[h, w] a) {\n    return a[0, 0] * 1000 + a[h - 1, w - 1];\n}\n\nexport kernel triple[h, w](in I64[h, w] a, out I64[h, w] b) over [i: h, j: w] {\n    b[i, j] = a[i, j] * 3;\n}\n\nexport kernel double_it[n](in I64[n] x, out I64[n] y) over [i: n] {\n    y[i] = x[i] + x[i];\n}\n\nexport void twice[n](inout I64[n] a, inout I64[n] b) {\n    double_it(a, b);\n    double_it(b, a);\n}\n```\n\n```python\n# borrow.py: what cint.borrow takes without a copy, and what it refuses.\nimport numpy as np\nimport cint\n\nmod = cint.load(\"grid.ci\")\nctx = mod.context()\n\na = np.arange(6, dtype=np.int64).reshape(2, 3)\nprint(ctx.corner(a), ctx.corner(a.T), ctx.corner(np.asfortranarray(a)), ctx.corner(a[::-1, ::-1]))\nprint(cint.borrow(a[::-1, ::-1]))\nprint(cint.borrow(np.array([True, False])))\nprint(ctx.last_entry())\n\nrefused = {\n    \"float64\": lambda: cint.borrow(np.zeros(4)),\n    \"big-endian\": lambda: cint.borrow(np.zeros(4, dtype=\">i8\")),\n    \"misaligned\": lambda: cint.borrow(np.frombuffer(bytearray(17), dtype=np.int64, count=2, offset=1)),\n    \"rank 5\": lambda: cint.borrow(np.zeros((1, 1, 1, 1, 1), dtype=np.int64)),\n    \"writable over read-only\": lambda: cint.borrow(np.frombuffer(b\"abcd\", dtype=np.uint8), writable=True),\n}\nfor label, attempt in refused.items():\n    try:\n        attempt()\n    except cint.BorrowRefused as e:\n        print(label + \":\", type(e).__name__, e.code)\n\nprint(cint.copy(np.array([15625], dtype=\">i8\")).tolist())\nprint(cint.copy([[1, 2], [3, 4]], elem=\"I16\").tolist())\ntry:\n    ctx.corner([[1, 2], [3, 4]])\nexcept cint.Refused as e:\n    print(\"list:\", type(e).__name__, e.code)\n```"
  },
  {
   "id": "spec-03p:borrowing-cpu-arrays-without-a-copy-p3",
   "edition": "SPEC-03P.1",
   "title": "8.2 Borrowing CPU arrays without a copy (part 4)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#borrowing-cpu-arrays-without-a-copy",
   "internal": 0,
   "content": "```console\n$ python3 borrow.py\n5 5 5 5000\n<cint.View I64[2, 3] read-only, no publish via buffer protocol>\n<cint.View Bool[2] read-only, no publish via buffer protocol>\ncorner: no copies\nfloat64: BorrowRefused E_UNSUPPORTED\nbig-endian: BorrowRefused E_UNSUPPORTED\nmisaligned: BorrowRefused E_UNSUPPORTED\nrank 5: BorrowRefused E_UNSUPPORTED\nwritable over read-only: BorrowRefused E_UNSUPPORTED\n[15625]\n[[1, 2], [3, 4]]\nlist: Refused E_UNSUPPORTED\n```\n\n14. The transposed array `a.T` has shape (3, 2) and strides of 1 and 3 elements, and its corners are still 0 and 5. The reversed array is registered from its lowest address with a negative stride in each dimension, and the copy report of that call lists no copies. The big-endian array holds the 8-byte big-endian encoding of 15625, which `cint.copy` reads correctly."
  },
  {
   "id": "spec-03p:borrowing-through-dlpack",
   "edition": "SPEC-03P.1",
   "title": "8.3 Borrowing through DLPack",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#borrowing-through-dlpack",
   "internal": 0,
   "content": "### 8.3 Borrowing through DLPack\n\nDLPack lets an array library hand its memory to another without a copy. The package consumes DLPack for objects that offer no buffer protocol, and produces read-only DLPack capsules for its `Buffer` objects.\n\n**Semantics**"
  },
  {
   "id": "spec-03p:borrowing-through-dlpack-p1",
   "edition": "SPEC-03P.1",
   "title": "8.3 Borrowing through DLPack (part 2)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#borrowing-through-dlpack",
   "internal": 0,
   "content": "1. <a id=\"P-10\"></a>The package exchanges a DLPack capsule when it borrows, to read the tensor's description, and again at each entry that uses the `View`, calling `__dlpack__(stream=s, max_version=(1, 0), dl_device=None, copy=False)`. The data pointer, shape, strides and data type shall equal those of the first exchange; a change is refused. A producer that cannot honor `copy=False`, or a capsule marked `DLPACK_FLAG_BITMASK_IS_COPIED`, is refused. For CPU memory the stream is `None`; for CUDA memory it is the context's stream, so the producer's earlier writes come first [P-10].\n2. <a id=\"P-10a\"></a>If `__dlpack__` with `max_version` raises `TypeError`, the package calls it with `stream` alone, as the array API standard allows for older producers. Such an unversioned capsule cannot express read-only status or `copy=False`, so it is accepted only for a read-only borrow of CPU memory [P-10a].\n3. <a id=\"P-11\"></a>A device array shall be on the context's device. A CUDA array used with a context of another device, or with a CPU context, is refused before any exchange at the entry that binds it, or when it is borrowed if `context=` is given. There is no implicit transfer [P-11].\n4. <a id=\"P-12\"></a>The data types `kDLInt` and `kDLUInt` with 8, 16, 32 or 64 bits and one lane map to `I8` to `U64`, and `kDLBool` with 8 bits and one lane maps to `Bool`, whose bytes are checked at entry. Every other type code, every other width of `kDLBool`, and every lane count other than 1 is refused [P-12].\n5. <a id=\"P-13\"></a>DLPack strides are in elements, and a NULL `strides` means compact row-major order. `byte_offset` shall be a multiple of the element size. A tensor marked read-only gives a view whose ceiling is `read`, and `writable=True` over it is refused [P-13].\n6. <a id=\"P-14\"></a>The package calls each capsule's deleter when it no longer needs the tensor: a capsule of one entry wh"
  },
  {
   "id": "spec-03p:borrowing-through-dlpack-p2",
   "edition": "SPEC-03P.1",
   "title": "8.3 Borrowing through DLPack (part 3)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#borrowing-through-dlpack",
   "internal": 0,
   "content": "**Examples**\n\n7. An object that offers only DLPack is borrowed through it, and a `Buffer` exported through DLPack to NumPy is read-only:\n\n```python\n# dlpack.py: borrowing through DLPack, and the read-only mark on exports.\nimport numpy as np\nimport cint\n\nmod = cint.load(\"calls.ci\")\nctx = mod.context()\n\nclass DLPackOnly:\n    \"\"\"An array that offers DLPack and not the buffer protocol.\"\"\"\n    def __init__(self, a):\n        self.a = a\n    def __dlpack__(self, **kwargs):\n        return self.a.__dlpack__(**kwargs)\n    def __dlpack_device__(self):\n        return self.a.__dlpack_device__()\n\nx = np.arange(4, dtype=np.int64)\nv = cint.borrow(DLPackOnly(x))\nprint(v)\nbuf = cint.empty((4,), \"I64\")\nctx.square(v, y=buf)\nprint(buf.tolist())\n\nm = np.from_dlpack(buf)\nprint(\"writeable:\", m.flags.writeable)\ntry:\n    m[0] = 99\nexcept ValueError:\n    print(\"write refused; buf =\", buf.tolist())\ndel m\nwith memoryview(buf) as mv:\n    print(\"memoryview read-only:\", mv.readonly)\n```\n\n```console\n$ python3 dlpack.py\n<cint.View I64[4] read-only, no publish via DLPack>\n[0, 1, 4, 9]\nwriteable: False\nwrite refused; buf = [0, 1, 4, 9]\nmemoryview read-only: True\n```\n\n**Notes**\n\n8. Consumers differ in honoring the read-only mark (6.3). For CUDA arrays, which need a machine with an NVIDIA GPU, the rules above are those the package applies; no CUDA run is shown in this document."
  },
  {
   "id": "spec-03p:outputs-and-mutation-hazards",
   "edition": "SPEC-03P.1",
   "title": "8.4 Outputs and mutation hazards",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#outputs-and-mutation-hazards",
   "internal": 0,
   "content": "### 8.4 Outputs and mutation hazards\n\nResults reach Python memory in three ways: a kernel's output into a `Buffer`, a kernel's output copied into borrowed memory, and a function's `inout` array written in place. This subclause shows each, and what happens when memory is shared in ways the rules forbid.\n\n**Semantics**\n\n1. The rules of 6.4 apply to every output: a dispatch publishes all of its outputs or none, a borrowed output needs `writable=True, publish=\"copy\"`, and a function's `inout` array is written in place.\n2. A `Buffer` bound to a kernel output is pending for that dispatch, published when it completes, and keeps its previous contents when it faults. Reading it raises `Unpublished` only if it has never been published (6.2).\n3. While an entry runs with the GIL released, borrowed memory can be changed by another NumPy view, another thread or native code. No claim is made for memory that a foreign writer changes during a borrow: the result of such an entry is outside the replay contract, no error is raised, and memory safety is not claimed, since a writer can change an index value between its check and its use. A caller that cannot exclude such writers passes `cint.copy` of its input.\n4. The hazards, and what a caller does about each:"
  },
  {
   "id": "spec-03p:outputs-and-mutation-hazards-p1",
   "edition": "SPEC-03P.1",
   "title": "8.4 Outputs and mutation hazards (part 2)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#outputs-and-mutation-hazards",
   "internal": 0,
   "content": "| Situation | What happens | What the caller does |\n|---|---|---|\n| Input borrowed, nothing else writes it | Exact result | Nothing |\n| Input borrowed, another writer changes it during the call | No assurance, including memory safety | Use `cint.copy`, or synchronize |\n| Kernel output borrowed with `publish=\"copy\"` | Copied in when the dispatch completes | Accept the copy, or use a `Buffer` |\n| Kernel output borrowed without `publish=\"copy\"` | Entry fault `E_UNSUPPORTED`, `bind.limit` | Add `publish=\"copy\"`, or use a `Buffer` |\n| Kernel output given as a bare array | Refused | Pass a `View` or a `Buffer` |\n| Function `inout` array | Written in place; after a fault it holds the stores that completed | Pass a copy and copy it back, if all or nothing is needed |\n| One memory passed as input and output | Entry fault `E_ALIAS`, `bind.alias` | Use a separate output |\n| `Buffer` output with a live export | `Busy`, code `E_ALIAS` | End the export first |\n| `View` used after its release | `StaleHandle` | Borrow again |\n\n**Examples**\n\n5. The script below shows each case on the library `calls.ci`:\n\n```cint\n// calls.ci: the values and arrays that cross from Python.\nerror ParseError { empty, bad_digit, too_large }\n\nexport ParseError!I64 parse_u(in U8[_] s) {\n    if (len(s) == 0) {\n        return ParseError.empty;\n    }\n    I64 v = 0;\n    for i in 0..len(s) {\n        U8 c = s[i];\n        if (c < 48 || c > 57) {\n            return ParseError.bad_digit;\n        }\n        v = v * 10 + ((c - 48) as I64);\n    }\n    return v;\n}\n\nexport void scale[n](inout I32[n] a, I32 k) {\n    for i in 0..n {\n        a[i] = a[i] * k;\n    }\n}\n\nexport Bool positive(I64 x) {\n    return x > 0;\n}\n\nexport Bool both(Bool a, Bool b) {\n    return a && b;\n}\n\nexport I8 narrow(I64 x) {\n    return x as I8;\n}\n\nexport kernel square[n](in I64[n] x, out I64[n] y) over [i: n] {\n    y[i] = x[i] * x[i];\n}\n```"
  },
  {
   "id": "spec-03p:outputs-and-mutation-hazards-p2",
   "edition": "SPEC-03P.1",
   "title": "8.4 Outputs and mutation hazards (part 3)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#outputs-and-mutation-hazards",
   "internal": 0,
   "content": "```python\n# outputs.py: how results reach Python memory, and the hazards around them.\nimport numpy as np\nimport cint\n\nmod = cint.load(\"calls.ci\")\nctx = mod.context()\nx = np.arange(4, dtype=np.int64)\n\ndef show(label, call):\n    try:\n        call()\n        print(label + \": ok;\", ctx.last_entry())\n    except (cint.Fault, cint.Refused, cint.Busy, cint.Unpublished) as e:\n        parts = [type(e).__name__, getattr(e, \"code\", None), getattr(e, \"operation\", None)]\n        print(label + \":\", \" \".join(p for p in parts if p))\n        if isinstance(e, cint.Fault):\n            ctx.clear_fault()\n\n# A kernel output in borrowed memory needs publish=\"copy\".\ny = np.zeros(4, dtype=np.int64)\nshow(\"borrowed, no publish\", lambda: ctx.square(x, y=cint.borrow(y, writable=True)))\nshow(\"borrowed, publish copy\", lambda: ctx.square(x, y=cint.borrow(y, writable=True, publish=\"copy\")))\nprint(y.tolist())\nshow(\"bare array as output\", lambda: ctx.square(x, y=y))\nshow(\"same memory in and out\", lambda: ctx.square(x, y=cint.borrow(x, writable=True, publish=\"copy\")))\n\n# A Buffer is published by the runtime; a live export blocks it as an output.\nbuf = cint.empty((4,), \"I64\")\nshow(\"read before publication\", lambda: buf.tolist())\nshow(\"buffer\", lambda: ctx.square(x, y=buf))\nheld = np.asarray(buf)\nshow(\"buffer with a live export\", lambda: ctx.square(x, y=buf))\ndel held\nshow(\"after the export ends\", lambda: ctx.square(x, y=buf))\n\n# A function writes its inout argument in place, and a fault keeps finished stores.\na = np.array([1, 2, 3], dtype=np.int32)\nctx.scale(a=cint.borrow(a, writable=True), k=3)\nprint(a.tolist(), ctx.last_entry())\nb = np.array([1, 2**30, 3], dtype=np.int32)\nshow(\"scale overflow\", lambda: ctx.scale(a=cint.borrow(b, writable=True), k=4))\nprint(b.tolist())\n```"
  },
  {
   "id": "spec-03p:outputs-and-mutation-hazards-p3",
   "edition": "SPEC-03P.1",
   "title": "8.4 Outputs and mutation hazards (part 4)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#outputs-and-mutation-hazards",
   "internal": 0,
   "content": "```console\n$ python3 outputs.py\nborrowed, no publish: UnsupportedFault E_UNSUPPORTED bind.limit\nborrowed, publish copy: ok; square: 1 copy\n  publish-copy y: I64 x 4\n[0, 1, 4, 9]\nbare array as output: Refused E_UNSUPPORTED\nsame memory in and out: AliasFault E_ALIAS bind.alias\nread before publication: Unpublished\nbuffer: ok; square: 1 copy\n  staging y: I64 x 4\nbuffer with a live export: Busy E_ALIAS\nafter the export ends: ok; square: 1 copy\n  staging y: I64 x 4\n[3, 6, 9] scale: no copies\nscale overflow: OverflowFault E_OVERFLOW mul.checked.i32\n[4, 1073741824, 3]\n```\n\n6. The last call faults at `a[1] * 4`, which is 2^32 and outside `I32`. The store to `a[0]` had completed, so the array holds 4 there; `a[1]` and `a[2]` are unchanged."
  },
  {
   "id": "spec-03p:values-that-cross",
   "edition": "SPEC-03P.1",
   "title": "8.5 Values that cross",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#values-that-cross",
   "internal": 0,
   "content": "### 8.5 Values that cross\n\nScalars cross as Python values of exactly the parameter's type. Nothing converts implicitly: a value out of range, a value of another numeric type, or a floating-point value is refused before the call runs.\n\n**Semantics**"
  },
  {
   "id": "spec-03p:values-that-cross-p1",
   "edition": "SPEC-03P.1",
   "title": "8.5 Values that cross (part 2)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#values-that-cross",
   "internal": 0,
   "content": "1. <a id=\"P-21\"></a>A Python `int` for an integer parameter takes the parameter's type, and a value outside its range is refused with `E_NARROW`. A Python `bool` is refused for an integer parameter, although `bool` is a subclass of `int`. A `Bool` parameter takes `True` or `False`, as a Python `bool` or a `numpy.bool_`, and refuses an `int`; a `Bool` result is a Python `bool`. Text crosses as `in U8[n]`: Python passes `bytes`, which is borrowed for the call, and a `str` is refused, naming `s.encode(\"utf-8\")` [P-21].\n2. <a id=\"P-21a\"></a>A fixed-point parameter takes only a `cint.Fixed` of exactly its format. A bare `int` is refused, because it could mean the raw storage or the value; `cint.Fixed(\"Q32.32\", value=1)` has raw 4294967296, and `cint.Fixed(\"Q32.32\", raw=1)` is 2^-32. `cint.Fixed(..., value=v)` takes an `int` or a `fractions.Fraction` that is exactly representable and in range, and refuses any other with `E_NARROW` [P-21a].\n3. <a id=\"P-22\"></a>A NumPy integer scalar is taken for an integer parameter only if its kind and item size map to the parameter's type under 8.2: `numpy.int64` and `numpy.longlong` both map to `I64`, and `numpy.int32` for an `I64` parameter is refused [P-22].\n4. <a id=\"P-23\"></a>A Python `float`, a `numpy.floating` or a `decimal.Decimal` is refused for every parameter [P-23].\n5. <a id=\"P-24\"></a>Integer results are Python `int` values, exact at every width, and fixed-point results are `cint.Fixed`, whose decimal form is exact since its scale is a power of two [P-24].\n6. An entry that returns an error value raises `cint.ErrorResult`, which is not a `Fault`, and leaves the context Ready. It carries `set`, the error set; `name`, the value; and `tag`, its number from 1. Each error set of the module has its own subclass, reachable as an attribute of the module, so `except mod.ParseError` catches that set alone and `except cint.Fault` catches "
  },
  {
   "id": "spec-03p:values-that-cross-p2",
   "edition": "SPEC-03P.1",
   "title": "8.5 Values that cross (part 3)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#values-that-cross",
   "internal": 0,
   "content": "**Examples**\n\n17. Scalars, error results and conversions on `calls.ci` (8.4):\n\n```python\n# values.py: scalar values, error results and float conversions at the Python boundary.\nimport numpy as np\nimport cint\n\nmod = cint.load(\"calls.ci\")\nctx = mod.context()\n\ndef show(label, call):\n    try:\n        print(label + \":\", repr(call()))\n    except (cint.Fault, cint.Refused, cint.ErrorResult, TypeError) as e:\n        parts = [type(e).__name__, getattr(e, \"code\", None)]\n        print(label + \":\", \" \".join(p for p in parts if p))\n        if isinstance(e, cint.Fault):\n            ctx.clear_fault()\n\nshow(\"narrow(100)\", lambda: ctx.narrow(100))\nshow(\"narrow(300)\", lambda: ctx.narrow(300))\nshow(\"narrow(2**63)\", lambda: ctx.narrow(2**63))\nshow(\"narrow(np.int64(5))\", lambda: ctx.narrow(np.int64(5)))\nshow(\"narrow(np.longlong(5))\", lambda: ctx.narrow(np.longlong(5)))\nshow(\"narrow(np.int32(5))\", lambda: ctx.narrow(np.int32(5)))\nshow(\"narrow(True)\", lambda: ctx.narrow(True))\nshow(\"narrow(1.0)\", lambda: ctx.narrow(1.0))\nshow(\"positive(7)\", lambda: ctx.positive(7))\nshow(\"positive(True)\", lambda: ctx.positive(True))\nshow(\"both(True, np.bool_(True))\", lambda: ctx.both(True, np.bool_(True)))\nshow(\"both(1, 0)\", lambda: ctx.both(1, 0))\nshow(\"narrow(5, fuel=0)\", lambda: ctx.narrow(5, fuel=0))\nshow(\"narrow(5, fuel=-2)\", lambda: ctx.narrow(5, fuel=-2))\n\nshow(\"parse_u(b'123')\", lambda: ctx.parse_u(b\"123\"))\nshow(\"parse_u('123')\", lambda: ctx.parse_u(\"123\"))\ntry:\n    ctx.parse_u(b\"12x\")\nexcept mod.ParseError as e:\n    print(\"parse_u(b'12x'):\", e.set, e.name, e.tag, isinstance(e, cint.Fault))"
  },
  {
   "id": "spec-03p:values-that-cross-p3",
   "edition": "SPEC-03P.1",
   "title": "8.5 Values that cross (part 4)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#values-that-cross",
   "internal": 0,
   "content": "show(\"from_float\", lambda: cint.from_float(np.array([1.5, 2.5, -2.5, -0.0]), \"I64\").tolist())\nshow(\"from_float floor\", lambda: cint.from_float(np.array([1.5, -2.5]), \"I64\", rounding=\"floor\").tolist())\nshow(\"from_float Q16.16\", lambda: [q.raw for q in cint.from_float(np.array([1.5, 0.1]), \"Q16.16\").tolist()])\nshow(\"from_float NaN\", lambda: cint.from_float(np.array([1.0, float(\"nan\")]), \"I64\"))\nshow(\"from_float 2**63\", lambda: cint.from_float(np.array([2.0**63]), \"I64\"))\nshow(\"saturate\", lambda: cint.from_float(np.array([2.0**63]), \"I64\", overflow=\"saturate\").tolist())\nshow(\"to_float\", lambda: cint.to_float(cint.copy(np.array([2**53 + 1], dtype=np.int64))).tolist())\n```\n\n```console\n$ python3 values.py\nnarrow(100): 100\nnarrow(300): NarrowFault E_NARROW\nnarrow(2**63): Refused E_NARROW\nnarrow(np.int64(5)): 5\nnarrow(np.longlong(5)): 5\nnarrow(np.int32(5)): Refused E_UNSUPPORTED\nnarrow(True): Refused E_UNSUPPORTED\nnarrow(1.0): Refused E_UNSUPPORTED\npositive(7): True\npositive(True): Refused E_UNSUPPORTED\nboth(True, np.bool_(True)): True\nboth(1, 0): Refused E_UNSUPPORTED\nnarrow(5, fuel=0): FuelFault E_FUEL\nnarrow(5, fuel=-2): Refused E_NARROW\nparse_u(b'123'): 123\nparse_u('123'): Refused E_UNSUPPORTED\nparse_u(b'12x'): ParseError bad_digit 2 False\nfrom_float: [2, 2, -2, 0]\nfrom_float floor: [1, -3]\nfrom_float Q16.16: [98304, 6554]\nfrom_float NaN: Refused E_NARROW\nfrom_float 2**63: Refused E_NARROW\nsaturate: [9223372036854775807]\nto_float: [9007199254740992.0]\n```\n\n18. `narrow(300)` runs and faults inside the function, at the conversion `x as I8`, so it is a `NarrowFault`. `narrow(2**63)` never runs: 2^63 is not an `I64`, so the argument cannot be formed and the call is refused. `narrow(5, fuel=0)` is formed and runs out of fuel at the entry's own charge. `0.1` in `Q16.16` is 6553.6 before rounding, and `half_even` gives raw 6554."
  },
  {
   "id": "spec-03p:a-complete-example-with-numpy",
   "edition": "SPEC-03P.1",
   "title": "8.6 A complete example with NumPy",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#a-complete-example-with-numpy",
   "internal": 0,
   "content": "### 8.6 A complete example with NumPy\n\nThis program uses `advance.ci` (Introduction) from Python: it borrows two NumPy arrays without a copy, writes into a `Buffer`, reads the result through a read-only export, makes the kernel fault and recovers. It was run with Python 3.13 and NumPy 2.5.3.\n\n```python\n# numpy_example.py: advance.ci called from Python with NumPy arrays.\nimport numpy as np\nimport cint\n\nmod = cint.load(\"advance.ci\")          # builds the library once, then reuses it\nctx = mod.context()\n\nn = 8\npos = np.arange(n, dtype=np.int64)\nvel = np.full(n, 3, dtype=np.int64)\nnxt = cint.empty((n,), \"I64\")          # runtime-owned output, not yet published\n\nwith cint.borrow(pos) as p, cint.borrow(vel) as v:\n    ctx.advance(p, v, 16, next=nxt)\nprint(nxt.tolist())\nprint(ctx.last_entry())\n\nout = np.asarray(nxt)                  # a read-only export, no copy\nprint(out.flags.writeable, ctx.total(out))\ndel out                                # end the export before nxt is written again\n\nvel[5] = 2**62\ntry:\n    ctx.advance(pos, vel, 16, next=nxt)\nexcept cint.OverflowFault as f:\n    print(f.code, f.operation, f.operands, f.work_item, f.position)\n    print(f)\nprint(nxt.tolist())\n\ntry:\n    ctx.total(pos)\nexcept cint.Faulted as e:\n    print(\"Faulted, nothing ran:\", e.nothing_ran)\nctx.clear_fault()\nprint(ctx.total(pos))\n```\n\n```console\n$ python3 numpy_example.py\n[48, 49, 50, 51, 52, 53, 54, 55]\nadvance: 1 copy\n  staging next: I64 x 8\nFalse 412\nE_OVERFLOW mul.checked.i64 (4611686018427387904, 16) 5 advance.ci:3:31\nE_OVERFLOW at advance.ci:3:31\n\noperation: mul.checked.i64\nleft:      4611686018427387904\nright:     16\nresult:    73786976294838206464\nmaximum:   9223372036854775807\nkernel:    advance.advance, dispatch 0, phase work-item, work item 5, step 3\n[48, 49, 50, 51, 52, 53, 54, 55]\nFaulted, nothing ran: False\n28\n```"
  },
  {
   "id": "spec-03p:a-complete-example-with-numpy-p1",
   "edition": "SPEC-03P.1",
   "title": "8.6 A complete example with NumPy (part 2)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#a-complete-example-with-numpy",
   "internal": 0,
   "content": "1. The first call borrows `pos` and `vel` and writes `nxt`; the copy report lists the one copy, of `nxt` from staging storage. `np.asarray(nxt)` is a read-only export, and passing it to `total` borrows it again for the call.\n2. The second call passes the arrays bare, so each is borrowed for that call. Work-item 5 faults at `vel[i] * dt`, 2^62 times 16; the fault names the operation, both operands, the exact result and the bound. `nxt` keeps what the first call published.\n3. The context is then Faulted, and `total` raises `cint.Faulted` without running. The held fault happened while work-items ran, so `nothing_ran` is false and the host decides what state to rebuild. After `clear_fault`, `total(pos)` gives 0 + 1 + ... + 7 = 28."
  },
  {
   "id": "spec-03p:host-effects-checkpoints-and-replay",
   "edition": "SPEC-03P.1",
   "title": "9 Host effects, checkpoints and replay",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#host-effects-checkpoints-and-replay",
   "internal": 0,
   "content": "## 9 Host effects, checkpoints and replay"
  },
  {
   "id": "spec-03p:output-effects-and-ambient-access",
   "edition": "SPEC-03P.1",
   "title": "9.1 Output effects and ambient access",
   "clauses": "H-7 H-8",
   "url": "/specifications/spec-03p/1/#output-effects-and-ambient-access",
   "internal": 0,
   "content": "### 9.1 Output effects and ambient access\n\ncint code reaches the world outside its context only through what the host supplies. The one effect every library has is output: a print statement.\n\n**Semantics**\n\n1. <a id=\"H-8\"></a>cint source has no clock, environment, file, network, thread or random-source operation. Each of these reaches cint code only through what a host program supplies, so an entry's outcome depends only on its semantic inputs and on what crossed the boundary (SPEC-04P.2 5.2.7) [H-8].\n2. <a id=\"H-7\"></a>A print statement is an output effect: an effect with no result. Its bytes reach the host through the output callback (7.3), or are discarded. While a context records, each print statement is written to the recording as an effect with the bytes and the status the host returned; on replay the bytes are compared with the recording and not printed, and a difference stops replay with `CINT_DIVERGED` [H-7].\n\n**Examples**\n\n3. Each entry of the library `counter.ci` of 9.3, example 9, runs a print statement. While `record.py` records, each print is written to the recording as an effect, and the replays of that example compare its bytes with the recording."
  },
  {
   "id": "spec-03p:checkpoints",
   "edition": "SPEC-03P.1",
   "title": "9.2 Checkpoints",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#checkpoints",
   "internal": 0,
   "content": "### 9.2 Checkpoints\n\nA checkpoint is a context's state as bytes. Restoring it into a context of the same program gives back that state exactly, on either CPU executor and on any machine.\n\n**Semantics**"
  },
  {
   "id": "spec-03p:checkpoints-p1",
   "edition": "SPEC-03P.1",
   "title": "9.2 Checkpoints (part 2)",
   "clauses": "H-15 H-19 H-19a H-19b",
   "url": "/specifications/spec-03p/1/#checkpoints",
   "internal": 0,
   "content": "1. <a id=\"H-19\"></a>A checkpoint is an envelope, which holds the format name, the runtime contract and the digests of the build, and the canonical state of 5.1, which holds the revision identity. The envelope is not hashed. A checkpoint is taken between entries, of a Ready or a Faulted context. Restoring a checkpoint whose revision identity differs from the program's is refused with `CINT_REFUSED`, and so is one whose runtime contract version is not exactly that of the context's runtime. A checkpoint taken on another executor or machine, with the same revision identity, is accepted [H-19].\n2. <a id=\"H-19a\"></a>Checkpoint bytes are untrusted input. A restore checks every structural rule before it replaces any state: minimal encodings, known tags and lengths, arena extents within capacity, child arenas within their parents, registry extents consistent with stored contents, pool slots within capacity, distinct and vacant free-list entries, generations within range, identifier counters above every identifier present and no trailing bytes. Malformed input is refused with `CINT_REFUSED`, and the context is unchanged [H-19a].\n3. <a id=\"H-15\"></a>The revision identity of a program is a SHA-256 digest over the profile, the runtime contract and the canonical intermediate form of the program with every module it imports, as SPEC-01P.2 specifies. It is the same for every executor and every machine, and it changes when the program or the runtime contract changes. A fault record, a checkpoint and a recording each carry it [H-15].\n4. In Python, `Context.checkpoint()` returns the bytes, `Context.restore(data)` restores them, `Context.state_hash()` gives the 32-byte state hash and `cint.read_checkpoint(data)` decodes a checkpoint into a read-only view of its globals, arenas, pools, registry, counters and fault record.\n5. <a id=\"H-19b\"></a>Between entries, a context can move to another"
  },
  {
   "id": "spec-03p:recordings-and-replay",
   "edition": "SPEC-03P.1",
   "title": "9.3 Recordings and replay",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#recordings-and-replay",
   "internal": 0,
   "content": "### 9.3 Recordings and replay\n\nA recording holds the context's initial state, every call the host made on the context and every outcome, so that a run can be checked again without its environment. Replay makes the same calls on a new context and compares each outcome.\n\n**Semantics**"
  },
  {
   "id": "spec-03p:recordings-and-replay-p1",
   "edition": "SPEC-03P.1",
   "title": "9.3 Recordings and replay (part 2)",
   "clauses": "H-14 H-14b H-16 H-17 H-17a H-18 H-20 H-21",
   "url": "/specifications/spec-03p/1/#recordings-and-replay",
   "internal": 0,
   "content": "1. <a id=\"H-14b\"></a>A host records a context through a recorder, which makes the host's calls on the context and writes their events. Beginning a recording writes its header, the code of the program, and a checkpoint of the context as it is. Each entry, checkpoint, restore and cleared fault is then made through the recorder, and print statements are written as effects. Ending the recording writes its last event. A context is recorded by one recorder at a time. In cint 0.2.0 a recorded entry takes integer and `Bool` arguments only: an entry with an array argument is refused while recording [H-14b].\n2. <a id=\"H-14\"></a>A recording consists of a header, which holds the profile, the fuel model, the runtime contract, the revision identity and the recording mode; the code of each revision it runs; the initial checkpoint; and the stream of events [H-14]:\n   - `entry`: its sequence number, the export's name, its canonical arguments, its fuel budget, depth limit and frame-arena capacity;\n   - `effect`: the bytes of a print statement and the status the host returned;\n   - `outcome`: the status, the fault record bytes if any, the fuel consumed, the result or the error result and the state hash;\n   - `checkpoint`, `restore` and `clear_fault`, with the state hashes and the record they concern;\n   - `end`, written last, with the head of the chain of digests over the events and the number of events. A recording without it is incomplete and is never loaded in part.\n3. <a id=\"H-18\"></a>A recording is in `full` mode unless `digest` is asked for. A `full` recording reproduces a run on its own; a `digest` recording holds digests in place of input contents and checks a run whose inputs are supplied again [H-18].\n4. <a id=\"H-17\"></a><a id=\"H-17a\"></a>Replay checks the recording whole, its checkpoints and its chain of digests, before it reads any of it. It then restores the initial checkpo"
  },
  {
   "id": "spec-03p:recordings-and-replay-p2",
   "edition": "SPEC-03P.1",
   "title": "9.3 Recordings and replay (part 3)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#recordings-and-replay",
   "internal": 0,
   "content": "**Examples**\n\n9. The library below has module state:\n\n```cint\n// counter.ci: a library with module state, for checkpoints and recordings.\nI64 tally = 0;\n\nexport I64 bump(I64 amount) {\n    tally += amount;\n    \"tally is {tally}\\n\";\n    return tally;\n}\n```\n\nThe program records a session with a checkpoint, a restore and a fault, replays it on both CPU executors, stops a replay after two entries, and reads the checkpoint it took:\n\n```python\n# record.py: checkpoints, a recording, and its replay on both CPU executors.\nimport cint\n\nmod = cint.load(\"counter.ci\")\nwith cint.Recorder(\"run.cintrec\") as rec:\n    ctx = mod.context(record=rec)\n    print(ctx.bump(2), ctx.bump(40))\n    saved = ctx.checkpoint()\n    print(ctx.bump(1))\n    ctx.restore(saved)\n    print(ctx.bump(10))\n    try:\n        ctx.bump(2**62)\n        ctx.bump(2**62)\n    except cint.OverflowFault as f:\n        print(f.operation, f.operands)\n    ctx.clear_fault()\n    final = ctx.state_hash()\n\nfor backend in (\"ref\", \"cpu\"):\n    result = cint.replay(mod, \"run.cintrec\", backend=backend)\n    print(backend, result.status, result.boundaries, result.final_state_hash == final)\n\npart = cint.replay(mod, \"run.cintrec\", stop=2)\nprint(part.status, part.stopped, part.boundaries)\nfresh = mod.context()\nfresh.restore(part.checkpoint)\nprint(fresh.bump(0))\n\nview = cint.read_checkpoint(saved)\nprint(view.globals)\n```\n\n```console\n$ python3 record.py\n2 42\n43\n52\nadd.checked.i64 (4611686018427387956, 4611686018427387904)\nref ok 6 True\ncpu ok 6 True\nok True 2\n42\n(Global(name='counter.tally', type='I64', value=42),)\n```"
  },
  {
   "id": "spec-03p:recordings-and-replay-p3",
   "edition": "SPEC-03P.1",
   "title": "9.3 Recordings and replay (part 4)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#recordings-and-replay",
   "internal": 0,
   "content": "10. The restore takes `tally` back to 42, so the next `bump(10)` gives 52. The second `bump(2**62)` overflows; the fault and the cleared fault are recorded. Each replay makes the six entries again, compares every outcome and ends with the same state hash. The replay stopped after two entries leaves `tally` at 42, which a new context restores from the replay's checkpoint."
  },
  {
   "id": "spec-03p:worked-cases-that-run",
   "edition": "SPEC-03P.1",
   "title": "10 Worked cases that run",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#worked-cases-that-run",
   "internal": 0,
   "content": "## 10 Worked cases that run"
  },
  {
   "id": "spec-03p:a-tour-of-the-c-interface",
   "edition": "SPEC-03P.1",
   "title": "10.1 A tour of the C interface",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#a-tour-of-the-c-interface",
   "internal": 0,
   "content": "### 10.1 A tour of the C interface\n\nThis program uses the library `tour.ci` and finds each wrapper by name in the reflection table. It shows an error result, the output callback and the busy flag, a buffer the runtime creates, a lease, refused calls and entry faults.\n\n```cint\n// tour.ci: a library for a tour of the C interface.\nerror ParseError { empty, bad_digit, too_large }\n\nexport ParseError!I64 parse_u(in U8[_] s) {\n    if (len(s) == 0) {\n        return ParseError.empty;\n    }\n    I64 v = 0;\n    for i in 0..len(s) {\n        U8 c = s[i];\n        if (c < 48 || c > 57) {\n            return ParseError.bad_digit;\n        }\n        v = v * 10 + ((c - 48) as I64);\n    }\n    return v;\n}\n\nexport kernel scale[n](in I64[n] x, in I64 k, out I64[n] y) over [i: n] {\n    y[i] = x[i] * k;\n}\n\nexport I64 greet(I64 times) {\n    for i in 0..times {\n        \"hello {i}\\n\";\n    }\n    return times;\n}\n```\n\n```c\n/* tour.c: error results, print output, leases, refused calls and entry faults. */\n#include <inttypes.h>\n#include <stdio.h>\n#include <string.h>\n#include \"cint_rt.h\"\n\nextern const cint_library cint_library_desc;\n\ntypedef struct { uint16_t tag; int64_t value; } parse_result;   /* ParseError!I64 */\ntypedef cint_status (*parse_fn)(cint_ctx *, int64_t, cint_view, parse_result *);\ntypedef cint_status (*scale_fn)(cint_ctx *, int64_t, cint_view, int64_t, cint_view);\ntypedef cint_status (*greet_fn)(cint_ctx *, int64_t, int64_t, int64_t *);\n\nstatic const char *const fault_names[] = {\"\", \"E_OVERFLOW\", \"E_DIV_ZERO\", \"E_BOUNDS\", \"E_SHAPE\",\n    \"E_SHIFT\", \"E_NARROW\", \"E_ALIAS\", \"E_STALE_HANDLE\", \"E_FUEL\", \"E_UNSUPPORTED\", \"E_DOMAIN\",\n    \"E_DEPTH\", \"E_ASSERT\"};"
  },
  {
   "id": "spec-03p:a-tour-of-the-c-interface-p1",
   "edition": "SPEC-03P.1",
   "title": "10.1 A tour of the C interface (part 2)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#a-tour-of-the-c-interface",
   "internal": 0,
   "content": "/* The wrapper of an export, found by name in the reflection table. */\nstatic cint_entry_fn find(const char *name)\n{\n    const cint_module_table *t = cint_library_desc.modules[0];\n    for (uint32_t k = 0; k < t->export_count; k++)\n        if (t->exports[k].name.len == strlen(name) && memcmp(t->exports[k].name.bytes, name, strlen(name)) == 0)\n            return t->exports[k].call;\n    return NULL;\n}\n\n/* Receives the bytes of each print statement. The first time, it also tries to call back\n   into the context, which is busy with the entry that printed. */\nstatic cint_ctx *reentry;\nstatic cint_status out(void *user, const uint8_t *bytes, size_t len)\n{\n    printf(\"%s%.*s\", (const char *)user, (int)len, (const char *)bytes);\n    if (reentry != NULL) {\n        printf(\"  (clear_fault from the callback: status %d)\\n\", cint_ctx_clear_fault(reentry));\n        reentry = NULL;\n    }\n    return CINT_OK;\n}\n\nstatic cint_view view_of(cint_buffer_id id, uint64_t gen, int64_t n, uint8_t perm)\n{\n    cint_view v;\n    memset(&v, 0, sizeof v);\n    v.buffer = id;\n    v.generation = gen;\n    v.type.code = CINT_TAG_I64;\n    v.rank = 1;\n    v.perm = perm;\n    v.shape[0] = n;\n    v.stride[0] = 1;\n    return v;\n}\n\n/* Registers n elements of host memory, with publish none, and returns a view of them. */\nstatic cint_view borrow(cint_ctx *ctx, void *p, uint16_t code, int64_t n, int writable)\n{\n    cint_buffer_desc d;\n    cint_buffer_id id = 0;\n    uint64_t gen = 0;\n    memset(&d, 0, sizeof d);\n    d.size = sizeof d;\n    d.writable = writable ? 1u : 0u;\n    d.type.code = code;\n    d.mem.kind = CINT_MEM_HOST;\n    d.mem.u.host.ptr = p;\n    d.extent = n;\n    cint_buffer_register(ctx, &d, &id, &gen);\n    cint_view v = view_of(id, gen, n, writable ? CINT_VIEW_WRITE : CINT_VIEW_READ);\n    v.type.code = code;\n    return v;\n}"
  },
  {
   "id": "spec-03p:a-tour-of-the-c-interface-p2",
   "edition": "SPEC-03P.1",
   "title": "10.1 A tour of the C interface (part 3)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#a-tour-of-the-c-interface",
   "internal": 0,
   "content": "/* A tagged I64 or U64 value: its tag byte, then 8 bytes, little-endian. */\nstatic uint64_t bits_of(const cint_tvalue *t)\n{\n    uint64_t u = 0;\n    for (int k = 8; k >= 1; k--) u = (u << 8) | t->bytes[k];\n    return u;\n}\n\n/* Prints the held fault, then clears it. */\nstatic void show_fault(cint_ctx *ctx)\n{\n    static cint_fault_record r;\n    size_t len = 0;\n    cint_ctx_fault(ctx, &r);\n    cint_fault_get(ctx, NULL, 0, &len);\n    printf(\"  %s %.*s, operands\", fault_names[r.code], (int)r.operation_len, r.operation);\n    for (unsigned k = 0; k < r.operand_count; k++) printf(\" %\" PRIu64, bits_of(&r.operands[k]));\n    if (r.has_limit) printf(\", limit %\" PRIu64, bits_of(&r.limit));\n    printf(\", %zu canonical bytes\\n\", len);\n    cint_ctx_clear_fault(ctx);\n}\n\nint main(void)\n{\n    const parse_fn parse_u = (parse_fn)find(\"parse_u\");\n    const scale_fn scale = (scale_fn)find(\"scale\");\n    const greet_fn greet = (greet_fn)find(\"greet\");\n    int64_t xs[4] = {1, 2, 3, 4}, zs[4] = {0}, copy[4] = {0}, result = 0;\n    cint_ctx_config config;\n    cint_ctx *ctx = NULL;\n    cint_status s;\n    uint32_t why = 0;\n\n    memset(&config, 0, sizeof config);\n    config.size = sizeof config;\n    config.program = cint_library_desc.modules[0]->info->program;\n    config.module = cint_library_desc.modules[0]->info;\n    config.output = out;\n    config.output_user = \"  | \";\n    if (cint_ctx_create(&config, &ctx) != CINT_OK) return 1;"
  },
  {
   "id": "spec-03p:a-tour-of-the-c-interface-p3",
   "edition": "SPEC-03P.1",
   "title": "10.1 A tour of the C interface (part 4)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#a-tour-of-the-c-interface",
   "internal": 0,
   "content": "    /* 1. An error result completes the entry. */\n    const char *texts[2] = {\"123\", \"12x\"};\n    for (int k = 0; k < 2; k++) {\n        parse_result pr;\n        const cint_error_set *set = NULL;\n        uint64_t tag = 0;\n        cint_view v = borrow(ctx, (void *)texts[k], CINT_TAG_U8, 3, 0);\n        s = parse_u(ctx, CINT_FUEL_UNBOUNDED, v, &pr);\n        cint_ctx_error(ctx, &set, &tag);\n        if (set == NULL)\n            printf(\"parse_u(\\\"%s\\\"): status %d, value %\" PRId64 \"\\n\", texts[k], s, pr.value);\n        else\n            printf(\"parse_u(\\\"%s\\\"): status %d, tag %u, error %s.%s\\n\", texts[k], s, pr.tag, set->name,\n                   set->values[tag - 1]);\n        cint_buffer_release(ctx, v.buffer);\n    }\n\n    /* 2. Print statements reach the output callback. */\n    reentry = ctx;\n    s = greet(ctx, CINT_FUEL_UNBOUNDED, 2, &result);\n    printf(\"greet: status %d, result %\" PRId64 \"\\n\", s, result);"
  },
  {
   "id": "spec-03p:a-tour-of-the-c-interface-p4",
   "edition": "SPEC-03P.1",
   "title": "10.1 A tour of the C interface (part 5)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#a-tour-of-the-c-interface",
   "internal": 0,
   "content": "    /* 3. A runtime-owned output, read through a lease and by copy. */\n    cint_view x = borrow(ctx, xs, CINT_TAG_I64, 4, 0);\n    cint_buffer_id yid = 0;\n    uint64_t ygen = 0, lease = 0;\n    cint_type i64;\n    memset(&i64, 0, sizeof i64);\n    i64.code = CINT_TAG_I64;\n    cint_buffer_create(ctx, i64, 4, 0, &yid, &ygen);\n    cint_view y = view_of(yid, ygen, 4, CINT_VIEW_WRITE);\n    s = scale(ctx, CINT_FUEL_UNBOUNDED, x, 10, y);\n    const void *addr = NULL;\n    cint_buffer_lease(ctx, yid, &addr, &lease);\n    const int64_t *ys = addr;\n    printf(\"scale: status %d, y = %\" PRId64 \" %\" PRId64 \" %\" PRId64 \" %\" PRId64 \" (lease %\" PRIu64 \")\\n\", s,\n           ys[0], ys[1], ys[2], ys[3], lease);\n    printf(\"scale while leased: status %d\\n\", scale(ctx, CINT_FUEL_UNBOUNDED, x, 100, y));\n    cint_lease_end(ctx, lease);\n    s = scale(ctx, CINT_FUEL_UNBOUNDED, x, 100, y);\n    cint_buffer_read(ctx, y, copy, sizeof copy);\n    printf(\"after lease_end: status %d, y = %\" PRId64 \" %\" PRId64 \" %\" PRId64 \" %\" PRId64 \"\\n\", s, copy[0],\n           copy[1], copy[2], copy[3]);\n\n    /* 4. Arguments that cannot be formed are refused. */\n    cint_view unknown = x;\n    unknown.buffer = 99;\n    s = scale(ctx, CINT_FUEL_UNBOUNDED, unknown, 1, y);\n    cint_ctx_refusal(ctx, &why);\n    printf(\"unknown buffer: status %d, reason %u\\n\", s, why);\n    cint_view wide = y;\n    wide.shape[0] = 5;\n    s = scale(ctx, CINT_FUEL_UNBOUNDED, x, 1, wide);\n    cint_ctx_refusal(ctx, &why);\n    printf(\"view past the extent: status %d, reason %u\\n\", s, why);\n    cint_view upgraded = x;\n    upgraded.perm = CINT_VIEW_WRITE;\n    s = scale(ctx, CINT_FUEL_UNBOUNDED, x, 1, upgraded);\n    cint_ctx_refusal(ctx, &why);\n    printf(\"write view of read-only memory: status %d, reason %u\\n\", s, why);\n    printf(\"fuel -2: status %d\\n\", scale(ctx, -2, x, 1, y));"
  },
  {
   "id": "spec-03p:a-tour-of-the-c-interface-p5",
   "edition": "SPEC-03P.1",
   "title": "10.1 A tour of the C interface (part 6)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#a-tour-of-the-c-interface",
   "internal": 0,
   "content": "    /* 5. Arguments that can be formed are checked at entry, and fail as faults. */\n    cint_view old = x;\n    old.generation = 7;\n    printf(\"wrong generation: status %d\\n\", scale(ctx, CINT_FUEL_UNBOUNDED, old, 1, y));\n    show_fault(ctx);\n    printf(\"read view as output: status %d\\n\", scale(ctx, CINT_FUEL_UNBOUNDED, x, 1, x));\n    show_fault(ctx);\n    cint_view short_y = y;\n    short_y.shape[0] = 3;\n    printf(\"short output: status %d\\n\", scale(ctx, CINT_FUEL_UNBOUNDED, x, 1, short_y));\n    show_fault(ctx);\n    cint_view z = borrow(ctx, zs, CINT_TAG_I64, 4, 1);\n    printf(\"borrowed output, publish none: status %d\\n\", scale(ctx, CINT_FUEL_UNBOUNDED, x, 1, z));\n    show_fault(ctx);\n\n    cint_buffer_release(ctx, x.buffer);\n    s = scale(ctx, CINT_FUEL_UNBOUNDED, x, 1, y);\n    cint_ctx_refusal(ctx, &why);\n    printf(\"released input: status %d, reason %u\\n\", s, why);\n    cint_buffer_release(ctx, yid);\n    cint_ctx_destroy(ctx);\n    return 0;\n}\n```\n\nBuilt and run, after the `cint build --lib --out out tour.ci` of 7.4:"
  },
  {
   "id": "spec-03p:a-tour-of-the-c-interface-p6",
   "edition": "SPEC-03P.1",
   "title": "10.1 A tour of the C interface (part 7)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#a-tour-of-the-c-interface",
   "internal": 0,
   "content": "```console\n$ cc -std=c17 -Wall -Wextra -Wpedantic -I \"$CINT_RT\" tour.c -L out -ltour -Wl,-rpath,'$ORIGIN/out' -o tour\n$ ./tour\nparse_u(\"123\"): status 0, value 123\nparse_u(\"12x\"): status 0, tag 2, error tour.ParseError.bad_digit\n  | hello 0\n  (clear_fault from the callback: status 3)\n  | hello 1\ngreet: status 0, result 2\nscale: status 0, y = 10 20 30 40 (lease 1)\nscale while leased: status 3\nafter lease_end: status 0, y = 100 200 300 400\nunknown buffer: status 2, reason 1\nview past the extent: status 2, reason 7\nwrite view of read-only memory: status 2, reason 9\nfuel -2: status 2\nwrong generation: status 1\n  E_STALE_HANDLE bind.stale, operands 0 7, limit 1, 155 canonical bytes\nread view as output: status 1\n  E_ALIAS bind.permission, operands 2, 142 canonical bytes\nshort output: status 1\n  E_SHAPE bind.shape, operands 2 0 3, limit 4, 164 canonical bytes\nborrowed output, publish none: status 1\n  E_UNSUPPORTED bind.limit, operands 2, 137 canonical bytes\nreleased input: status 2, reason 2\n```"
  },
  {
   "id": "spec-03p:a-tour-of-the-c-interface-p7",
   "edition": "SPEC-03P.1",
   "title": "10.1 A tour of the C interface (part 8)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#a-tour-of-the-c-interface",
   "internal": 0,
   "content": "1. Both calls of `parse_u` complete with status 0 (7.3 paragraph 3). The second returns `ParseError.bad_digit`: the tag in the result is 2, the second value of the set and `cint_ctx_error` gives the set's qualified name and the value's name. The context is not faulted, and the next call runs.\n2. Each print statement of `greet` reaches `out` whole, with the `output_user` pointer of the configuration. The first time, `out` calls `cint_ctx_clear_fault` on the context that is running `greet`, against 7.2 paragraph 2, to show what the runtime does: it answers `CINT_BUSY` (3) and changes nothing, and `greet` goes on to return 2.\n3. `y` is storage the runtime created, zero-filled, and `scale` writes it (6.2). The lease gives its address for reading, and lease numbers count from 1. While the lease is live, a call that binds `y` to an output returns `CINT_BUSY` and runs nothing; after `cint_lease_end` the same call runs, and `cint_buffer_read` copies the new contents out (6.3).\n4. Five calls are refused, and none of them runs or changes the context (7.1 paragraphs 3 and 10). Buffer 99 was never issued (reason 1). A view of five elements of a four-element buffer reaches outside its registration (reason 7). A write view of `x`, which was registered read-only, is reason 9. A fuel budget of -2 is refused. At the end, after `x` is released, a view with its old identifier is reason 2.\n5. Four calls have arguments that can be formed, so the wrapper checks them at entry and faults with no fuel charged (7.1 paragraph 11). A view of `x` with generation 7, against a registration of generation 1, is `bind.stale`, with the parameter index and the generation as operands and the registration's generation as the limit. The read view `x` passed for the output `y` is `bind.permission` for parameter 2. A three-element view for `y`, after `n` took 4 from `x`, is `bind.shape`: parameter 2, dimensi"
  },
  {
   "id": "spec-03p:dispatches-within-one-entry",
   "edition": "SPEC-03P.1",
   "title": "10.2 Dispatches within one entry",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#dispatches-within-one-entry",
   "internal": 0,
   "content": "### 10.2 Dispatches within one entry\n\nAn entry can issue several dispatches, and each publishes its outputs when it completes. This program calls `twice` of `grid.ci` (8.2), a function that issues two dispatches of the kernel `double_it`, the first writing `b` from `a` and the second writing `a` from `b`. It then calls `double_it` directly with two work-items that overflow.\n\n```python\n# dispatches.py: two dispatches in one entry, and the fault of the lowest work-item.\nimport numpy as np\nimport cint\n\nmod = cint.load(\"grid.ci\")\nctx = mod.context()\n\na = np.array([1, 2, 3], dtype=np.int64)\nb = np.zeros(3, dtype=np.int64)\nctx.twice(a=cint.borrow(a, writable=True), b=cint.borrow(b, writable=True))\nprint(a.tolist(), b.tolist())\n\na = np.array([1, 2**61, 3], dtype=np.int64)\nb = np.zeros(3, dtype=np.int64)\ntry:\n    ctx.twice(a=cint.borrow(a, writable=True), b=cint.borrow(b, writable=True))\nexcept cint.OverflowFault as f:\n    print(f.operation, \"dispatch\", f.dispatch, \"work item\", f.work_item)\nprint(a.tolist(), b.tolist())\nctx.clear_fault()\n\nx = np.zeros(1000, dtype=np.int64)\nx[900] = 2**62\nx[7] = 2**62\ntry:\n    ctx.double_it(x, y=cint.empty((1000,), \"I64\"))\nexcept cint.OverflowFault as f:\n    print(f.operation, \"dispatch\", f.dispatch, \"work item\", f.work_item)\n```\n\n```console\n$ python3 dispatches.py\n[4, 8, 12] [2, 4, 6]\nadd.checked.i64 dispatch 1 work item 1\n[1, 2305843009213693952, 3] [2, 4611686018427387904, 6]\nadd.checked.i64 dispatch 0 work item 7\n```"
  },
  {
   "id": "spec-03p:dispatches-within-one-entry-p1",
   "edition": "SPEC-03P.1",
   "title": "10.2 Dispatches within one entry (part 2)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#dispatches-within-one-entry",
   "internal": 0,
   "content": "1. The first call leaves `b` equal to twice the old `a`, and then `a` equal to twice `b`.\n2. In the second call, dispatch 0 completes and publishes `b`, whose second element is 2^62. Dispatch 1 faults at work-item 1, where 2^62 + 2^62 is 2^63. Nothing of dispatch 1 is published: `a` holds what it held before the call, and `b` keeps what dispatch 0 published (6.4 paragraph 1).\n3. Dispatch numbers count from 0 in each entry. The direct call of `double_it` is a new entry, so its one dispatch is number 0. Work-items 7 and 900 both overflow, and the fault reported is that of work-item 7, the lowest index, on every executor (9.3 paragraph 7)."
  },
  {
   "id": "spec-03p:the-same-fault-from-cint-code",
   "edition": "SPEC-03P.1",
   "title": "10.3 The same fault from cint code",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#the-same-fault-from-cint-code",
   "internal": 0,
   "content": "### 10.3 The same fault from cint code\n\nA dispatch issued from cint code is checked and faults as the same dispatch issued by a host (7.1 paragraph 3). This script runs the kernel of `advance.ci` twice in one run, the second time with `dt` equal to 2, as `host.c` does in 7.3.\n\n```cint advance_run.ci\nkernel advance[n](in I64[n] pos, in I64[n] vel, in I64 dt, out I64[n] next) over [i: n] {\n    next[i] = pos[i] + vel[i] * dt;\n}\n\nvoid run() {\n    I64[4] pos = [0, 1, 2, 3];\n    I64[4] vel = [16, 16, 4611686018427387904, 16];\n    I64[4] next = [0, 0, 0, 0];\n    advance(pos, vel, 1, next);\n    \"next: {next[0]} {next[1]} {next[2]} {next[3]}\\n\";\n    advance(pos, vel, 2, next);\n    \"not reached\\n\";\n}\n\nrun();\n```\n\n```text\nnext: 16 17 4611686018427387906 19\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> advance_run.ci:2:31\n...\n   = operation: mul.checked.i64\n   = operand-count: 2\n   = operand: I64 4611686018427387904\n   = operand: I64 2\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n...\n   = address: advance_run.advance, dispatch 1, phase 1, work-item 2, step 3\n...\n```\n\n1. The operation, the operands and the limit are those that `host.c` reports in 7.3: the fault record does not depend on which side issued the dispatch. The address differs in the dispatch number. Here both dispatches belong to one run of the script, so the one that faults is number 1; in 7.3 each call of a wrapper is an entry of its own, and its one dispatch is number 0. Phase 1 is the work-item phase; the entry checks of 7.1 paragraph 11 fault in phase 0.\n2. `cint run` prints the fault in the form that SPEC-06P.1 describes, with the source line, the revision identity and the call stack among the lines this example skips."
  },
  {
   "id": "spec-03p:future-directions",
   "edition": "SPEC-03P.1",
   "title": "11 Future directions",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#future-directions",
   "internal": 0,
   "content": "## 11 Future directions\n\nThis clause describes interfaces that cint 0.2.0 does not provide. It states no requirement."
  },
  {
   "id": "spec-03p:future-directions-p1",
   "edition": "SPEC-03P.1",
   "title": "11 Future directions (part 2)",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#future-directions",
   "internal": 0,
   "content": "1. **Host functions with declared effects.** A host program supplies functions that cint code declares with `extern` and calls, each with one effect class: `pure`, whose result depends only on its arguments; `observe`, whose results a recording holds and replay returns without calling the host; or `unrestricted`, at which replay stops. A function's class is the greatest of its own and its callees', as the effect field of the reflection table (7.4) is for an export that prints.\n2. **Fortran.** `cint build` writes, for each module, a Fortran module of `bind(C)` interfaces and a C shim that implements them, so that a Fortran program calls exports with its own arrays and never handles a view.\n3. **The migration assistant.** A set of commands reads a floating-point routine, measures the ranges its variables take on stated inputs, proposes a fixed-point format for each, writes a cint skeleton, and compares the port with the original in a report.\n4. **Input hazard checks.** With `check_inputs`, the Python package hashes each borrowed input at entry and again before each publication of a dispatch that reads it, and faults the entry when the two differ; while recording, it snapshots borrowed inputs instead. The check detects a change by a foreign writer that persists to the second hash and no other, so the limit of 8.4 paragraph 3 remains.\n5. **A generated module header.** `cint build --lib` writes, beside the library, a C header that declares each wrapper with its export's signature and effect class in a comment, the module descriptor and `cint_library_desc`, so that a host program includes it in place of the declarations it writes in 7.3 and 10.1.\n6. **Further loading and calling forms.** Loading a module from Python on the interpreter, an in-place form of a kernel call, and libraries built by `cint build --lib` that hold the checkpoint, recording and replay functions are ca"
  },
  {
   "id": "spec-03p:annex-a-informative-clause-identifiers-stated-in",
   "edition": "SPEC-03P.1",
   "title": "Annex A (informative) Clause identifiers stated in other editions",
   "clauses": "",
   "url": "/specifications/spec-03p/1/#annex-a-informative-clause-identifiers-stated-in-other-editions",
   "internal": 0,
   "content": "## Annex A (informative) Clause identifiers stated in other editions\n\nA tool message, or an earlier edition, may cite a clause identifier of this document's series whose rule a 0.2.0 edition states elsewhere. Each such identifier is listed here with the edition and section that state it, or, where no 0.2.0 edition states its rule, with the section that describes the topic."
  },
  {
   "id": "spec-03p:annex-a-informative-clause-identifiers-stated-in-p1",
   "edition": "SPEC-03P.1",
   "title": "Annex A (informative) Clause identifiers stated in other editions (part 2)",
   "clauses": "H-14a M-12 M-13 M-14 M-14a M-15 M-16 M-17 M-17a M-18 M-19 M-20",
   "url": "/specifications/spec-03p/1/#annex-a-informative-clause-identifiers-stated-in-other-editions",
   "internal": 0,
   "content": "| Identifier | Stated in |\n|---|---|\n| <a id=\"H-14a\"></a>H-14a | [SPEC-01P.2 8.2](SPEC-01P.2-ENCODINGS.md#H-14a) |\n| <a id=\"M-12\"></a>M-12 | [SPEC-04P.2 6.14.4](SPEC-04P.2-LANGUAGE.md#M-12) |\n| <a id=\"M-13\"></a>M-13 | [SPEC-04P.2 6.14.1](SPEC-04P.2-LANGUAGE.md#M-13) |\n| <a id=\"M-14\"></a>M-14 | [SPEC-04P.2 6.14.2](SPEC-04P.2-LANGUAGE.md#M-14) |\n| <a id=\"M-14a\"></a>M-14a | [SPEC-04P.2 6.14.2](SPEC-04P.2-LANGUAGE.md#M-14a) |\n| <a id=\"M-15\"></a>M-15 | [SPEC-04P.2 6.14.3](SPEC-04P.2-LANGUAGE.md#M-15) |\n| <a id=\"M-16\"></a>M-16 | [SPEC-04P.2 6.14.3](SPEC-04P.2-LANGUAGE.md#M-16) |\n| <a id=\"M-17\"></a>M-17 | [SPEC-04P.2 6.14.4](SPEC-04P.2-LANGUAGE.md#M-17) |\n| <a id=\"M-17a\"></a>M-17a | [SPEC-04P.2 6.14.3](SPEC-04P.2-LANGUAGE.md#M-17a) |\n| <a id=\"M-18\"></a>M-18 | [SPEC-04P.2 6.14.3](SPEC-04P.2-LANGUAGE.md#M-18) |\n| <a id=\"M-19\"></a>M-19 | [SPEC-04P.2 6.14.2](SPEC-04P.2-LANGUAGE.md#M-19) |\n| <a id=\"M-20\"></a>M-20 | [SPEC-04P.2 6.14.1](SPEC-04P.2-LANGUAGE.md#M-20) |\n| <a id=\"M-20a\"></a>M-20a | [SPEC-04P.2 6.14.1](SPEC-04P.2-LANGUAGE.md#M-20a) |\n| <a id=\"M-20b\"></a>M-20b | [SPEC-04P.2 6.14.1](SPEC-04P.2-LANGUAGE.md#M-20b) |\n| <a id=\"M-21\"></a>M-21 | [SPEC-04P.2 6.12.4](SPEC-04P.2-LANGUAGE.md#M-21) |\n| <a id=\"M-22\"></a>M-22 | [SPEC-04P.2 6.12.4](SPEC-04P.2-LANGUAGE.md#M-22) |\n| <a id=\"M-23\"></a>M-23 | [SPEC-04P.2 6.14.5](SPEC-04P.2-LANGUAGE.md#M-23) |\n| <a id=\"M-24\"></a>M-24 | [SPEC-04P.2 6.12.1](SPEC-04P.2-LANGUAGE.md#M-24) |\n| <a id=\"M-24a\"></a>M-24a | [SPEC-04P.2 6.12.4](SPEC-04P.2-LANGUAGE.md#M-24a) |\n| <a id=\"M-25\"></a>M-25 | [SPEC-04P.2 6.12.4](SPEC-04P.2-LANGUAGE.md#M-25) |\n| <a id=\"M-26\"></a>M-26 | [SPEC-04P.2 6.13.2](SPEC-04P.2-LANGUAGE.md#M-26) |\n| <a id=\"M-27\"></a>M-27 | [SPEC-04P.2 6.12.2](SPEC-04P.2-LANGUAGE.md#M-27) |\n| <a id=\"X-9\"></a>X-9 | [Not a rule of this edition; SPEC-03P.1 8.5](SPEC-03P.1-HOST-INTERFACE.md#values-that-cross) |"
  },
  {
   "id": "spec-04p:spec-04p-2",
   "edition": "SPEC-04P.2",
   "title": "SPEC-04P.2",
   "clauses": "",
   "url": "/specifications/spec-04p/2/",
   "internal": 0,
   "content": "# SPEC-04P.2: The cint language\n\nSPEC-04P.2, edition 2 of the cint language specification, cint v0.2.0, 2026-10-11."
  },
  {
   "id": "spec-04p:foreword",
   "edition": "SPEC-04P.2",
   "title": "Foreword",
   "clauses": "IM-30 LS-17",
   "url": "/specifications/spec-04p/2/#foreword",
   "internal": 0,
   "content": "## Foreword\n\nThis document specifies the cint programming language. cint 0.2.0 implements this edition, except for the constructs that its tools refuse (4, paragraph 4).\n\nEach rule ends with one or more clause identifiers in brackets, such as [LS-17] or [IM-30]. An identifier names one rule across editions: a rule keeps its identifier when its text moves to another section or another document, and an identifier is never reused. Section numbers belong to this edition only.\n\nThis edition replaces SPEC-04P.1, \"Language surface\". It also takes over the rules of SPEC-01P.1 that define types, operators, faults and fuel; SPEC-01P.2 keeps the byte encodings. Annex F lists every rule that moved and where it is now."
  },
  {
   "id": "spec-04p:introduction",
   "edition": "SPEC-04P.2",
   "title": "Introduction",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#introduction",
   "internal": 0,
   "content": "## Introduction\n\ncint is a C-family programming language for programs whose results must be exact and the same everywhere. Every value has a declared type: an integer type, a fixed-point type whose values are scaled integers, `Bool`, an error set, or an aggregate of these. Every plain arithmetic operator is checked: it gives the exact mathematical result, and when that result does not fit its type, the program stops with a fault that names the operation, its operands and the exact result. Wrapping and saturating arithmetic exist, but only through operators, conversions and named operations spelled for them.\n\nA cint program has one meaning. Given the same semantic inputs (3.24), every conforming implementation (4) that runs the program writes the same output bytes and consumes the same count of fuel (3.21). When the program faults, every such implementation produces a fault record (3.11) equal in every field except `revision` and `source-map`, which identify the program and not the outcome (8.2). This holds whether the program is compiled to C, run by the interpreter `cint-interp` (3.19), or has its kernels (3.28) dispatched (3.29) to a GPU. An implementation may refuse a program that it cannot run exactly (4, paragraphs 3 and 4).\n\nThe first program below sums the squares of 1 to 10. Top-level statements run in order, and a string on its own prints itself, with each `{...}` replaced by the value of the expression inside it:\n\n```cint squares.ci\nI64 total = 0;\nfor i in 1..=10 {\n    total += i * i;\n}\n\"sum of squares: {total}\\n\";\n```\n\nprints\n\n```text\nsum of squares: 385\n```\n\nThe same loop in `I8`, whose range is -128 to 127, cannot reach the end:\n\n```cint squares8.ci\nI8 total = 0;\nfor i in 1..=10 {\n    I8 k = i as I8;\n    total += k * k;\n    \"after {k}: {total}\\n\";\n}\n```"
  },
  {
   "id": "spec-04p:introduction-p1",
   "edition": "SPEC-04P.2",
   "title": "Introduction (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#introduction",
   "internal": 0,
   "content": "```text\nafter 1: 1\nafter 2: 5\nafter 3: 14\nafter 4: 30\nafter 5: 55\nafter 6: 91\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> squares8.ci:4:11\n   |\n 4 |     total += k * k;\n   |           ^ add.checked.i8\n   |\n   = operation: add.checked.i8\n   = operand-count: 2\n   = operand: I8 91\n   = operand: I8 49\n   = exact:   140\n   = limit:   I8 127\n   ...\n```\n\nThe seventh addition would give 140, so the program stops there. The six lines it wrote before the fault stay written, and the report names the operation, both operands, the exact result and the bound it crossed. The program never continues with a wrapped value."
  },
  {
   "id": "spec-04p:how-this-document-is-organized",
   "edition": "SPEC-04P.2",
   "title": "How this document is organized",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#how-this-document-is-organized",
   "internal": 0,
   "content": "### How this document is organized\n\nClauses 1 to 4 state what the document covers, the documents it relies on, its terms and what conformance means. Clause 5 describes the environment a program is translated and run in: modules and scripts, diagnostics, faults, fuel, call depth and the limits of an implementation. Clause 6 defines the language, from the concepts it rests on through types, lexical elements, expressions, declarations and statements, to arrays, views, kernels and memory. Clause 7 defines the built-in operations. Clause 8 explains how to find out why a program did what it did: the fault record, the agreement of every implementation on every outcome, golden outputs and tests, checkpoints and replay and the debug tools. Annex A gives the complete grammar. The other annexes are informative, except B.3, which states the form of operation identifiers: the diagnostic and fault codes, how cint treats each kind of behavior that C leaves undefined, a guide for C and Python programmers, the open questions and an index of clause identifiers.\n\nEach subclause of clauses 6, 7 and 8 opens with a short summary and then has some of these parts:\n\n- The **summary**: informative. It introduces the subclause and states no rule; where it and a rule differ, the rule governs.\n- **Syntax**: the grammar of the construct, in the notation of 6.1.\n- **Constraints**: rules checked when the program is translated. A program that breaks a constraint is rejected with a diagnostic and does not run.\n- **Semantics**: what the construct means when the program runs.\n- **Faults**: the faults the construct can raise, and what each fault record holds.\n- **Examples** and **Notes**: informative. A note or example may cite the identifiers of the rules it illustrates and adds no rule of its own."
  },
  {
   "id": "spec-04p:how-this-document-is-organized-p1",
   "edition": "SPEC-04P.2",
   "title": "How this document is organized (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#how-this-document-is-organized",
   "internal": 0,
   "content": "Every example in this document is a complete program or a complete part of one, and its output is shown as cint 0.2.0 prints it, except where a value is replaced by a placeholder in angle brackets, which the text explains. Where a tool of that release refuses an example (4, paragraph 4), the output shown is the reference's. A line `...` in shown output stands for lines left out."
  },
  {
   "id": "spec-04p:scope",
   "edition": "SPEC-04P.2",
   "title": "1 Scope",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#scope",
   "internal": 0,
   "content": "## 1 Scope\n\n1. This document specifies the form and meaning of programs written in the cint language, profile `cint-core-1`. It specifies:\n   - the representation of source text;\n   - types, values and the operators on them;\n   - declarations, statements, modules and tests;\n   - arrays, views and kernels;\n   - arenas, pools and handles;\n   - the faults a program can raise and the content of the record each fault produces;\n   - the fuel a program consumes and the bounds on call depth and local storage;\n   - the diagnostics an implementation reports when it rejects a program.\n2. This document does not specify:\n   - the byte encodings of fault records, program state, checkpoints, recordings and identities, which SPEC-01P.2 specifies, except the canonical form of a handle (6.14.4) and the storage of a `Bool` (6.3.3), which this document states;\n   - how an executor carries out a kernel dispatch so that it agrees with clause 6.13, which SPEC-02P.1 specifies;\n   - the C and Python interfaces through which a host program calls cint code, which SPEC-03P.1 specifies;\n   - the commands of the cint tools, which SPEC-06P.1 specifies; where this document states what `cint run` does, it does so to fix the semantic inputs and the output of its examples;\n   - the intermediate representation, the C that the compiler emits and the conformance suite, which SPEC-09P.1 specifies;\n   - the behavior of code outside the program that the program reaches through the host interface."
  },
  {
   "id": "spec-04p:normative-references",
   "edition": "SPEC-04P.2",
   "title": "2 Normative references",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#normative-references",
   "internal": 0,
   "content": "## 2 Normative references\n\nThe following documents are referred to in the text in such a way that some or all of their content constitutes requirements of this document. For dated references, only the edition cited applies.\n\n- The Unicode Consortium. *The Unicode Standard*, Version 17.0.0, 2025. Used for the terms Unicode scalar value and code point, and for the property `Default_Ignorable_Code_Point`.\n- The Unicode Consortium. *Unicode Standard Annex #9: Unicode Bidirectional Algorithm*, revision 51, 2025-08-13, the revision of Unicode 17.0.0. Used for the directional formatting characters of 6.4.1.\n- F. Yergeau. *UTF-8, a transformation format of ISO 10646*. RFC 3629 (STD 63), 2003-11. Used for the encoding of source text (6.4.1).\n- SPEC-01P.2, *Canonical encodings and identity*, edition 2. Used for the encodings of fault records, state, checkpoints and identities, for the value of each fault code in an encoded record, and for the terms of 3.37 to 3.43 (3.31, 5.2.3, 8.1, 8.2, 8.4).\n- SPEC-02P.1, *Kernels and executors*, edition 1. Used for the full procedure of the overlap tests of 6.12.5 and 6.13.2, and for what an executor shall do to give a kernel dispatch its meaning (6.13).\n- SPEC-03P.1, *The host interface: C and Python*, edition 1. Used for the host program that creates contexts and runs entries, for the layout of values at the C interface, and for the term of 3.44 (5.2.1, 6.3, 6.15.2, 8.4).\n- SPEC-06P.1, *The cint tools*, edition 1. Used for the command language of a workbench session, the exit statuses and options of each tool, and the allowances each tool gives (5.1.2, 5.2, 6.15, 8.5).\n- SPEC-09P.1, *Toolchain and conformance*, edition 1. Used for the conformance suite, the refusals of the cint tools (4, paragraph 4) and the SIR (8.2, 8.5)."
  },
  {
   "id": "spec-04p:normative-references-p1",
   "edition": "SPEC-04P.2",
   "title": "2 Normative references (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#normative-references",
   "internal": 0,
   "content": "Clauses 5 to 7 depend on SPEC-02P.1 for the overlap tests of 6.12.5 and 6.13.2. Their other citations of these editions point to encodings, interfaces and tool options that do not change the outcome of a program."
  },
  {
   "id": "spec-04p:terms-definitions-and-symbols",
   "edition": "SPEC-04P.2",
   "title": "3 Terms, definitions and symbols",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "## 3 Terms, definitions and symbols\n\nFor the purposes of this document, the following terms and definitions apply. Other terms are defined where they first appear, in italic type. Terms explicitly defined in this document are not to be presumed to refer implicitly to similar terms defined elsewhere.\n\n<a id=\"term-z\"></a>**3.1 Z**: the set of mathematical integers, of unbounded size.\n\n<a id=\"term-value\"></a>**3.2 value**: what an object (3.33) holds or an expression produces, together with its type. A value of an integer type is an element of Z in the type's range, and a value of a fixed-point type is a multiple of 2^-f in its range. The other values are those of `Bool`, of error sets and of handle types, and the arrays and structs built from them (6.3).\n\n<a id=\"term-type\"></a>**3.3 type**: the set of values an object (3.33) may hold and the operations defined on them. An integer type has a *range* from its minimum `MIN(T)` to its maximum `MAX(T)`.\n\n<a id=\"term-exact-result\"></a>**3.4 exact result**: the result of an arithmetic operation computed in Z, before any check against the range of the result type. For an operation that rounds, the exact result is the value after its one rounding, before the range check (6.7.15).\n\n<a id=\"term-checked-operator\"></a>**3.5 checked operator**: an operator that gives the exact result when it is in the range of the result type and otherwise raises a fault. Every plain operator is checked: an arithmetic operator spelled without a `%` or `|` suffix, such as `+`, `/`, `%` or `<<`.\n\n<a id=\"term-wrapping-operator\"></a>**3.6 wrapping operator**: an operator spelled with a `%` suffix after an arithmetic operator (`+%`, `-%`, `*%`, `<<%` and unary `-%`), whose result is the exact result reduced modulo 2 to the power of the type's width into the type's range. A wrapping operator does not fault on overflow."
  },
  {
   "id": "spec-04p:terms-definitions-and-symbols-p1",
   "edition": "SPEC-04P.2",
   "title": "3 Terms, definitions and symbols (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "<a id=\"term-saturating-operator\"></a>**3.7 saturating operator**: an operator spelled with a `|` suffix after an arithmetic operator (`+|`, `-|`, `*|`), whose result is `sat(T, v)` (3.45) for the exact result `v`. A saturating operator does not fault on overflow.\n\n<a id=\"term-result-form\"></a>**3.8 result form**: a built-in operation, such as `add_result`, that returns an error union (3.13) instead of raising the fault its checked operator would raise.\n\n<a id=\"term-fault\"></a>**3.9 fault**: the stop of a run at an operation that cannot give a correct result, such as an overflow, a division by zero or an index outside an array (5.2.3).\n\n<a id=\"term-fault-code\"></a>**3.10 fault code**: the name of the kind of a fault, such as `E_OVERFLOW`.\n\n<a id=\"term-fault-record\"></a>**3.11 fault record**: the description of a fault that an implementation produces: its fault code, the operation, the operands, the exact result, the bound that was crossed, the source position, and the identity of the program.\n\n<a id=\"term-operation-identifier\"></a>**3.12 operation identifier**: the name of an operation in a fault record, such as `add.checked.i64`.\n\n<a id=\"term-error-union\"></a><a id=\"term-error-set\"></a><a id=\"term-error\"></a>**3.13 error, error set, error union**: an *error set* is a type declared with `error`, whose values are named errors (6.3.7). An *error* is a value of an error set, returned by a function to report an expected failure; unlike a fault, an error is handled by the program, with `try` or `catch`. An *error union* `E!T` is a function result that holds a `T` or a value of the error set `E` (6.3.7).\n\n<a id=\"term-translation\"></a>**3.14 translation**: everything an implementation does with a program before it runs: reading the source text, checking the constraints, and compiling or preparing the program."
  },
  {
   "id": "spec-04p:terms-definitions-and-symbols-p2",
   "edition": "SPEC-04P.2",
   "title": "3 Terms, definitions and symbols (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "<a id=\"term-diagnostic\"></a>**3.15 diagnostic**: a message an implementation reports during translation when a program breaks a constraint. A diagnostic has a code, the letter `C` followed by four digits, and a source position.\n\n<a id=\"term-refusal\"></a>**3.16 refusal**: the report by an implementation that it will not run a valid program, or a kernel dispatch, because it cannot execute it exactly. A refused program is not rejected: it stays conforming. A refusal is reported during translation when the need is known then, and otherwise when an entry or a kernel dispatch begins, before any of its work runs. A refused program is never run with a different meaning.\n\n<a id=\"term-implementation\"></a>**3.17 implementation**: a set of programs that translates and runs cint programs.\n\n<a id=\"term-the-reference\"></a>**3.18 the reference**: the implementation `cint_ref`, written to follow this document directly, whose results are the expected results of the conformance suite.\n\n<a id=\"term-executor\"></a>**3.19 executor**: the part of an implementation that runs a translated program (8.2, Note 13).\n\n<a id=\"term-entry\"></a>**3.20 entry**: one run of a program from its entry point: the top-level statements of a script, the function `main`, a `test` block or an exported function called from a host program.\n\n<a id=\"term-fuel\"></a>**3.21 fuel**: a count of steps (calls, loop iterations, reductions and kernel dispatches) that an entry is charged as it runs. An entry with a fuel allowance of `B` faults at the charge that would take its consumed fuel above `B`.\n\n<a id=\"term-call-depth\"></a>**3.22 call depth**: the number of user-function calls active at one time in an entry.\n\n<a id=\"term-frame-arena\"></a>**3.23 frame arena**: the storage that holds the local arrays of active function calls, counted in elements."
  },
  {
   "id": "spec-04p:terms-definitions-and-symbols-p3",
   "edition": "SPEC-04P.2",
   "title": "3 Terms, definitions and symbols (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "<a id=\"term-semantic-input\"></a>**3.24 semantic input**: a value that decides the outcome of an entry: the program, its input values, the effects the host supplied to it (8.2, paragraph 2), the fuel allowance, the call-depth limit and the frame-arena capacity.\n\n<a id=\"term-module\"></a>**3.25 module**: one source file. Scripts and importable modules are defined in 5.1.2.\n\n<a id=\"term-array\"></a>**3.26 array**: a fixed number of elements of one type, stored in order.\n\n<a id=\"term-view\"></a>**3.27 view**: a typed, shaped window onto array storage, given by its element type, its rank, an extent and a stride for each dimension, and whether it may be written (6.3.5, 6.12.4).\n\n<a id=\"term-kernel\"></a>**3.28 kernel**: a function that runs once for each point of an iteration space, writing its results to output views that only that point may write.\n\n<a id=\"term-dispatch\"></a>**3.29 dispatch**: one call of a kernel over an iteration space. Each point of the space is a *work-item*.\n\n<a id=\"term-handle\"></a><a id=\"term-pool\"></a><a id=\"term-arena\"></a>**3.30 arena, pool, handle**: an *arena* is a region of storage with a fixed capacity from which objects are taken and released together; a *pool* is a fixed set of slots that are taken and released one at a time; a *handle* is a checked reference to an object in an arena or a pool.\n\n<a id=\"term-revision\"></a>**3.31 revision**: the identity of a program, a digest computed as SPEC-01P.2 specifies. Source positions are not part of it (8.1), and it depends on the runtime contract version (3.43, 8.4). A fault record names the revision its source positions refer to.\n\n<a id=\"term-golden\"></a>**3.32 golden**: an output, or the text of a whole outcome (8.3), saved from a run whose output was checked once, kept with the program, and compared byte for byte with the output of each later run of the program on the same inputs (8.3)."
  },
  {
   "id": "spec-04p:terms-definitions-and-symbols-p4",
   "edition": "SPEC-04P.2",
   "title": "3 Terms, definitions and symbols (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "<a id=\"term-object\"></a>**3.33 object**: storage that holds a value: a variable, an element of an array, or a field of a struct (6.2.2).\n\n<a id=\"term-size-parameter\"></a>**3.34 size parameter**: a name, bound at each call or dispatch, for an extent of an array or view argument; inside the body it is a read-only `I64` (6.9.5, 6.13.2).\n\n<a id=\"term-sequential-code\"></a>**3.35 sequential code**: the code of a program outside kernel bodies (6.13).\n\n<a id=\"term-storage-integer\"></a><a id=\"term-raw-value\"></a>**3.36 raw value, storage integer**: the integer `r` of the storage type of a fixed-point type that stands for the value `r / 2^f` (6.3.2).\n\n<a id=\"term-boundary\"></a>**3.37 boundary**: as defined in SPEC-01P.2, 3.16. A boundary is a point of a run at which the state of its context (3.44) is defined and its state hash is taken, such as the end of an entry (3.20) that ran.\n\n<a id=\"term-case\"></a>**3.38 case**: as defined in SPEC-01P.2, 3.15. A case is a recording (3.40) that also holds the source text of every module of its program, so that the run can be replayed on another machine with no other file.\n\n<a id=\"term-checkpoint\"></a>**3.39 checkpoint**: as defined in SPEC-01P.2, 3.11. A checkpoint is the canonical bytes of the state of a context (3.44), taken between entries, from which the context can be restored.\n\n<a id=\"term-recording\"></a>**3.40 recording**: as defined in SPEC-01P.2, 3.14. A recording is a file that holds the identity and code of a program, a checkpoint (3.39) taken when recording began, and the entries and other events that followed, in order.\n\n<a id=\"term-sir-text\"></a>**3.41 SIR text**: as defined in SPEC-01P.2, 3.19. SIR text is the canonical text form of the intermediate representation of one module."
  },
  {
   "id": "spec-04p:terms-definitions-and-symbols-p5",
   "edition": "SPEC-04P.2",
   "title": "3 Terms, definitions and symbols (part 6)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "<a id=\"term-source-map\"></a>**3.42 source map**: as defined in SPEC-01P.2, 3.20. A source map lists each operation that can fault in every module of a program, with its ordinal, line, column and operation identifier (3.12).\n\n<a id=\"term-runtime-contract-version\"></a>**3.43 runtime contract version**: as defined in SPEC-01P.2, 3.18. The runtime contract version names the interface between compiled code and the runtime library: `cint-rt-3` in cint 0.2.0.\n\n<a id=\"term-context\"></a>**3.44 context**: as defined in SPEC-03P.1, 3.4. A context is one instance of a program's state, held by a host program, in which entries (3.20) run one at a time."
  },
  {
   "id": "spec-04p:symbols",
   "edition": "SPEC-04P.2",
   "title": "3.45 Symbols",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#symbols",
   "internal": 0,
   "content": "### 3.45 Symbols\n\n| Symbol | Meaning |\n|---|---|\n| `MIN(T)`, `MAX(T)` | The least and greatest values of the integer type `T`. |\n| `w` | The width of an integer type in bits. |\n| `in(T, v)` | True when `MIN(T) <= v <= MAX(T)`. |\n| `wrap(T, v)` | The value of `T` congruent to `v` modulo 2^`w`. |\n| `sat(T, v)` | `MIN(T)` if `v < MIN(T)`, `MAX(T)` if `v > MAX(T)` and `v` otherwise. |\n| `floor(x)` | The greatest integer not greater than the rational `x`. |\n| `ceil(x)` | The least integer not less than the rational `x`. |\n| `log2(x)` | The base-2 logarithm of the positive rational `x`. |\n| `min(a, b)`, `max(a, b)` | The lesser and the greater of `a` and `b`. |\n| `clamp(v, l, h)` | For `l <= h`, `min(max(v, l), h)`. |\n| `2^k` | 2 raised to the power `k`. |\n| `\\|a\\|` | The absolute value of `a`. |"
  },
  {
   "id": "spec-04p:conformance",
   "edition": "SPEC-04P.2",
   "title": "4 Conformance",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#conformance",
   "internal": 0,
   "content": "## 4 Conformance"
  },
  {
   "id": "spec-04p:conformance-p1",
   "edition": "SPEC-04P.2",
   "title": "4 Conformance (part 2)",
   "clauses": "CONF-14 IM-129 IM-7 LS-272 LS-273 LS-274 LS-275",
   "url": "/specifications/spec-04p/2/#conformance",
   "internal": 0,
   "content": "1. In this document, \"shall\" states a requirement on a program or on an implementation, and \"shall not\" a prohibition. \"May\" states a permission. A rule on programs is a constraint, checked during translation, unless it says that a run that breaks it faults.\n2. <a id=\"LS-272\"></a>A *conforming program* is one that satisfies every constraint of this document. A conforming program has exactly one outcome for each set of semantic inputs: it ends normally after writing specified output bytes, or it stops with one fault, described by one fault record, after writing a specified prefix of its output [LS-272].\n3. A *conforming implementation* shall:\n   - reject every program that breaks a constraint, with a diagnostic as described in 5.1.3, and produce no executable code for it;\n   - for every conforming program that it runs, produce the outcome this document specifies: the same output bytes, the same fuel consumed and a fault record equal in every field except `revision` and `source-map` to that of every other conforming implementation (8.2, paragraph 3);\n   - <a id=\"IM-129\"></a>refuse a conforming program, or a kernel dispatch, that it cannot execute exactly: during translation when the need is known then, and otherwise with the fault `E_UNSUPPORTED` when the entry or the dispatch begins, before any of its work runs (5.2.5) [IM-129].\n4. An implementation may refuse a construct that it does not implement, with a diagnostic whose code begins with `C9`. Such a refusal is not a rejection: the program stays conforming, and on an implementation that runs it, its outcome is the one this document specifies [SPEC-09P.1 CONF-14]. The code C9102 has two uses: it diagnoses a constraint that names no code of its own, and, since it begins with `C9`, it can also report a refusal. The reference tells the two uses apart. A program that the reference rejects breaks a constraint and is not co"
  },
  {
   "id": "spec-04p:environment",
   "edition": "SPEC-04P.2",
   "title": "5 Environment",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#environment",
   "internal": 0,
   "content": "## 5 Environment\n\nThis clause describes the setting in which a program is translated and run. Translation (5.1) turns source files into a program or rejects them with diagnostics. Execution (5.2) runs the program as entries into a context, writes its output, stops it at a fault, and bounds it by fuel, call depth and frame storage. Implementation limits (5.3) say how large a program every implementation accepts."
  },
  {
   "id": "spec-04p:source-files-and-modules",
   "edition": "SPEC-04P.2",
   "title": "5.1.1 Source files and modules",
   "clauses": "LS-3 LS-8",
   "url": "/specifications/spec-04p/2/#source-files-and-modules",
   "internal": 0,
   "content": "#### 5.1.1 Source files and modules\n\nA cint program is written in source files. The contents of a module decide whether it is a script, which runs, or an importable module, which other modules use.\n\n**Syntax**\n\n```ebnf\nmodule       = [ profile_decl ] { import_decl } { top_item } ;\nprofile_decl = \"profile\" STRING \";\" ;\n```\n\n`import_decl` and `top_item` are defined in 6.15.1.\n\n**Constraints**\n\n1. <a id=\"LS-3\"></a>A source file has a name that ends in `.ci`, and its contents are source text as 6.4.1 describes. A file whose name ends in `.cint` is not a source file of this language and is rejected with C1001, reported at line 1, at the first character. This edition gives no diagnostic for other names, which are not source files by the first sentence [LS-3].\n2. <a id=\"LS-8\"></a>A profile declaration, when present, shall be the first item of the file; anywhere else it is a syntax error (C1050). It shall name `cint-core-1`, the profile this document defines; a file whose declaration names any other profile is refused (3.16) [LS-8].\n\n**Semantics**\n\n3. Each source file is one module [LS-3]. A file without a profile declaration is written in `cint-core-1` [LS-8].\n\n**Examples**\n\n4. A profile declaration that names the profile changes nothing:\n\n```cint profiled.ci\nprofile \"cint-core-1\";\n\"profile checked\\n\";\n```\n\n```text\nprofile checked\n```"
  },
  {
   "id": "spec-04p:scripts-and-programs",
   "edition": "SPEC-04P.2",
   "title": "5.1.2 Scripts and programs",
   "clauses": "LS-219 LS-220 LS-221 LS-312",
   "url": "/specifications/spec-04p/2/#scripts-and-programs",
   "internal": 0,
   "content": "#### 5.1.2 Scripts and programs\n\nA program starts from one module, its root. The root is either a script, whose top-level statements run in source order, or a module that defines a function `main`. A module with only declarations is an importable module: it has no entry of its own and is used through `import`.\n\n**Constraints**\n\n1. <a id=\"LS-220\"></a>A script, a module with at least one top-level statement (paragraph 5), cannot be imported (C3010) [LS-220].\n2. <a id=\"LS-221\"></a>A program that is not a script may define its entry as `void main()` or as `E!void main()` for an error set `E`. A module that has both top-level statements and `main` is rejected with C3011, at the name `main` [LS-221].\n3. <a id=\"LS-219\"></a>A variable declared at the top level of a script is a local of the script's entry. It is visible from its declaration to the end of the script, and never inside a function, kernel or test: naming it there is C3004 [LS-219].\n4. <a id=\"LS-312\"></a>The diagnostics whose cause depends on whether a module is a script (C3004, C3010, C3011, and C6004 for a module-level initializer that is not constant, 6.9.3) carry a note. The note names the first top-level statement, in source order, that makes the module a script, or says that the module has none. The note changes neither the code nor the position of the diagnostic [LS-312].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:scripts-and-programs-p1",
   "edition": "SPEC-04P.2",
   "title": "5.1.2 Scripts and programs (part 2)",
   "clauses": "LS-218 LS-219 LS-220 LS-221 LS-222 LS-223 LS-224 LS-312",
   "url": "/specifications/spec-04p/2/#scripts-and-programs",
   "internal": 0,
   "content": "5. <a id=\"LS-218\"></a>A *script* is a module that contains at least one top-level statement [LS-218]. A `test` block is not a statement and does not make a module a script [LS-312].\n6. An *importable module* contains only imports, declarations, tests and `static_assert` [LS-220].\n7. When a script runs, its top-level statements run in source order, as one entry (5.2.1) [LS-218].\n8. In a script, the declarations of structs, error sets, arenas, pools, functions, kernels and constants are visible throughout the module, whatever their order. An arena or pool is created with the context, before the first statement runs [LS-219].\n9. A program with `main` runs `main` as its entry. When `main` has the result type `E!void` and returns an error, the entry ends with that error as its result (5.2.1) [LS-221].\n10. <a id=\"LS-222\"></a>There is one meaning for every way a program runs. A script run by `cint run`, a program with `main`, and the same statements entered in a `cint workbench` session have the same types, the same arithmetic and the same faults, whichever executor (3.19) runs them, except that a variable declared at a session prompt is a module-level variable (paragraph 12), where in a script it is a local of the entry (paragraph 3) [LS-222].\n11. <a id=\"LS-223\"></a>What is entered in a `cint workbench` session, other than a command, is `cint-core-1` source. The session's own commands, such as `:checkpoint` and `:inspect`, form a separate command language that SPEC-06P.1 defines [LS-223].\n12. <a id=\"LS-224\"></a>In a `cint workbench` session, an entry that is a single expression prints its value and its type. A variable declared at the prompt is a module-level variable of the session's own module, so a function declared later can read it [LS-224].\n\n**Examples**\n\n13. A script may call a function declared after the call:"
  },
  {
   "id": "spec-04p:scripts-and-programs-p2",
   "edition": "SPEC-04P.2",
   "title": "5.1.2 Scripts and programs (part 3)",
   "clauses": "LS-218",
   "url": "/specifications/spec-04p/2/#scripts-and-programs",
   "internal": 0,
   "content": "```cint ordered.ci\n\"{twice(21)}\\n\";\nI64 twice(I64 v) {\n    return 2 * v;\n}\n```\n\n```text\n42\n```\n\n14. A top-level variable of a script is not visible inside a function. The note names the statement that makes the module a script:\n\n```cint balance.ci\nvoid show() {\n    \"{balance}\\n\";\n}\nshow();\nI64 balance = 5;\n```\n\n```text\nerror[C3004]: script local used in a function or test\n  --> balance.ci:2:7\n   |\n 2 |     \"{balance}\\n\";\n   |       ^\n   |\n   = note: this module is a script because of the top-level statement at balance.ci:4:1\n```\n\n15. The same program with `main`: `balance` is now a local of `main` and is passed as an argument:\n\n```cint balance_main.ci\nvoid show(I64 balance) {\n    \"{balance}\\n\";\n}\nvoid main() {\n    I64 balance = 5;\n    show(balance);\n}\n```\n\n```text\n5\n```\n\n16. A module cannot be a script and define `main`:\n\n```cint both.ci\nvoid main() {\n    \"in main\\n\";\n}\n\"top level\\n\";\n```\n\n```text\nerror[C3011]: script rule\n  --> both.ci:1:6\n   |\n 1 | void main() {\n   |      ^\n   |\n   = note: this module is a script because of the top-level statement at both.ci:4:1\n```\n\n17. A module whose every top-level item is a declaration is not a script, so its module-level variables need constant initializers. The note says so:\n\n```cint initial.ci\nI64 start() {\n    return 4;\n}\nI64 counter = start();\n```\n\n```text\nerror[C6004]: constant expression required\n  --> initial.ci:4:15\n   |\n 4 | I64 counter = start();\n   |               ^\n   |\n   = note: this file is a module, not a script, because every top-level item is a declaration (LS-218)\n```\n\n18. This example shows a `cint workbench` session. Each entry is source text; an expression prints its value and type, and a fault is reported in the layout of 5.1.3:"
  },
  {
   "id": "spec-04p:scripts-and-programs-p3",
   "edition": "SPEC-04P.2",
   "title": "5.1.2 Scripts and programs (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#scripts-and-programs",
   "internal": 0,
   "content": "```console\n$ cint workbench\ncint workbench   profile cint-core-1   backend cpu-sir-interp   new session\nci[1]> 7 / 2\n= 3 : I64\nci[2]> I64 x = 5;\nx = 5 : I64\nci[3]> I64 triple() { return x * 3; }\ntriple : () -> I64   revision session@r2\nci[4]> triple()\n= 15 : I64\nci[5]> I8 small = 100;\nsmall = 100 : I8\nci[6]> small + small\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> entry 6:1:7\n   |\n 1 | small + small\n   |       ^ add.checked.i8\n   |\n   = operation: add.checked.i8\n   = operand-count: 2\n   = operand: I8 100\n   = operand: I8 100\n   = exact:   200\n   = limit:   I8 127\n...\n```\n\n**Notes**\n\n19. `cint run` needs a program: a root module with neither top-level statements nor `main` has no entry, and `cint run` stops with a usage error. `cint test` runs the tests of such a module (6.15.3).\n20. SPEC-06P.1 describes the session in full, including how a redefinition in a live session makes a new revision of the session's module. A session names the revisions of its module `session@r1`, `session@r2` and so on and the `backend` field of its first line names the executor (3.19).\n21. A function that needs the value of a script variable takes it as a parameter (example 15)."
  },
  {
   "id": "spec-04p:diagnostics",
   "edition": "SPEC-04P.2",
   "title": "5.1.3 Diagnostics",
   "clauses": "LS-283",
   "url": "/specifications/spec-04p/2/#diagnostics",
   "internal": 0,
   "content": "#### 5.1.3 Diagnostics\n\nWhen a program breaks a constraint, the implementation rejects it with a diagnostic: a code, a position and a message. The code and the position belong to the language, so implementations that report a code for a program report the same first one (4, paragraph 4 and B.1 state where cint and the reference differ). A run-time fault (5.2.3) is reported in the same layout.\n\n**Semantics**\n\n1. <a id=\"LS-283\"></a>A diagnostic has a *code*, the letter `C` followed by four digits, and a *position*, the file, line and column (6.4.2) of the offending construct. The first digit of the code gives its category [LS-283]:\n\n| Codes | Category |\n|---|---|\n| C1xxx | Files, source text, tokens and syntax |\n| C2xxx | Types, conversions, constants and views |\n| C3xxx | Names, modules and tests |\n| C4xxx | Statements, control flow and names used as keywords |\n| C5xxx | Parameter modes and kernels |\n| C6xxx | Evaluation during translation |\n| C9xxx | Implementation limits and refusals (5.3; 4, paragraph 4) |\n\n   The subclause that defines each code states its position; Annex B lists every code with that subclause."
  },
  {
   "id": "spec-04p:diagnostics-p1",
   "edition": "SPEC-04P.2",
   "title": "5.1.3 Diagnostics (part 2)",
   "clauses": "LS-276 LS-277 LS-278 LS-282 LS-312",
   "url": "/specifications/spec-04p/2/#diagnostics",
   "internal": 0,
   "content": "2. <a id=\"LS-278\"></a>The position of a diagnostic is the first character of the offending construct. Where a construct can be read two ways, the subclause that defines the code names the token: for example, C2003 is reported at the literal, inside any parentheses and at the `-` of a negative literal; C3001 at the declared name; C6001 at the operator that faulted. A diagnostic that concerns a whole file is reported at line 1, at the first character [LS-278].\n3. <a id=\"LS-282\"></a>Translation finds errors in phases: first forming tokens from the source text, then parsing, then checking names, types and constant expressions. The first diagnostic reported is the least, in the order of line, then column, then code, among the errors of the earliest phase that finds any. An implementation may report further diagnostics after the first, in the same order, at most 100 for a module, followed by a count of the rest. The output is deterministic [LS-282].\n4. Only the code and the position are compared between implementations; the message and the notes are text for the reader [LS-312].\n5. <a id=\"LS-277\"></a>The text form has two severities: `error`, for a diagnostic, after which the program is rejected and nothing runs, and `fault`, for a run-time fault (5.2.3). `cint-core-1` defines no warnings: every construct is either valid or rejected [LS-277].\n6. <a id=\"LS-276\"></a>The text form of a diagnostic or a fault has this layout [LS-276]:\n\n```text\n<severity>[<code>]: <message>\n  --> <file>:<line>:<column>\n   |\nNN | <the source line, as written>\n   | <spaces><caret> <operation or note>\n   |\n   = <label>: <exact value>\n```"
  },
  {
   "id": "spec-04p:diagnostics-p2",
   "edition": "SPEC-04P.2",
   "title": "5.1.3 Diagnostics (part 3)",
   "clauses": "LS-279 LS-289 LS-290 LS-291 LS-292 LS-293 LS-294",
   "url": "/specifications/spec-04p/2/#diagnostics",
   "internal": 0,
   "content": "   The caret marks the position. A diagnostic may add `= note:` lines and one `= help:` line, and a tool may add ` in <function>` to the position line. For a fault, the `<label>` lines are the fields of the fault record (5.2.3, 8.1), followed by the lines that 8.1 lists as not part of the record.\n7. <a id=\"LS-279\"></a>When the source line contains tabs, the caret line reproduces them at the same places, so the caret stands under its character in any tab width (6.4.2, example 5) [LS-279].\n8. <a id=\"LS-289\"></a>The *machine form* of a diagnostic or a fault is one JSON object on one line. `cint --json` writes it in place of the text form. Keys are sorted by their UTF-8 bytes and the object holds no insignificant white space. A value of the program is written as an object with its type `t` and its exact decimal value `v`, both strings, such as `{\"t\":\"I64\",\"v\":\"9223372036854775807\"}` [LS-289]. The keys are:\n   - a diagnostic has the keys `code`, `column`, `file`, `line`, `message`, `schema` (the string `CINT-DIAG-1`) and `severity`;\n   - a fault has the keys `schema` (the string `CINT-FAULT-1`) and `severity`, the fields of the fault record (`code`, `operation`, `operands`, `exact`, `limit`, `file`, `line`, `column`, `revision`, `source_map`, `address` and `stack`), equal to those of the record (8.1), and the key `noncanonical`, an object that holds what is not part of the record, such as `fuel_consumed`. The `state` line of the text form (8.1) has no key [LS-289].\n   - <a id=\"LS-290\"></a>For a fault in a kernel, `address` is an object with the keys `dispatch`, `step` and `work_item`, which are part of the record, beside `kernel` and `phase` [LS-290].\n9. <a id=\"LS-291\"></a><a id=\"LS-292\"></a><a id=\"LS-293\"></a><a id=\"LS-294\"></a>A diagnostic may suggest a fix, on its `help` line. A suggested fix [LS-291, LS-292, LS-293, LS-294]:\n   - is an explicit edit of the source whose"
  },
  {
   "id": "spec-04p:diagnostics-p3",
   "edition": "SPEC-04P.2",
   "title": "5.1.3 Diagnostics (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#diagnostics",
   "internal": 0,
   "content": "**Examples**\n\n10. This example shows a literal that does not fit its type. The caret marks the literal:\n\n```cint fit_level.ci\nI8 level = 200;\n\"{level}\\n\";\n```\n\n```text\nerror[C2003]: literal does not fit its type\n  --> fit_level.ci:1:12\n   |\n 1 | I8 level = 200;\n   |            ^\n```\n\n11. A lexical error is reported before a type error on an earlier line, because forming tokens is the earlier phase. `007` is a decimal literal with a leading zero (6.4.5):\n\n```cint phases.ci\nI8 a = 300;\nI64 b = 007;\n\"{a} {b}\\n\";\n```\n\n```text\nerror[C1022]: invalid integer literal\n  --> phases.ci:2:9\n   |\n 2 | I64 b = 007;\n   |         ^\n```\n\n12. This example shows the machine form of a diagnostic and of a fault. The program `fit.ci` is `fit_level.ci` above; `add_one.ci` prints `start` and then faults inside the function `add_one`:\n\n```console\n$ cint --json run fit.ci\n{\"code\":\"C2003\",\"column\":12,\"file\":\"fit.ci\",\"line\":1,\"message\":\"literal does not fit its type\",\"schema\":\"CINT-DIAG-1\",\"severity\":\"error\"}\n$ cint --json run add_one.ci\nstart\n{\"address\":null,\"code\":\"E_OVERFLOW\",\"column\":14,\"exact\":{\"t\":\"Z\",\"v\":\"9223372036854775808\"},\"file\":\"add_one.ci\",\"limit\":{\"t\":\"I64\",\"v\":\"9223372036854775807\"},\"line\":2,\"noncanonical\":{\"fuel_consumed\":\"2\"},\"operands\":[{\"t\":\"I64\",\"v\":\"9223372036854775807\"},{\"t\":\"I64\",\"v\":\"1\"}],\"operation\":\"add.checked.i64\",\"revision\":\"<hash>\",\"schema\":\"CINT-FAULT-1\",\"severity\":\"fault\",\"source_map\":null,\"stack\":[{\"column\":12,\"file\":\"add_one.ci\",\"line\":6}]}\n```\n\n   `<hash>` stands for the `revision` value, 64 hexadecimal digits that identify the program (3.31). `stack` holds the position of the call `add_one(big)`.\n\n**Notes**\n\n13. `cint run` writes diagnostics and fault reports to its standard error, and the program's output to its standard output. It prints neither the `help` line nor the function name of paragraph 6."
  },
  {
   "id": "spec-04p:program-start-and-termination",
   "edition": "SPEC-04P.2",
   "title": "5.2.1 Program start and termination",
   "clauses": "IM-117 LS-221",
   "url": "/specifications/spec-04p/2/#program-start-and-termination",
   "internal": 0,
   "content": "#### 5.2.1 Program start and termination\n\nA program runs inside a context, one entry at a time. The context holds what lasts between entries; an entry is one run from an entry point to its end.\n\n**Semantics**\n\n1. <a id=\"IM-117\"></a>A *context* is the state of one loaded program: its module-level variables, its arenas and pools and its fault record. It lasts across entries until the host program that created it destroys it (SPEC-03P.1) [IM-117].\n2. Each entry (3.20) has its own fuel allowance (5.2.4), call-depth limit (5.2.5) and frame arena (5.2.6), and counts its own fuel and its own kernel dispatches [IM-117].\n3. `cint run` creates a context and runs one entry in it: the top-level statements of a script, or `main` (5.1.2). Each `test` block runs as an entry in a fresh context of its own (6.15.3).\n4. An entry ends in one of three ways [LS-221]:\n   - it *completes*: the last top-level statement of the script finishes, or the entry function returns;\n   - it *ends with an error*: `main`, of result type `E!void`, returns an error value of `E`;\n   - it *faults* (5.2.3).\n5. An entry that ends with an error is not faulted: the error value is its result, the context is not faulted and its output stands. `cint run` reports the error on its standard error, as 6.11.7 states, and exits with the status of Note 7 [LS-221].\n\n**Examples**\n\n6. This example shows a program whose `main` returns an error:\n\n```cint config_check.ci\nerror Config { missing, invalid }\nConfig!void main() {\n    \"checking\\n\";\n    return .invalid;\n}\n```\n\n   The output written before the `return` stands, and `cint run` reports the error and exits with status 6:\n\n```console\n$ cint run config_check.ci\nchecking\nerror: config_check.Config.invalid (tag 2)\n```\n\n**Notes**"
  },
  {
   "id": "spec-04p:program-start-and-termination-p1",
   "edition": "SPEC-04P.2",
   "title": "5.2.1 Program start and termination (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#program-start-and-termination",
   "internal": 0,
   "content": "7. The exit status of `cint run` is 0 when the entry completes, 1 when it faults, 2 when the program is rejected with a diagnostic, and 6 when `main` returns an error. SPEC-06P.1 lists every status."
  },
  {
   "id": "spec-04p:output",
   "edition": "SPEC-04P.2",
   "title": "5.2.2 Output",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#output",
   "internal": 0,
   "content": "#### 5.2.2 Output\n\nOutput is the bytes a program prints.\n\n**Semantics**\n\n1. A program's output is the sequence of bytes that its print statements write, in the order they run (6.10.10, with the formatting of 7.5). The bytes depend only on the program and its semantic inputs (5.2.7), never on the host's locale or platform, so the same entry writes the same bytes on every implementation (8.2). `cint run` writes them to its standard output.\n\n**Examples**\n\n2. Output written before a fault stands. The fault report follows it:\n\n```cint partial.ci\nfor i in 1..=3 {\n    \"line {i}\\n\";\n}\nU8 level = 255;\nlevel += 1;\n\"not reached\\n\";\n```\n\n```text\nline 1\nline 2\nline 3\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> partial.ci:5:7\n   |\n 5 | level += 1;\n   |       ^ add.checked.u8\n   ...\n```"
  },
  {
   "id": "spec-04p:faults",
   "edition": "SPEC-04P.2",
   "title": "5.2.3 Faults",
   "clauses": "IM-104",
   "url": "/specifications/spec-04p/2/#faults",
   "internal": 0,
   "content": "#### 5.2.3 Faults\n\nA fault stops a run at an operation that cannot give a correct result. It is reported with everything needed to see why: the operation, its operands, the exact result and the bound it crossed, and where it happened.\n\n**Semantics**\n\n1. <a id=\"IM-104\"></a>Every fault has one of these *fault codes*. The number is the code's value in the encoded fault record (SPEC-01P.2) [IM-104]:"
  },
  {
   "id": "spec-04p:faults-p1",
   "edition": "SPEC-04P.2",
   "title": "5.2.3 Faults (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#faults",
   "internal": 0,
   "content": "| Code | Number | Raised by | Rules |\n|---|---:|---|---|\n| `E_OVERFLOW` | 1 | A checked operator, conversion or named operation whose exact or rounded result is outside the range of its type | 6.7, 6.6, 7.2, 7.3 |\n| `E_DIV_ZERO` | 2 | A division or remainder whose divisor is 0, `muldiv` included | 6.7.7, 7.2 |\n| `E_BOUNDS` | 3 | An index outside an extent, a slice whose bounds are not valid, a full arena or pool or an exhausted frame arena | 6.12, 6.14, 5.2.6 |\n| `E_SHAPE` | 4 | Views whose shapes disagree, a negative extent, `min` or `max` of an empty input, or a dispatch whose work-item count exceeds `MAX(I64)` | 6.12, 7.3, 7.4, 6.13 |\n| `E_SHIFT` | 5 | A shift or rotation count outside `0` to `w - 1` | 6.7.8 |\n| `E_NARROW` | 6 | A checked conversion whose value is outside the target's range, or a `c` hole whose value is not a Unicode scalar value | 6.6, 7.5.3 |\n| `E_ALIAS` | 7 | A writable argument that overlaps another argument, or operands of `copy` that overlap | 6.9.5, 6.12.5, 6.13, 7.4 |\n| `E_STALE_HANDLE` | 8 | A handle that is not valid for one of the reasons of 6.14.4, among them the null handle and a handle whose generation has ended, or an allocation from or a reset of a retired arena | 6.14 |\n| `E_FUEL` | 9 | A charge point that would exceed the entry's fuel allowance | 5.2.4 |\n| `E_UNSUPPORTED` | 10 | An entry, a dispatch or a call depth whose type, operation or layout the implementation cannot carry out exactly, found when the entry or the dispatch begins (3.16) | 4, 5.2.5 |\n| `E_DOMAIN` | 11 | `isqrt`, `isqrt_round` or a fixed-point square root of a negative value, or `clamp` with its bounds in the wrong order | 7.2 |\n| `E_DEPTH` | 12 | A call that would exceed the entry's call-depth limit | 5.2.5 |\n| `E_ASSERT` | 13 | A failed `assert` outside a test | 6.10.9 |"
  },
  {
   "id": "spec-04p:faults-p2",
   "edition": "SPEC-04P.2",
   "title": "5.2.3 Faults (part 3)",
   "clauses": "IM-118 IM-121",
   "url": "/specifications/spec-04p/2/#faults",
   "internal": 0,
   "content": "2. <a id=\"IM-118\"></a>A fault ends the current entry at once. No later operation of the entry runs, its deferred statements do not run (6.10.7), and the entry has no result [IM-118].\n3. Program code cannot catch, inspect or resume a fault. No construct of the language observes a fault raised in its own context: the context is the only fault boundary, and a fault is handled by the program that supervises the context, through the host interface. A failure that a program is meant to handle is an error, returned as a value (6.11) [IM-118].\n4. A fault sets the fault record of the context. The record stays: every further entry into the context fails at once with the same record, which the host receives, until the host resets the context. Resetting clears the fault record and changes no other state. A host that wants an earlier state restores a checkpoint (8.4) [IM-118].\n5. <a id=\"IM-121\"></a>After a fault, the state of the context is [IM-121]:\n\n| Part of the state | What it holds |\n|---|---|\n| Module-level variables and arrays written by sequential code | Every store of every statement that completed before the fault, including statements of functions that the faulting statement called; not the store of the faulting statement itself (6.2.4) |\n| Outputs of the kernel dispatch that faulted | Not published: their previous contents remain (6.13.6) |\n| Fault record | The record of the fault (8.1) |\n| Fuel consumed by the entry | The sum of the charges that succeeded; a charge that faults `E_FUEL` is not counted (5.2.4) |\n| Local variables of active calls | Not part of the state; the debug tools can show them (8.5) |"
  },
  {
   "id": "spec-04p:faults-p3",
   "edition": "SPEC-04P.2",
   "title": "5.2.3 Faults (part 4)",
   "clauses": "IM-122 LS-280 LS-284 LS-285",
   "url": "/specifications/spec-04p/2/#faults",
   "internal": 0,
   "content": "6. <a id=\"IM-122\"></a>Sequential code (3.35) does not roll back stores [IM-122].\n7. <a id=\"LS-284\"></a>A fault report names the fault code, the operation, every operand, the source position and the call path. The *operation identifier* is lower case and has the form `name.form.t` (B.3), with a second type for a conversion and a rounding mode where one applies: `add.checked.i64`, `shl.wrap.u32`, `as.checked.i64.i8`, `div.checked.i128` [LS-284]. 8.1 describes every field of the record and how to read a report.\n8. <a id=\"LS-280\"></a>Every value in a report is printed exactly, in decimal, with its type. When a fault concerns a range, the report prints the bound that was crossed as `limit`. A value is never abbreviated, rounded or written in scientific notation. A fixed-point operand is shown as its type, the word `raw` and its raw value (3.36), from which its exact decimal value follows (8.1) [LS-280].\n9. <a id=\"LS-285\"></a>Each fault code records these fields beyond the operation and the position [LS-285]:\n\n| Code | Fields |\n|---|---|\n| `E_OVERFLOW` | the operands, the exact result and the bound crossed |\n| `E_DIV_ZERO` | the dividend and the divisor |\n| `E_BOUNDS` | the index or the bounds of a slice, the dimension and the extent |\n| `E_SHAPE` | the extents that disagree |\n| `E_SHIFT` | the value and the count; the limit is the largest valid count, `w - 1` |\n| `E_NARROW` | the value, and the bound of the target type it crossed |\n| `E_ALIAS` | the two arguments that overlap |\n| `E_STALE_HANDLE` | the handle and the generations that disagree |\n| `E_FUEL` | the allowance, as the limit |\n| `E_DEPTH` | the depth limit |\n| `E_UNSUPPORTED` | the operation that cannot be carried out |\n| `E_DOMAIN` | the operand |\n| `E_ASSERT` | the two operands of a comparison condition, or none |"
  },
  {
   "id": "spec-04p:faults-p4",
   "edition": "SPEC-04P.2",
   "title": "5.2.3 Faults (part 5)",
   "clauses": "IM-105 LS-286",
   "url": "/specifications/spec-04p/2/#faults",
   "internal": 0,
   "content": "10. <a id=\"LS-286\"></a>A fault record is never shortened to fit a fixed-size structure. Its operands can exceed 1,024 bits: the exact product of two `I1024` values needs up to 2,047 bits [LS-286].\n11. <a id=\"IM-105\"></a>A host resource that runs out or fails, such as memory for a host allocation, a file or device error or a failing host callback, is not a fault. It is an outcome of the host interface (SPEC-03P.1): it has no fault record, and the entry it ends has no execution identity (8.2) [IM-105].\n12. A fault during the evaluation of a constant expression at translation is not a run-time fault; it is the diagnostic C6001, which carries the same fault code and operands (6.8).\n\n**Examples**\n\n13. This example shows a fault inside a function. The report adds one `called from` line for each active call, outermost first:\n\n```cint called.ci\nI64 add_one(I64 v) {\n    return v + 1;\n}\n\"start\\n\";\nI64 big = I64.max;\nI64 next = add_one(big);\n\"{next}\\n\";\n```\n\n```text\nstart\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> called.ci:2:14\n   |\n 2 |     return v + 1;\n   |              ^ add.checked.i64\n   |\n   = operation: add.checked.i64\n   = operand-count: 2\n   = operand: I64 9223372036854775807\n   = operand: I64 1\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n   ...\n   = stack-depth: 1\n   = called from: called.ci:6:12\n   ...\n```\n\n14. A division by zero has no exact result and no limit:\n\n```cint by_zero.ci\nI64 total = 10;\nI64 items = 0;\nI64 mean = total / items;\n\"{mean}\\n\";\n```\n\n```text\nfault[E_DIV_ZERO]: division by zero\n  --> by_zero.ci:3:18\n   |\n 3 | I64 mean = total / items;\n   |                  ^ div.checked.i64\n   |\n   = operation: div.checked.i64\n   = operand-count: 2\n   = operand: I64 10\n   = operand: I64 0\n   = exact:   none\n   = limit:   none\n   ...\n```"
  },
  {
   "id": "spec-04p:faults-p5",
   "edition": "SPEC-04P.2",
   "title": "5.2.3 Faults (part 6)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#faults",
   "internal": 0,
   "content": "15. A failed `assert` outside a test faults `E_ASSERT` at the first character of its condition, and records both operands of the comparison. The message is not evaluated:\n\n```cint asserted.ci\nI64 have = 3;\nI64 want = 4;\nassert(have == want, \"counts differ\");\n\"after\\n\";\n```\n\n```text\nfault[E_ASSERT]: assertion failed\n  --> asserted.ci:3:8\n   |\n 3 | assert(have == want, \"counts differ\");\n   |        ^ assert.checked.bool\n   |\n   = operation: assert.checked.bool\n   = operand-count: 2\n   = operand: I64 3\n   = operand: I64 4\n   ...\n```\n\n**Notes**\n\n16. In C, signed overflow, division by zero and an index outside an array are undefined behavior: the program may continue with any value. In cint each is a fault, reported at the operation. Annex C lists the others.\n17. A program that needs a change of state to happen entirely or not at all keeps two copies and switches between them, or writes the new state with a kernel, whose outputs are published only when every work-item succeeds (6.13.6)."
  },
  {
   "id": "spec-04p:fuel",
   "edition": "SPEC-04P.2",
   "title": "5.2.4 Fuel",
   "clauses": "IM-137 IM-139",
   "url": "/specifications/spec-04p/2/#fuel",
   "internal": 0,
   "content": "#### 5.2.4 Fuel\n\nFuel counts the steps an entry takes: calls, loop iterations, reductions and kernel dispatches. An entry may be given a fuel allowance, and it faults when a step would take it past the allowance.\n\n**Semantics**\n\n1. <a id=\"IM-137\"></a>Fuel is counted in units of the fuel model `fuel-v1`, at the charge points of paragraph 3. It is not elapsed time and not a count of machine instructions: the fuel an entry consumes is the same on every conforming implementation, every executor and every optimization level [IM-137].\n2. Each entry has a *fuel allowance* `B`, an `I64` with `B >= 0` and its consumed fuel starts at 0. A host that passes a value that is not such an `I64` (for example `2^63` as an unsigned 64-bit value) is not accepted when the entry starts (SPEC-03P.1). An entry may have no allowance: it still counts fuel, and only a charge that would carry its count past `MAX(I64)` faults `E_FUEL`, with the limit `I64 9223372036854775807` [IM-137].\n3. <a id=\"IM-139\"></a>The charge points of `fuel-v1` are these, and nothing else charges fuel [IM-139]:"
  },
  {
   "id": "spec-04p:fuel-p1",
   "edition": "SPEC-04P.2",
   "title": "5.2.4 Fuel (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#fuel",
   "internal": 0,
   "content": "| Charge point | Units |\n|---|---:|\n| A call of a user function, including the entry function and the implicit entry of a script, after the depth check and before the parameters are bound | 1 |\n| Each iteration of a `for` or `while` loop, including the first, after the condition is `true` and before the body runs | 1 |\n| A reduction over `n` elements (`sum`, `fold_checked`, `sum_wrap`, `sum_sat`, `min`, `max`, `count` and `dot` over an array), once, before any element is read | `ceil(n / 64)`, and 0 for `n = 0` |\n| A kernel dispatch of `N` work-items, once, after the entry checks of the dispatch pass (6.13.6, paragraph 7) and before any work-item runs; the calls and loop iterations inside each work-item then charge as above, in work-item order | `N` |\n| Operators, conversions and named scalar operations at any width, even when written as calls (`abs`, `muldiv`, `isqrt`, `add_result` and the others); array assignment and initializers; `copy`, `fill` and other operations that iterate over elements | 0 |"
  },
  {
   "id": "spec-04p:fuel-p2",
   "edition": "SPEC-04P.2",
   "title": "5.2.4 Fuel (part 3)",
   "clauses": "IM-137 IM-140 IM-141 IM-142 IM-143 LS-141",
   "url": "/specifications/spec-04p/2/#fuel",
   "internal": 0,
   "content": "4. <a id=\"IM-141\"></a>When a charge would make the entry's consumed fuel exceed `B`, the charge point faults `E_FUEL` with the operation identifier `fuel.charge` and the limit `B`. The step does not happen: the call is not entered, the iteration does not begin, the reduction reads no element, the dispatch does not start. The fault's position is the loop keyword for an iteration, the callee name for a call or a reduction, the function's name in its declaration for an entry function, the `test` keyword for a test block, and the first top-level statement for the implicit entry of a script [IM-141].\n5. <a id=\"LS-141\"></a>At a call, the arguments are evaluated first, then the checks on entry to the callee run in their stated order (shapes, then overlap of writable arguments, 6.9.5), then the depth check (5.2.5), then the fuel charge, then the body. A call that fails a check is not charged [LS-141].\n6. <a id=\"IM-142\"></a>An implementation may charge in batches, such as a loop's whole trip count at once, only when the result is the same on every input: the same position of an `E_FUEL` fault, the same consumed count and the same state at the fault [IM-142].\n7. <a id=\"IM-143\"></a><a id=\"IM-140\"></a>With an allowance, every entry ends: each iteration, call, reduction and dispatch is charged, the work between two charge points is bounded by the program's text and the extents of the arrays it reads and writes, and the iterations and calls inside each work-item of a kernel are charged as they occur [IM-143, IM-140].\n8. Fuel is counted per entry. It does not accumulate across entries and is not part of the context's state. The fuel an entry consumed is part of its outcome (8.2) [IM-137].\n\n**Examples**"
  },
  {
   "id": "spec-04p:fuel-p3",
   "edition": "SPEC-04P.2",
   "title": "5.2.4 Fuel (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#fuel",
   "internal": 0,
   "content": "9. A fault report shows the fuel the entry consumed before the fault. Here it is 22: 1 for the entry `main`, 1 for the call of `total`, 3 for its iterations, 1 for the call of `total2` and 16 for `sum` (7.3) over 1,000 elements. `n` is a size parameter (3.34):\n\n```cint fuel_count.ci\nI64 total[n](in I64[n] xs) {\n    I64 s = 0;\n    for i in 0..n {\n        s += xs[i];\n    }\n    return s;\n}\nI64 total2[n](in I64[n] xs) {\n    return sum(xs);\n}\nvoid main() {\n    I64[3] small = [1, 2, 3];\n    I64[1000] big;\n    \"{total(small)} {total2(big)}\\n\";\n    I8 stop = 127;\n    stop += 1;\n}\n```\n\n```text\n6 0\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> fuel_count.ci:16:10\n   ...\n   = fuel-consumed: 22 (not part of the fault record)\n   ...\n```\n\n10. A call that fails its shape check is not charged; the arguments are slices (6.12.3). The fuel consumed is 2, for `main` and `run`; the call of `copy_first` charged nothing:\n\n```cint shape_first.ci\nvoid copy_first[n](inout I64[n] dst, in I64[n] src) {\n    dst[0] = src[0];\n}\nvoid run(I64 k) {\n    I64[6] x;\n    I64[6] y;\n    copy_first(x[0..k], y[2..5]);\n}\nvoid main() {\n    run(4);\n}\n```\n\n```text\nfault[E_SHAPE]: shapes do not match\n  --> shape_first.ci:7:5\n   |\n 7 |     copy_first(x[0..k], y[2..5]);\n   |     ^ bind.shape\n   ...\n   = fuel-consumed: 2 (not part of the fault record)\n   ...\n```\n\n11. `cint debug locate` (8.5) runs a program with a fuel allowance. Its first lines name the executor that ran the program, the boundary (3.37) of the recording (3.40) at which the fault was found, and the *bracket*, the boundaries between which the fault lies (8.5). With an allowance of 3, the script `countdown.ci` charges 1 for its entry and 1 for each of two iterations; the third iteration would take it to 4, so the `while` faults:\n\n```cint countdown.ci\nI64 k = 0;\nwhile (k < 5) {\n    k += 1;\n}\n\"{k}\\n\";\n```\n\n```text\n5\n```"
  },
  {
   "id": "spec-04p:fuel-p4",
   "edition": "SPEC-04P.2",
   "title": "5.2.4 Fuel (part 5)",
   "clauses": "IM-140",
   "url": "/specifications/spec-04p/2/#fuel",
   "internal": 0,
   "content": "```console\n$ cint debug locate countdown.ci --fuel 3\nprogram    countdown.ci   evaluator cpu-sir-interp, under a recording\ntarget     boundary 1 of 1, the program entry: the first fault, reproduced by replay\nbracket    the initial state; then boundary 1\nfault[E_FUEL]: fuel allowance exhausted\n  --> countdown.ci:2:1\n   |\n 2 | while (k < 5) {\n   | ^ fuel.charge\n   |\n   = operation: fuel.charge\n   = operand-count: 0\n   = exact:   none\n   = limit:   I64 3\n...\n   = fuel-consumed: 3 (not part of the fault record)\n...\n```\n\n**Notes**\n\n12. Operators and named scalar operations charge nothing because the cost of each is bounded by the width of its operands, and the number of them between two charge points is bounded by the program's text [IM-140].\n13. 5.2.7 gives the allowance of `cint run`, and SPEC-06P.1 lists the allowance each tool gives."
  },
  {
   "id": "spec-04p:call-depth",
   "edition": "SPEC-04P.2",
   "title": "5.2.5 Call depth",
   "clauses": "IM-119 LS-144",
   "url": "/specifications/spec-04p/2/#call-depth",
   "internal": 0,
   "content": "#### 5.2.5 Call depth\n\nEvery call of a user function makes the active calls one deeper. Each entry has a limit on that depth, and the call that would pass it faults at the same call on every implementation, instead of overflowing a native stack.\n\n**Semantics**\n\n1. <a id=\"IM-119\"></a>Each entry has a *call-depth limit* `D`, an `I64` with `D >= 1`. The entry function, or the implicit entry of a script, has depth 1 and each active call of a user function adds 1 [IM-119].\n2. <a id=\"LS-144\"></a>A call that would make the depth exceed `D` faults `E_DEPTH` before its fuel charge and before its frame is created. The call is not entered and consumes no fuel. The fault record has the operation identifier `call.enter`, no operands and the limit `D`; its position is the callee name of that call, and its stack holds the `D - 1` call sites of the active calls [IM-119, LS-144].\n3. Recursion is permitted outside kernels. A kernel body calls no user function (6.13.3), so a kernel never recurses [LS-144].\n4. `D` is given by the host program or the tool that starts the entry (5.2.7). An implementation shall accept every `D` up to 4,096 (5.3) [LS-144].\n5. An implementation whose native stack cannot hold `D` frames of the program shall keep the frames elsewhere, or refuse the entry with `E_UNSUPPORTED` before it starts. It shall not crash [IM-119, LS-144].\n\n**Examples**\n\n6. Recursion to a depth of 11 completes. The second call stops at depth 256: the script's entry and 255 active calls of `down`:\n\n```cint depth.ci\nI64 down(I64 n) {\n    if (n == 0) {\n        return 0;\n    }\n    return down(n - 1) + 1;\n}\n\"{down(10)}\\n\";\n\"{down(1000000)}\\n\";\n```"
  },
  {
   "id": "spec-04p:call-depth-p1",
   "edition": "SPEC-04P.2",
   "title": "5.2.5 Call depth (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#call-depth",
   "internal": 0,
   "content": "```text\n10\nfault[E_DEPTH]: call depth limit exceeded\n  --> depth.ci:5:12\n   |\n 5 |     return down(n - 1) + 1;\n   |            ^ call.enter\n   |\n   = operation: call.enter\n   = operand-count: 0\n   = exact:   none\n   = limit:   I64 256\n   ...\n   = stack-depth: 255\n   = called from: depth.ci:8:3\n   = called from: depth.ci:5:12\n   ...\n```"
  },
  {
   "id": "spec-04p:the-frame-arena",
   "edition": "SPEC-04P.2",
   "title": "5.2.6 The frame arena",
   "clauses": "LS-110",
   "url": "/specifications/spec-04p/2/#the-frame-arena",
   "internal": 0,
   "content": "#### 5.2.6 The frame arena\n\nThe local arrays of sequential code (3.35) live in a region of fixed capacity, the frame arena and not on a native stack. Its capacity is counted in elements, so a program runs out of it at the same declaration on every implementation, and running out is a fault, not a crash.\n\n**Constraints**\n\n1. <a id=\"LS-110\"></a>A local array whose extent is a size parameter (3.34), such as `I64[n] tmp;`, is permitted only in sequential code. In a kernel body it is diagnosed C9102 at that extent, since the private arrays of a kernel have constant extents (6.13.3) [LS-110].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:the-frame-arena-p1",
   "edition": "SPEC-04P.2",
   "title": "5.2.6 The frame arena (part 2)",
   "clauses": "LS-110",
   "url": "/specifications/spec-04p/2/#the-frame-arena",
   "internal": 0,
   "content": "2. Each local array of sequential code is storage of the entry's frame arena (3.23). The arena's capacity, and the use of it, are counted in elements: each element counts once, whatever its type [LS-110].\n3. The capacity is a semantic input of the entry (5.2.7). Its default, and the least capacity an implementation shall accept, is 2,097,152 elements [LS-110].\n4. Each entry starts with an empty frame arena. A local array is charged its number of elements when its declaration runs, after its shape is checked (6.12.1) and before its initializer, and is released when its block exits, however the block exits. The charges therefore follow the nesting of blocks and the depth of recursion, and an array declared in a loop body is charged once in each iteration and released before the next [LS-110].\n5. Scalars, structs, view variables and the private arrays of a kernel are not charged. The top-level arrays of a script are locals of its entry and are charged [LS-110].\n6. A declaration whose charge would exceed the capacity faults `E_BOUNDS` with the operation identifier `arena.alloc`, at the declared name. The operands are three `I64` values: the elements requested, the elements in use and the capacity. The record has no exact result and no limit [LS-110].\n7. An implementation need not charge the local arrays of an entry when it proves that, over every call path, the entry never uses more than 2,097,152 elements: no run within the semantic inputs can then exhaust the arena [LS-110].\n\n**Examples**\n\n8. Each call of `nest` holds 100,000 elements. Twenty nested calls fit; the twenty-first does not. `E_BOUNDS` covers an exhausted frame arena (5.2.3), so the message reads `index out of bounds`:"
  },
  {
   "id": "spec-04p:the-frame-arena-p2",
   "edition": "SPEC-04P.2",
   "title": "5.2.6 The frame arena (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#the-frame-arena",
   "internal": 0,
   "content": "```cint frames.ci\nI64 nest(I64 level) {\n    I64[100000] scratch;\n    scratch[0] = level;\n    if (level == 0) {\n        return 0;\n    }\n    return nest(level - 1) + scratch[0];\n}\n\"{nest(19)}\\n\";\n\"{nest(25)}\\n\";\n```\n\n```text\n190\nfault[E_BOUNDS]: index out of bounds\n  --> frames.ci:2:17\n   |\n 2 |     I64[100000] scratch;\n   |                 ^ arena.alloc\n   |\n   = operation: arena.alloc\n   = operand-count: 3\n   = operand: I64 100000\n   = operand: I64 2000000\n   = operand: I64 2097152\n   = exact:   none\n   = limit:   none\n   ...\n```\n\n9. An array declared in a loop body is released at the end of each iteration, so 100 iterations of 100,000 elements fit:\n\n```cint loop_frames.ci\nvoid main() {\n    I64 total = 0;\n    for i in 0..100 {\n        I64[100000] row;\n        row[0] = i;\n        total += row[0];\n    }\n    \"{total}\\n\";\n}\n```\n\n```text\n4950\n```\n\n10. Elements are counted, not bytes. After an array of 2,097,152 `I64` elements, one more `U8` element does not fit:\n\n```cint element_count.ci\nvoid main() {\n    I64[2097152] all;\n    U8[1] one;\n    \"{one[0]}\\n\";\n}\n```\n\n```text\nfault[E_BOUNDS]: index out of bounds\n  --> element_count.ci:3:11\n   |\n 3 |     U8[1] one;\n   |           ^ arena.alloc\n   |\n   = operation: arena.alloc\n   = operand-count: 3\n   = operand: I64 1\n   = operand: I64 2097152\n   = operand: I64 2097152\n   ...\n```"
  },
  {
   "id": "spec-04p:semantic-inputs",
   "edition": "SPEC-04P.2",
   "title": "5.2.7 Semantic inputs",
   "clauses": "IM-137 LS-110 LS-144",
   "url": "/specifications/spec-04p/2/#semantic-inputs",
   "internal": 0,
   "content": "#### 5.2.7 Semantic inputs\n\nThe outcome of an entry is decided by its semantic inputs (3.24) and by nothing else. Three of them are numbers that bound the entry, given by the host program or the tool that starts it.\n\n**Semantics**\n\n1. The fuel allowance (5.2.4), the call-depth limit (5.2.5) and the frame-arena capacity (5.2.6) are given for each entry by the host program, by the configuration of the tool (SPEC-06P.1), or by the tool that starts the entry. A value given explicitly replaces the default [LS-144, IM-137, LS-110].\n2. `cint run` starts its entry with these values [LS-144, LS-110]:\n\n| Semantic input | Range | `cint run` |\n|---|---|---|\n| Fuel allowance | an `I64` from 0, or none | none |\n| Call-depth limit `D` | an `I64` from 1 | 256 |\n| Frame-arena capacity | at least 2,097,152 elements | 2,097,152 elements |\n\n3. 8.2 states what agreement on an outcome means, and what never enters it: the time, the machine, the locale, the scheduling of threads and the addresses of native storage."
  },
  {
   "id": "spec-04p:implementation-limits",
   "edition": "SPEC-04P.2",
   "title": "5.3 Implementation limits",
   "clauses": "LS-311",
   "url": "/specifications/spec-04p/2/#implementation-limits",
   "internal": 0,
   "content": "### 5.3 Implementation limits\n\nEvery implementation accepts programs at least as large as the limits below.\n\n**Semantics**\n\n1. <a id=\"LS-311\"></a>A conforming implementation shall accept every program within these limits [LS-311]:\n\n| Quantity | Limit |\n|---|---|\n| Size of a source file | at least 16,777,216 bytes |\n| Nesting of blocks and of expressions, not counting `else if` chains | at least 256 |\n| `else if` arms in one chain | no limit other than the file's size |\n| Cases in one `switch` | at least 65,536 |\n| Parameters of one function | at least 64 |\n| Fields of one struct | at least 4,096 |\n| Length of an identifier | exactly 255 bytes: a longer identifier is C1012 on every implementation (6.4.4) |\n| Magnitude of a literal | exactly `2^4096 - 1`: a larger literal is C1023 on every implementation (6.4.5) |\n| Rank of an array or view | exactly 4 (6.12) |\n| Call-depth limit `D` accepted as a semantic input | at least 4,096 active calls (5.2.5) |\n| Frame-arena capacity accepted as a semantic input | at least 2,097,152 elements (5.2.6) |\n\n2. The rows that say \"exactly\" bind every implementation; the others are minimums. An implementation may accept more [LS-311].\n3. A program beyond one of an implementation's own limits is rejected with a diagnostic whose code begins with `C9`: C9001 for a capacity or output size, reported at line 1 when it concerns a whole file, and C9004 for nesting beyond the implementation's limit, at the construct that exceeds it. The implementation shall not miscompile or truncate the program [LS-311]."
  },
  {
   "id": "spec-04p:language",
   "edition": "SPEC-04P.2",
   "title": "6 Language",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#language",
   "internal": 0,
   "content": "## 6 Language\n\nThis clause defines the language: the notation of its grammar, the concepts it rests on, its types, lexical elements, literals, conversions, expressions, declarations, statements, errors, arrays and views, kernels, memory and modules."
  },
  {
   "id": "spec-04p:notation",
   "edition": "SPEC-04P.2",
   "title": "6.1 Notation",
   "clauses": "IM-1 LS-295",
   "url": "/specifications/spec-04p/2/#notation",
   "internal": 0,
   "content": "### 6.1 Notation\n\nThis subclause gives the notation of the Syntax parts and the symbols used in rules. Clause 3 defines the terms.\n\n1. Syntax is written in a form of EBNF: `=` defines a rule, `;` ends it, `|` separates alternatives, `[ x ]` is optional, `{ x }` is repeated zero or more times, `( )` groups, quoted text is a terminal, and `(* *)` encloses a comment [LS-295].\n2. The names of lexical rules, which form tokens, are written in capitals, such as `IDENT` and `DEC_INT`. Tokens are formed by maximal munch (6.4.2), and white space and comments between tokens are skipped. The other rules are written in lower case and are built from tokens [LS-295].\n3. A Syntax part states the structure of a construct only. The rules on types, on mixing operators, on exhaustive `switch` and the like are its Constraints. Annex A collects every Syntax part [LS-295].\n4. <a id=\"IM-1\"></a>Rules use the symbols of 3.45, with these values. For an integer type `T` of width `w`: when `T` is signed, `MIN(T)` is `-2^(w-1)` and `MAX(T)` is `2^(w-1) - 1`; when `T` is unsigned, `MIN(T)` is 0 and `MAX(T)` is `2^w - 1`. `wrap(T, v)` is the one value `r` with `in(T, r)` and `r` congruent to `v` modulo `2^w`. `clamp(v, l, h)`, for `l <= h`, is `min(max(v, l), h)`. `2^k` is 2 raised to the power `k`. These symbols have the same values as the built-in operations of the same names (7.2.1), without their faults [IM-1].\n5. Numbers in rules and tables are decimal unless written with the prefix `0x` [IM-1]."
  },
  {
   "id": "spec-04p:values",
   "edition": "SPEC-04P.2",
   "title": "6.2.1 Values",
   "clauses": "IM-5",
   "url": "/specifications/spec-04p/2/#values",
   "internal": 0,
   "content": "#### 6.2.1 Values\n\nEvery value a program computes has a type: an integer in its type's range, a fixed-point value, a `Bool`, an error value, a handle, or an array or struct of these. How a machine stores an integer is not part of its meaning.\n\n**Semantics**\n\n1. <a id=\"IM-5\"></a>A value of an integer type is a member of Z within the type's range. Its meaning does not depend on how it is represented [IM-5].\n2. Only the operations defined on bits see a representation: the bitwise operators, the rotations, the wrapping conversion `as%`, the wrapping shift `<<%`, the conversions `!bits` and `!lanes` of a hole (7.5.4), and the encodings of SPEC-01P.2. For these, a signed value has the two's complement bit pattern of its type's width. Everywhere else, only the mathematical value can be observed [IM-5].\n3. `Bool` has the values `false` and `true` and is not an integer type (6.3.3). Arrays and structs hold values of the types of 6.3.\n\n**Examples**\n\n4. The value -1 of type `I8` has the bit pattern `11111111`, which `as%` reads as the `U8` value 255. The plain operators see only the value:\n\n```cint values.ci\nI8 a = -1;\nU8 bits = a as% U8;\nI8 b = a * a;\n\"{bits} {b} {a & 15}\\n\";\n```\n\n```text\n255 1 15\n```"
  },
  {
   "id": "spec-04p:objects-and-storage-durations",
   "edition": "SPEC-04P.2",
   "title": "6.2.2 Objects and storage durations",
   "clauses": "LS-112",
   "url": "/specifications/spec-04p/2/#objects-and-storage-durations",
   "internal": 0,
   "content": "#### 6.2.2 Objects and storage durations\n\nAn *object* is storage that holds a value: a variable, an element of an array or a field of a struct. Each object exists for a stated span, its *storage duration* and holds a value of its type for the whole span.\n\n**Semantics**\n\n1. A local variable, including a parameter, exists from the moment its declaration runs, or its function is entered, until its block exits, however the block exits. A local array is storage of the frame arena (5.2.6) [LS-112].\n2. The variables declared at the top level of a script are locals of the script's entry (5.1.2): they exist until the entry ends.\n3. A module-level variable of an importable module, or of a program with `main`, exists as long as the context and keeps its value from one entry to the next (6.9.3).\n4. The bytes of a string literal exist for the whole run and cannot be written (6.4.8).\n5. Objects in arenas and pools exist until their arena is reset or their slot is released (6.14).\n6. Every object holds a value of its type from the moment it exists: a variable of an integer, fixed-point, `Bool` or error-set type has a required initializer, and an array or struct without one is filled with zeros (6.9.1). No object is read before it holds a value.\n7. A view refers to the storage of another object. A view cannot be stored, so it never outlives that object (6.12)."
  },
  {
   "id": "spec-04p:scopes-and-visibility",
   "edition": "SPEC-04P.2",
   "title": "6.2.3 Scopes and visibility",
   "clauses": "LS-112",
   "url": "/specifications/spec-04p/2/#scopes-and-visibility",
   "internal": 0,
   "content": "#### 6.2.3 Scopes and visibility\n\nA name is visible in a region of the program, its scope. Names declared at module level are visible throughout the module; local names are visible from their declaration to the end of their block. A name visible at a point cannot be declared again there.\n\n**Constraints**\n\n1. <a id=\"LS-112\"></a>A declaration shall not use a name that is visible at that point, whether the visible name is a local, a parameter, a module-level name, an imported name or a built-in name. A repeated name is C3001, at the declared name. There is no shadowing [LS-112].\n2. A name that is not visible at the point of use is C3005 [LS-112].\n\n**Semantics**\n\n3. Each block introduces a scope [LS-112].\n4. The names of the types, structs, error sets, functions, kernels, constants and module-level variables of a module are visible everywhere in the module, whatever the order of declarations [LS-112].\n5. A local name, including a top-level variable of a script (5.1.2), is visible from its declaration to the end of its block [LS-112].\n\n**Examples**\n\n6. A name of an enclosing block cannot be declared again in an inner block:\n\n```cint shadow.ci\nI64 x = 1;\nif (x == 1) {\n    I64 x = 2;\n    \"{x}\\n\";\n}\n```\n\n```text\nerror[C3001]: duplicate name\n  --> shadow.ci:3:9\n   |\n 3 |     I64 x = 2;\n   |         ^\n```\n\n7. Blocks that do not enclose each other may declare the same name, and a constant may be declared after the function that uses it:\n\n```cint siblings.ci\nI64 scaled(I64 v) {\n    return v * K;\n}\nconst I64 K = 10;\nI64 total = 0;\nfor i in 0..3 {\n    I64 step = i + 1;\n    total += step;\n}\nfor i in 0..3 {\n    I64 step = scaled(i);\n    total += step;\n}\n\"{total}\\n\";\n```\n\n```text\n36\n```\n\n8. A local name is not visible before its declaration:\n\n```cint too_early.ci\n\"{later}\\n\";\nI64 later = 1;\n```"
  },
  {
   "id": "spec-04p:scopes-and-visibility-p1",
   "edition": "SPEC-04P.2",
   "title": "6.2.3 Scopes and visibility (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#scopes-and-visibility",
   "internal": 0,
   "content": "```text\nerror[C3005]: undefined or unusable name\n  --> too_early.ci:1:3\n   |\n 1 | \"{later}\\n\";\n   |   ^\n```"
  },
  {
   "id": "spec-04p:evaluation-order",
   "edition": "SPEC-04P.2",
   "title": "6.2.4 Evaluation order",
   "clauses": "IM-97 LS-142 LS-143",
   "url": "/specifications/spec-04p/2/#evaluation-order",
   "internal": 0,
   "content": "#### 6.2.4 Evaluation order\n\nEvery expression is evaluated in one order, left to right, and every operand is evaluated exactly once. So when an expression could fault in more than one place, the first fault in that order is the fault, on every implementation.\n\n**Constraints**\n\n1. <a id=\"LS-142\"></a>A call always has parentheses. Naming a function without calling it is rejected: as a statement, such as `f;`, with C4012, and where a value is expected, such as `I64 y = twice;`, with C4010 [LS-142].\n2. <a id=\"LS-143\"></a>A call statement whose function returns a value other than `void` shall use the value or discard it with `_ =` (6.11); otherwise it is C4011 [LS-143].\n3. <a id=\"IM-97\"></a>Assignment, compound assignment, `++` and `--` are statements, not expressions. They have no value and cannot appear inside an expression (6.7.14) [IM-97].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:evaluation-order-p1",
   "edition": "SPEC-04P.2",
   "title": "6.2.4 Evaluation order (part 2)",
   "clauses": "IM-100 IM-101 IM-102 IM-92 IM-93 IM-94 IM-95 IM-96 IM-98 IM-99 LS-137 LS-138",
   "url": "/specifications/spec-04p/2/#evaluation-order",
   "internal": 0,
   "content": "4. <a id=\"IM-92\"></a><a id=\"LS-137\"></a>The operands of an operator are evaluated left to right, each completely, including any fault it raises, before the next begins. The operator is applied after its operands are evaluated [IM-92, LS-137].\n5. <a id=\"IM-93\"></a>A call evaluates the callee, then each argument from left to right, then performs the call. Named arguments are evaluated in the order written. The elements of an array literal and the arguments of a struct constructor are evaluated from left to right [IM-93, LS-137].\n6. <a id=\"IM-94\"></a><a id=\"LS-138\"></a>`&&`, `||`, `? :` and `catch` evaluate only the operands that the result requires [IM-94, LS-138].\n7. <a id=\"IM-95\"></a>No operand is evaluated twice, and none is skipped because an implementation can predict its value, if its evaluation could fault [IM-95].\n8. <a id=\"IM-96\"></a>Consequently, the first fault in evaluation order is the fault of the expression [IM-96].\n9. <a id=\"IM-98\"></a><a id=\"LS-139\"></a>An assignment `place = expr` evaluates the subexpressions of the place, such as an array and its indices, from left to right and checks them first, then evaluates `expr`, then stores. `place op= expr` reads the place once, when the place is checked [IM-98, LS-139].\n10. <a id=\"IM-99\"></a>The store of the statement that faults does not happen. Every store, and every output, of a statement that completed before the fault remains, including those of statements in functions that the faulting statement called [IM-99].\n11. <a id=\"IM-100\"></a>In sequential code, stores become observable in program order. An implementation may reorder or remove a store only when no run, including one that faults later, can observe the difference in the state of the context [IM-100].\n12. <a id=\"IM-101\"></a>Every intermediate result has the type of its operation. There is no integer promotion, no evaluation in a wider type and no i"
  },
  {
   "id": "spec-04p:evaluation-order-p2",
   "edition": "SPEC-04P.2",
   "title": "6.2.4 Evaluation order (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#evaluation-order",
   "internal": 0,
   "content": "**Examples**\n\n14. Operands and arguments are evaluated from left to right, and the result follows the precedence of the operators:\n\n```cint left_right.ci\nI64 show(I64 v) {\n    \"[{v}]\";\n    return v;\n}\nI64 s = show(1) + show(2) * show(3);\n\"\\n{s}\\n\";\n```\n\n```text\n[1][2][3]\n7\n```\n\n15. The left operand faults first, so the division by zero is never reached:\n\n```cint first_fault.ci\nI64 x = I64.max;\nI64 y = 0;\nI64 r = (x + 1) / y;\n\"{r}\\n\";\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> first_fault.ci:3:12\n   |\n 3 | I64 r = (x + 1) / y;\n   |            ^ add.checked.i64\n   ...\n```\n\n16. The place is checked before the value is computed:\n\n```cint place_first.ci\nvoid main() {\n    I64[3] a;\n    I64 z = 0;\n    a[-1] = 1 / z;\n}\n```\n\n```text\nfault[E_BOUNDS]: index out of bounds\n  --> place_first.ci:4:6\n   |\n 4 |     a[-1] = 1 / z;\n   |      ^ index.checked.i64\n   |\n   = operation: index.checked.i64\n   = operand-count: 1\n   = operand: I64 -1\n   = exact:   none\n   = limit:   I64 3\n   ...\n```\n\n17. `g` completes before `1 / z` faults, so its output and its store remain; the assignment to `y` does not happen:\n\n```cint completed.ci\nI64 counter = 0;\nI64 g() {\n    counter = counter + 1;\n    \"g ran, counter {counter}\\n\";\n    return 5;\n}\nvoid step(I64 z) {\n    I64 y = 7;\n    y = g() + 1 / z;\n}\nvoid main() {\n    step(0);\n}\n```\n\n```text\ng ran, counter 1\nfault[E_DIV_ZERO]: division by zero\n  --> completed.ci:9:17\n   ...\n```\n\n18. `&&`, `||` and `? :` skip the operands they do not need:\n\n```cint short_circuit.ci\nI64 loud(I64 v) {\n    \"[{v}]\";\n    return v;\n}\nI64 a = 0;\nBool b = a != 0 && loud(1) == 1;\nBool c = a == 0 || loud(2) == 2;\nI64 d = a == 0 ? loud(3) : loud(4);\n\"\\n{b} {c} {d}\\n\";\n```\n\n```text\n[3]\nfalse true 3\n```"
  },
  {
   "id": "spec-04p:evaluation-order-p3",
   "edition": "SPEC-04P.2",
   "title": "6.2.4 Evaluation order (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#evaluation-order",
   "internal": 0,
   "content": "19. The product `a * b` has type `I32`, so it faults even though the final quotient would fit. Converting first, or naming a wide intermediate, gives the quotient:\n\n```cint intermediate.ci\nI32 a = 2_000_000_000;\nI32 b = 2;\nI32 d = ((a as I64) * (b as I64) / 4) as I32;\nI32 e = muldiv(I32, a, b, 4, floor);\n\"{d} {e}\\n\";\nI32 c = a * b / 4;\n\"{c}\\n\";\n```\n\n```text\n1000000000 1000000000\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> intermediate.ci:6:11\n   |\n 6 | I32 c = a * b / 4;\n   |           ^ mul.checked.i32\n   ...\n```\n\n20. A call statement must use the result of its function:\n\n```cint unused.ci\nI64 f() {\n    return 1;\n}\nf();\n```\n\n```text\nerror[C4011]: control-flow rule\n  --> unused.ci:4:1\n   |\n 4 | f();\n   | ^\n```\n\n**Notes**\n\n21. In C, the order in which the operands of most operators and the arguments of a call are evaluated is unspecified, and `i = i++ + 1` is undefined. In cint the order is fixed, and an assignment cannot appear inside an expression."
  },
  {
   "id": "spec-04p:types",
   "edition": "SPEC-04P.2",
   "title": "6.3 Types",
   "clauses": "LS-50",
   "url": "/specifications/spec-04p/2/#types",
   "internal": 0,
   "content": "### 6.3 Types\n\nEvery object and every expression of a cint program has a type, and the type is known when the program is translated. The type decides which values an object can hold, which operators apply to it, and what happens when a result does not fit. This section describes each kind of type: its values, how its name is written, and when two types are the same. The conversions between types are in 6.6, the operators in 6.7 and the declarations that create objects in 6.9.\n\ncint has no floating-point type and no pointer type, and no value changes type without a conversion written in the program (6.6), except that a value of an error set converts to a larger set (6.3.7).\n\n**Semantics**\n\n1. The types are:\n\n| Kind | Types | Values | Section |\n|---|---|---|---|\n| Integer | `I8` `I16` `I32` `I64` `I128` `I256` `I512` `I1024`, `U8` `U16` `U32` `U64` `U128` `U256` `U512` | the integers in the type's range | 6.3.1 |\n| Fixed point | `Q<i>.<f>`, such as `Q16.16` | the multiples of 2^-f in the type's range | 6.3.2 |\n| Boolean | `Bool` | `false` and `true` | 6.3.3 |\n| Array | an element type and a shape, such as `I64[8]` or `I32[2, 3]` | a fixed number of elements of the element type | 6.3.4 |\n| View | `in` or `inout` before an array type, such as `in I64[_]` | a window onto the elements of an array | 6.3.5 |\n| Struct | a name declared with `struct` | one value for each field | 6.3.6 |\n| Error set and error union | a name declared with `error`; `E!T` | the values of the set; a `T` or an error | 6.3.7 |\n| Arena, pool and handle | `Arena(T)`, `Pool(T)`, `Handle(T[])`, `Handle(T)` | an arena, a pool or a checked reference into one | 6.3.8 |\n\n   [LS-50]\n\n2. The integer types and the fixed-point types are the *numeric types*. The numeric types and `Bool` are the *scalar types*."
  },
  {
   "id": "spec-04p:types-p1",
   "edition": "SPEC-04P.2",
   "title": "6.3 Types (part 2)",
   "clauses": "IM-56",
   "url": "/specifications/spec-04p/2/#types",
   "internal": 0,
   "content": "3. <a id=\"IM-56\"></a>Two integer types, or two fixed-point types, are the same type only when their names are the same. Two struct types, or two error sets, are the same type only when they come from the same declaration, so two structs with the same fields are different types. An operator, an assignment or an argument that needs one type and is given another is diagnosed C2001 (6.6) [IM-56]."
  },
  {
   "id": "spec-04p:integer-types",
   "edition": "SPEC-04P.2",
   "title": "6.3.1 Integer types",
   "clauses": "IM-4 IM-6 IM-7 IM-9",
   "url": "/specifications/spec-04p/2/#integer-types",
   "internal": 0,
   "content": "#### 6.3.1 Integer types\n\nAn integer type holds every integer from its minimum to its maximum, and no other value. Its name is `I` for a signed type or `U` for an unsigned type, followed by its width in bits. The types of 8 to 64 bits are the usual machine integers. The *wide types*, `I128` to `I1024` and `U128` to `U512`, are integer types like the others, with larger ranges.\n\n**Syntax**\n\n```ebnf\nINT_TYPE = \"I8\" | \"I16\" | \"I32\" | \"I64\" | \"I128\" | \"I256\" | \"I512\" | \"I1024\"\n         | \"U8\" | \"U16\" | \"U32\" | \"U64\" | \"U128\" | \"U256\" | \"U512\" ;   (* spelled as IDENT *)\n```\n\n**Constraints**\n\n1. <a id=\"IM-7\"></a><a id=\"IM-9\"></a>The bounds of a `for` range shall have type `I64`, as an array index does (6.12.2). A bound of another integer type is diagnosed C2001, even when its value fits; `as I64` (6.6) converts it [IM-7, IM-9].\n\n**Semantics**\n\n2. <a id=\"IM-4\"></a><a id=\"IM-6\"></a>An integer type `T` of width `w` has the range `MIN(T)` to `MAX(T)`. For a signed type these are -2^(w-1) and 2^(w-1) - 1; for an unsigned type, 0 and 2^w - 1 [IM-4, IM-6]:\n\n| Type | `w` | `MIN(T)` | `MAX(T)` |\n|---|---:|---:|---:|\n| `I8` | 8 | -128 | 127 |\n| `I16` | 16 | -32768 | 32767 |\n| `I32` | 32 | -2147483648 | 2147483647 |\n| `I64` | 64 | -9223372036854775808 | 9223372036854775807 |\n| `I128` | 128 | -2^127 | 2^127 - 1 |\n| `I256` | 256 | -2^255 | 2^255 - 1 |\n| `I512` | 512 | -2^511 | 2^511 - 1 |\n| `I1024` | 1024 | -2^1023 | 2^1023 - 1 |\n| `U8` | 8 | 0 | 255 |\n| `U16` | 16 | 0 | 65535 |\n| `U32` | 32 | 0 | 4294967295 |\n| `U64` | 64 | 0 | 18446744073709551615 |\n| `U128` | 128 | 0 | 2^128 - 1 |\n| `U256` | 256 | 0 | 2^256 - 1 |\n| `U512` | 512 | 0 | 2^512 - 1 |\n\n3. A value of an integer type is an integer in Z, within the type's range. How a value is stored does not change its meaning (6.2.1)."
  },
  {
   "id": "spec-04p:integer-types-p1",
   "edition": "SPEC-04P.2",
   "title": "6.3.1 Integer types (part 2)",
   "clauses": "IM-11 IM-16 IM-7 IM-8 LS-51",
   "url": "/specifications/spec-04p/2/#integer-types",
   "internal": 0,
   "content": "4. <a id=\"LS-51\"></a>`T.min` and `T.max` are `MIN(T)` and `MAX(T)` as values of type `T`. Both are constant expressions (6.8) [LS-51].\n\n5. <a id=\"IM-11\"></a><a id=\"IM-16\"></a>The wide types are integer types like `I64`: they are copied by assignment and passed in any mode. Every operator of 6.7 and every conversion of 6.6 applies to them with the same meaning, the same forms and the same faults as on `I64`; only the range differs [IM-11, IM-16].\n\n6. The named operations of 7.2 are defined for every integer type, with these exceptions, each diagnosed C2103: `rotl` and `rotr` take unsigned types only; `uabs` takes a signed type and gives the unsigned type of the same width, so it is not defined for `I1024`; `mul_full` gives the type of twice the width with the same signedness, so it is not defined for `I1024` or `U512` [IM-16].\n\n7. `I64` is the *canonical word*. The length and the extents of an array, an index, the bounds and the variable of a `for` range, the result of `count`, a fuel allowance and a call-depth limit are `I64` values. A literal with no context to type it is an `I64` (6.5) [IM-7].\n\n8. <a id=\"IM-8\"></a>An implementation may hold an `I64` value in a narrower machine representation only where it has established, from facts known at translation or checked before a dispatch begins, that every value the object can take fits that representation and that no value and no fault can differ [IM-8].\n\n**Examples**\n\n9. This example shows the range of each type of 8 to 128 bits:\n\n```cint int_ranges.ci\n\"I8   {I8.min} to {I8.max}\\n\";\n\"U8   {U8.min} to {U8.max}\\n\";\n\"I16  {I16.min} to {I16.max}\\n\";\n\"U16  {U16.min} to {U16.max}\\n\";\n\"I32  {I32.min} to {I32.max}\\n\";\n\"U32  {U32.min} to {U32.max}\\n\";\n\"I64  {I64.min} to {I64.max}\\n\";\n\"U64  {U64.min} to {U64.max}\\n\";\n\"I128 {I128.min} to {I128.max}\\n\";\n```"
  },
  {
   "id": "spec-04p:integer-types-p2",
   "edition": "SPEC-04P.2",
   "title": "6.3.1 Integer types (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#integer-types",
   "internal": 0,
   "content": "```text\nI8   -128 to 127\nU8   0 to 255\nI16  -32768 to 32767\nU16  0 to 65535\nI32  -2147483648 to 2147483647\nU32  0 to 4294967295\nI64  -9223372036854775808 to 9223372036854775807\nU64  0 to 18446744073709551615\nI128 -170141183460469231731687303715884105728 to 170141183460469231731687303715884105727\n```\n\n10. A wide type holds the square of the largest `I64`, and `I256` holds its cube. The same multiplication checks its result as it does in `I64`, so four times the square, which needs 129 bits, faults:\n\n```cint wide.ci\nI128 big = I64.max as I128;\nI128 square = big * big;\n\"{square}\\n\";\nI256 cube = (square as I256) * (big as I256);\n\"{cube}\\n\";\nI128 four = square * 4;\n\"{four}\\n\";\n```\n\n```text\n85070591730234615847396907784232501249\n784637716923335095224261902710254454442933591094742482943\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> wide.ci:6:20\n   |\n 6 | I128 four = square * 4;\n   |                    ^ mul.checked.i128\n   |\n   = operation: mul.checked.i128\n   = operand-count: 2\n   = operand: I128 85070591730234615847396907784232501249\n   = operand: I128 4\n   = exact:   340282366920938463389587631136930004996\n   = limit:   I128 170141183460469231731687303715884105727\n   ...\n```\n\n11. This example shows the unsigned wide types:\n\n```cint unsigned_wide.ci\n\"U128 {U128.min} to {U128.max}\\n\";\nU256 one = 1;\nU256 top = one << 255;\n\"{top}\\n\";\nU128 a = U128.max;\n\"{a +% 1} {a +| 1 == a}\\n\";\n```\n\n```text\nU128 0 to 340282366920938463463374607431768211455\n57896044618658097711785492504343953926634992332820282019728792003956564819968\n0 true\n```\n\n12. A range bound of type `I32` is not widened to `I64`. The fix is `0..(n as I64)`:\n\n```cint canonical_word.ci\nI32 n = 3;\nfor i in 0..n {\n    \"{i}\\n\";\n}\n```\n\n```text\nerror[C2001]: type mismatch\n  --> canonical_word.ci:2:13\n   |\n 2 | for i in 0..n {\n   |             ^\n```\n\n**Notes**"
  },
  {
   "id": "spec-04p:integer-types-p3",
   "edition": "SPEC-04P.2",
   "title": "6.3.1 Integer types (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#integer-types",
   "internal": 0,
   "content": "13. In C, the width of `int` and `long` depends on the platform, and an operand narrower than `int` is promoted before arithmetic. In cint each width is fixed by the type's name, and an `I8` operand stays an `I8`: there is no promotion.\n\n14. The byte layout of integer values in storage and in fault records is given by SPEC-01P.2, and their layout at the C interface by SPEC-03P.1."
  },
  {
   "id": "spec-04p:fixed-point-types",
   "edition": "SPEC-04P.2",
   "title": "6.3.2 Fixed-point types",
   "clauses": "IM-54 IM-55 LS-36",
   "url": "/specifications/spec-04p/2/#fixed-point-types",
   "internal": 0,
   "content": "#### 6.3.2 Fixed-point types\n\nA fixed-point type holds numbers with a fixed number of binary fraction digits. `Q16.16` has 16 integer bits, counting the sign bit, and 16 fraction bits: every value is a whole multiple of 2^-16, from -32768 up to 32768 - 2^-16. A value is stored as a signed integer, its raw value, equal to the number times 2^16. The number 1.5 is stored as 98304, and the step between two neighboring values is 2^-16, which is 0.0000152587890625. Fixed point serves where a C program would use floating point for numbers of a known resolution and range, such as positions, rates and gains. Each value is an exact multiple of the resolution, and an operation that rounds does so once, by a named rounding mode: `half_even` unless the program names another.\n\n**Syntax**\n\n```ebnf\nFIXED_TYPE = \"Q\" nonzero { digit } \".\" ( \"0\" | nonzero { digit } ) ;\n```\n\n1. <a id=\"LS-36\"></a>A fixed-point type name is one token with no space inside: `Q16.16`, `Q1.15`, `Q8.0`. The number before the point is `i` and the number after it is `f` [LS-36].\n\n**Constraints**\n\n2. <a id=\"IM-55\"></a>`i + f` shall be 8, 16, 32 or 64; otherwise the name is diagnosed C2005. The grammar makes `i` at least 1 and `f` at least 0 [IM-55, LS-36].\n\n**Semantics**\n\n3. <a id=\"IM-54\"></a>`Q<i>.<f>` is a signed type. `i` counts the integer bits, the sign bit included and `f` counts the fraction bits. Its *storage type* is the signed integer type of width `w = i + f`: `I8`, `I16`, `I32` or `I64` [IM-54, IM-55].\n\n4. A value of `Q<i>.<f>` is the rational number `r / 2^f`, where the integer `r`, the value's *raw value*, is a value of the storage type. The raw value is also called the *storage integer* (3.36). The type therefore has exactly 2^w values, one for each raw value; its *resolution*, the difference between neighboring values, is 2^-f; and its range is -2^(i-1) to 2^(i-1) - 2^-f [IM-54]:"
  },
  {
   "id": "spec-04p:fixed-point-types-p1",
   "edition": "SPEC-04P.2",
   "title": "6.3.2 Fixed-point types (part 2)",
   "clauses": "IM-54 LS-51",
   "url": "/specifications/spec-04p/2/#fixed-point-types",
   "internal": 0,
   "content": "| Type | Storage type | Resolution | Least value | Greatest value |\n|---|---|---|---:|---:|\n| `Q1.15` | `I16` | 2^-15 | -1 | 1 - 2^-15 |\n| `Q8.8` | `I16` | 2^-8 | -128 | 128 - 2^-8 |\n| `Q8.0` | `I8` | 1 | -128 | 127 |\n| `Q16.16` | `I32` | 2^-16 | -32768 | 32768 - 2^-16 |\n| `Q32.32` | `I64` | 2^-32 | -2^31 | 2^31 - 2^-32 |\n| `Q4.60` | `I64` | 2^-60 | -8 | 8 - 2^-60 |\n\n5. `Q.min` and `Q.max` are the least and the greatest value of `Q`, and `Q.epsilon` is its resolution, the value whose raw value is 1. All three are constant expressions (6.8) [LS-51].\n\n6. Two fixed-point types are the same type only when both `i` and `f` are equal, as 6.3 states. `Q16.16` and `Q8.24` are different types, and `Q16.16` is a different type from its storage type `I32`. A value moves from one of these types to another only by a conversion (6.6), and the raw value of a fixed-point value is read and written with `.raw` (6.6).\n\n7. Every operation on a fixed-point value is defined on its raw value. Addition, subtraction, negation and comparison act on the raw values exactly as on the storage type, and do not round. Multiplication, division and square root compute their result in an intermediate of 2w bits and round it once to the type's resolution, by `half_even` unless the program names another mode; the rounding modes are defined in 6.7.15. As on integers, the plain operators fault when a result does not fit, the wrapping operators wrap the raw value and the saturating operators clamp it. The rules are in 6.7 and 7.2 [IM-54].\n\n**Examples**\n\n8. This example shows the number, its raw value, the resolution and the range of `Q16.16`:\n\n```cint fixed_basics.ci\nQ16.16 a = 1.5;\nQ16.16 b = -0.25;\n\"{a} is stored as {a.raw}\\n\";\n\"{b} is stored as {b.raw}\\n\";\n\"resolution {Q16.16.epsilon}\\n\";\n\"range {Q16.16.min} to {Q16.16.max}\\n\";\n```"
  },
  {
   "id": "spec-04p:fixed-point-types-p2",
   "edition": "SPEC-04P.2",
   "title": "6.3.2 Fixed-point types (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#fixed-point-types",
   "internal": 0,
   "content": "```text\n1.5 is stored as 98304\n-0.25 is stored as -16384\nresolution 0.0000152587890625\nrange -32768.0 to 32767.9999847412109375\n```\n\n9. Formats trade range for resolution. `Q8.0` holds the integers of `I8`:\n\n```cint fixed_formats.ci\n\"Q1.15:  {Q1.15.min} to {Q1.15.max}, step {Q1.15.epsilon}\\n\";\n\"Q8.8:   {Q8.8.min} to {Q8.8.max}, step {Q8.8.epsilon}\\n\";\n\"Q8.0:   {Q8.0.min} to {Q8.0.max}, step {Q8.0.epsilon}\\n\";\n\"Q32.32: step {Q32.32.epsilon}\\n\";\n```\n\n```text\nQ1.15:  -1.0 to 0.999969482421875, step 0.000030517578125\nQ8.8:   -128.0 to 127.99609375, step 0.00390625\nQ8.0:   -128.0 to 127.0, step 1.0\nQ32.32: step 0.00000000023283064365386962890625\n```\n\n10. A number that is not a multiple of the resolution has no exact value in the type. The decimal 0.1 is one: written with a `round` clause (6.4.6), it takes the nearest value, which is closer in `Q16.16` than in `Q8.8`:\n\n```cint fixed_grid.ci\nQ16.16 tenth = 0.1 round half_even;\nQ8.8 coarse = 0.1 round half_even;\n\"{tenth} (raw {tenth.raw})\\n\";\n\"{coarse} (raw {coarse.raw})\\n\";\n```\n\n```text\n0.100006103515625 (raw 6554)\n0.1015625 (raw 26)\n```\n\n11. `Q17.16` would need 33 bits of storage:\n\n```cint fixed_name.ci\nQ17.16 x = 1.0;\n\"{x}\\n\";\n```\n\n```text\nerror[C2005]: fraction, fixed-point, enum literal, or rounding rule\n  --> fixed_name.ci:1:1\n   |\n 1 | Q17.16 x = 1.0;\n   | ^\n```\n\n**Notes**\n\n12. Some documentation names a fixed-point format by its fraction bits alone, and calls `Q1.15` \"Q15\". A cint type name always gives both numbers, and `i` includes the sign bit.\n\n13. `cint-core-1` has no unsigned fixed-point type and no fixed-point type wider than 64 bits.\n\n14. ISO C has no fixed-point type, and a C program that needs one scales an integer by hand. A `Q` type is that scaled integer with the scale in its type, so the compiler keeps track of the scale and of every rounding."
  },
  {
   "id": "spec-04p:bool",
   "edition": "SPEC-04P.2",
   "title": "6.3.3 Bool",
   "clauses": "IM-10 LS-135 LS-50",
   "url": "/specifications/spec-04p/2/#bool",
   "internal": 0,
   "content": "#### 6.3.3 Bool\n\n`Bool` is the type of conditions and of the results of comparisons. It has two values, `false` and `true`. It is not an integer type: an integer does not become a `Bool`, and a `Bool` takes part in no arithmetic.\n\n**Syntax**\n\n```ebnf\nbool_literal = \"false\" | \"true\" ;\n```\n\nThe type is written `Bool`, one of the alternatives of `base_type` (A.5).\n\n**Constraints**\n\n1. <a id=\"IM-10\"></a>The condition of `if`, `while` and `for`, the first operand of `?:` and the operands of `&&`, `||` and `!` shall have type `Bool`. An integer in one of these places is diagnosed C2002; a comparison such as `n != 0` gives a `Bool` [IM-10, LS-135].\n\n2. <a id=\"LS-50\"></a>`Bool` is not a numeric type. An arithmetic or bitwise operator with a `Bool` operand is diagnosed C2103. Of the comparisons, only `==` and `!=` apply to `Bool` (6.7.10) [LS-50].\n\n**Semantics**\n\n3. `Bool` has the two values `false` and `true`, written as the literals `false` and `true`. In storage, a `Bool` occupies one byte, which holds 0 for `false` and 1 for `true` [IM-10, LS-50].\n\n4. A `Bool` converts to an integer type with `as`, and no conversion goes from an integer to `Bool`, as 6.6 states.\n\n**Examples**\n\n5. A comparison gives a `Bool`, and `as` turns a `Bool` into 0 or 1:\n\n```cint bool.ci\nI64 n = 3;\nBool odd = n % 2 != 0;\nif (odd && n > 2) {\n    \"odd and above 2\\n\";\n}\n\"{odd} {odd as I64} {(!odd) as U8}\\n\";\n```\n\n```text\nodd and above 2\ntrue 1 0\n```\n\n6. An integer is not a condition:\n\n```cint bool_condition.ci\nI64 n = 3;\nif (n) {\n    \"nonzero\\n\";\n}\n```\n\n```text\nerror[C2002]: condition is not `Bool`\n  --> bool_condition.ci:2:5\n   |\n 2 | if (n) {\n   |     ^\n```\n\n**Notes**\n\n7. In C, any scalar value is a condition and a comparison gives an `int`. In cint, `if (n)` is diagnosed and a comparison gives a `Bool`."
  },
  {
   "id": "spec-04p:array-types",
   "edition": "SPEC-04P.2",
   "title": "6.3.4 Array types",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#array-types",
   "internal": 0,
   "content": "#### 6.3.4 Array types\n\nAn array type is an element type followed by a shape. Declaring arrays, their extents and initializers, indexing, slicing and copying are specified in 6.12.\n\n**Semantics**\n\n1. An array type is an element type followed by a *shape*: a list of *extents* in brackets, one for each dimension. `I64[8]` holds 8 `I64` values, and `I32[2, 3]` holds 2 rows of 3 `I32` values.\n2. The number of extents is the array's *rank*, from 1 to 4 (6.12.1). The element type is a scalar type, a struct type, an error set or a handle type.\n3. An array holds its elements in row-major order, so the last index varies fastest.\n\n**Examples**\n\n4. This example shows the elements of `I32[2, 3]` in storage order, read through a rank-1 view of the same elements (`reshape`, 7.4):\n\n```cint array_types.ci\nvoid show() {\n    I32[2, 3] m = [[1, 2, 3], [4, 5, 6]];\n    in I32[_] flat = reshape(m, 6);\n    for k in 0..6 {\n        if (k > 0) {\n            \" \";\n        }\n        \"{flat[k]}\";\n    }\n    \"\\n\";\n}\nshow();\n```\n\n```text\n1 2 3 4 5 6\n```\n\n**Notes**\n\n5. In C, `int m[2][3]` is an array of arrays and `m[i][j]` indexes twice. In cint, `I32[2, 3]` is one array of rank 2, and its element is `m[i, j]` (6.12.2)."
  },
  {
   "id": "spec-04p:view-types",
   "edition": "SPEC-04P.2",
   "title": "6.3.5 View types",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#view-types",
   "internal": 0,
   "content": "#### 6.3.5 View types\n\nA view type is an array type with a permission in front of it. Declaring views is specified in 6.9.1, passing them in 6.9.5 and 6.12.4, and taking them by slicing in 6.12.3.\n\n**Syntax**\n\n```ebnf\nview_decl = ( \"in\" | \"inout\" ) type IDENT \"=\" expr \";\" ;\nparam     = [ \"in\" | \"inout\" ] type IDENT ;\n```\n\nView types appear in a `view_decl` (6.9.1) and in a `param` (6.9.5), each with a `type` that has a `shape`.\n\n**Semantics**\n\n1. A view type is an array type with a permission in front of it: `in I64[_]` is a read-only view of rank 1, and `inout I32[_, _]` a view of rank 2 that may also be written. The extent `_` accepts any extent.\n2. A view holds no elements of its own: it refers to the elements of an array or of an arena allocation, and reading or writing through it reads or writes those elements.\n3. A view may be a local variable, a parameter or an argument, but it cannot be stored in a struct, an array or a module-level variable.\n\n**Examples**\n\n4. This example takes a read-only view of the first three elements and a writable view of the rest. The write through `tail` changes `a`:\n\n```cint view_types.ci\nI64 total[n](in I64[n] xs) {\n    I64 s = 0;\n    for i in 0..n {\n        s += xs[i];\n    }\n    return s;\n}\nI64 run() {\n    I64[5] a = [1, 2, 3, 4, 5];\n    in I64[_] head = a[0..3];\n    inout I64[_] tail = a[3..];\n    tail[0] = 40;\n    return total(head) * 1000 + total(a);\n}\n\"{run()}\\n\";\n```\n\n```text\n6051\n```"
  },
  {
   "id": "spec-04p:struct-types",
   "edition": "SPEC-04P.2",
   "title": "6.3.6 Struct types",
   "clauses": "LS-313 LS-314 LS-78 LS-79",
   "url": "/specifications/spec-04p/2/#struct-types",
   "internal": 0,
   "content": "#### 6.3.6 Struct types\n\nA struct type is a named record: a fixed list of fields, each with a name and a type. A struct value holds one value for each field. A struct is declared with `struct` and its values are made with a constructor (6.9.6).\n\n**Constraints**\n\n1. <a id=\"LS-79\"></a>A field shall not have an `Arena` or `Pool` type (C2051), and the extents of an array field shall be constant (C6004). A view type cannot be written as the type of a field (C1050) [LS-79].\n\n2. <a id=\"LS-313\"></a>A struct shall not contain itself, directly or through the fields or elements of its fields: C2055 at the field's name [LS-313].\n\n3. Struct values are not compared: `==`, `!=` and the ordering comparisons with struct operands are diagnosed C2103 [LS-313].\n\n**Semantics**\n\n4. A field may have a scalar type, an array type with constant extents, another struct type, an error set or a `Handle` type [LS-79, LS-314].\n\n5. <a id=\"LS-78\"></a>A struct value is a value, as an integer is. Assignment, initialization and passing as an `in` argument copy every field, the elements of array fields included, and a change made to the copy afterward does not reach the original [LS-78].\n\n**Examples**\n\n6. This example shows a struct with a struct field that holds an array. `b` is a copy of `a`, so the write to `b` leaves `a` unchanged; a struct declared without an initializer has every field 0:\n\n```cint struct_types.ci\nstruct Vec3 {\n    I32[3] c;\n}\nstruct Body {\n    I64 id;\n    Vec3 pos;\n    Bool active;\n}\nvoid main() {\n    Body a;\n    a.id = 7;\n    a.pos.c[0] = 1;\n    Body b = a;\n    b.pos.c[0] = 100;\n    \"{a.pos.c[0]} {b.pos.c[0]} {b.id} {b.active}\\n\";\n}\n```\n\n```text\n1 100 7 false\n```\n\n7. An arena is not a field:\n\n```cint struct_arena_field.ci\nstruct Scratch {\n    Arena(I64) a;\n}\nvoid main() {\n    \"unreached\\n\";\n}\n```"
  },
  {
   "id": "spec-04p:struct-types-p1",
   "edition": "SPEC-04P.2",
   "title": "6.3.6 Struct types (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#struct-types",
   "internal": 0,
   "content": "```text\nerror[C2051]: type rule\n  --> struct_arena_field.ci:2:5\n   |\n 2 |     Arena(I64) a;\n   |     ^\n```\n\n**Notes**\n\n8. The layout of a struct at the C interface, which a host program sees, is given by SPEC-03P.1."
  },
  {
   "id": "spec-04p:error-sets-and-error-unions",
   "edition": "SPEC-04P.2",
   "title": "6.3.7 Error sets and error unions",
   "clauses": "LS-97",
   "url": "/specifications/spec-04p/2/#error-sets-and-error-unions",
   "internal": 0,
   "content": "#### 6.3.7 Error sets and error unions\n\nAn error set is a type whose values name the expected ways an operation can fail, such as `ParseError.bad_digit`. An error union `E!T` is the result type of a function that returns either a value of type `T` or a value of the error set `E`. Errors are ordinary values that the program handles; they are not faults (5.2.3). Returning, propagating and handling errors with `return`, `try` and `catch` is specified in 6.11.\n\n**Syntax**\n\n```ebnf\nerror_decl  = \"error\" IDENT [ \":\" INT_TYPE ]\n              ( \"{\" IDENT { \",\" IDENT } [ \",\" ] \"}\"\n              | \"=\" qualified { \"|\" qualified } \";\" ) ;\nunion_type  = qualified \"!\" ( \"void\" | base_type ) ;\nqualified   = IDENT [ \".\" IDENT ] ;\n```\n\nA `union_type` appears only as the result type of a function (6.9.4).\n\n**Constraints**\n\n1. The constraints on the underlying type of an error set and on the operands of a combined set (paragraph 9) are stated in 6.9.7.\n\n2. A call of a function whose result is an error union shall be consumed where it is made, as 6.11.2 states (C2040).\n\n3. <a id=\"LS-97\"></a>The short form `.name`, used where the set is known, and the form `C.name`, for a combined set `C`, name a value only when exactly one member set declares `name`. When several do, both forms are diagnosed C2044, and the value is written with the set that declares it, such as `QueueError.full` [LS-97].\n\n4. A value of an error set converts to an error set that holds all of its values: at `try`, at `return`, in an assignment or an initializer, as an argument, and as an operand of `==` or `!=` whose other operand has the larger set. It does not convert the other way: that is diagnosed C2042 at `try` and at `return`, and C2001 elsewhere [LS-97]."
  },
  {
   "id": "spec-04p:error-sets-and-error-unions-p1",
   "edition": "SPEC-04P.2",
   "title": "6.3.7 Error sets and error unions (part 2)",
   "clauses": "LS-314 LS-91 LS-92 LS-93",
   "url": "/specifications/spec-04p/2/#error-sets-and-error-unions",
   "internal": 0,
   "content": "5. <a id=\"LS-91\"></a><a id=\"LS-314\"></a>Error-set values are compared only with `==` and `!=`; an ordering comparison is diagnosed C2103. No error value is 0, so an array or struct variable that holds error-set values, directly or inside a field or an element, needs an initializer: a declaration without one is diagnosed C2054. A variable of an error-set type, like every scalar variable, needs one too (C2050, 6.9.1) [LS-91, LS-314].\n\n**Semantics**\n\n6. <a id=\"LS-92\"></a>`error Name { a, b, c }` declares an error set whose values are `Name.a`, `Name.b` and `Name.c`. Where the set is known from the context, a value may be written `.a` [LS-92].\n\n7. <a id=\"LS-93\"></a>The values of a set are numbered from 1 in the order of declaration; the number of a value is its *tag*, and 0 means success. The numbers are stored in the set's underlying type, `U16` unless the declaration names another. Adding a value at the end of a set keeps the numbers of the earlier values. An error value is its number alone and carries no other data [LS-93].\n\n8. What a value of an error union `E!T` holds is stated in 6.11.2."
  },
  {
   "id": "spec-04p:error-sets-and-error-unions-p2",
   "edition": "SPEC-04P.2",
   "title": "6.3.7 Error sets and error unions (part 3)",
   "clauses": "LS-314 LS-96 LS-97",
   "url": "/specifications/spec-04p/2/#error-sets-and-error-unions",
   "internal": 0,
   "content": "9. A *combined set*, `error C = A | B;`, or `error C : U32 = A | B;` with a declared underlying type, holds every value of each of its operand sets. Its values are numbered by concatenation: the values of the first operand keep their numbers and the values of the second follow, in their own order; a set that appears twice is included once, at its first position. Each declared set keeps its own numbering, and a value keeps its identity when it converts from one set to another. With `error IoError { closed, full }`, `error ParseError { empty, bad_digit, too_large }` and `error IoOrParse = IoError | ParseError;`, `IoOrParse` numbers `IoError.closed` 1, `IoError.full` 2, `ParseError.empty` 3, `ParseError.bad_digit` 4 and `ParseError.too_large` 5. `ParseError.bad_digit` is one value, which a `ParseError` holds as 2 and an `IoOrParse` as 4 [LS-97].\n\n10. An error-set value is an ordinary value. A variable, a struct field, an array element, a parameter and a function result may have an error-set type. A `switch` over an error-set value without `default` lists every value of the set (6.10.5). Error unions are function results only, so every error is handled or discarded at its call [LS-314].\n\n11. <a id=\"LS-96\"></a>Two error sets are built in. `ArithError`, the set of the result forms and of the conversion `as?` (6.6, 6.7.12), has the four values `overflow`, `div_zero`, `shift` and `narrow`; `AllocError` is the set of `alloc_result` and `insert_result` (6.14) [LS-96].\n\n**Examples**\n\n12. A function that returns a digit or an error, a function whose combined set holds `ParseError`, and the three ways to consume a call:\n\n```cint error_types.ci\nerror ParseError { empty, bad_digit, too_large }\nerror IoError : U8 { closed, full }\nerror IoOrParse = IoError | ParseError;\n\nParseError!I64 digit(I64 c) {\n    if (c < 48 || c > 57) {\n        return .bad_digit;\n    }\n    return c - 48;\n}"
  },
  {
   "id": "spec-04p:error-sets-and-error-unions-p3",
   "edition": "SPEC-04P.2",
   "title": "6.3.7 Error sets and error unions (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#error-sets-and-error-unions",
   "internal": 0,
   "content": "IoOrParse!I64 twice(I64 c) {\n    I64 d = try digit(c);\n    return d * 2;\n}\n\nvoid main() {\n    I64 a = digit(55) catch -1;\n    I64 b = digit(65) catch -1;\n    \"{a} {b}\\n\";\n    I64 c = twice(52) catch -1;\n    \"{c}\\n\";\n    I64 d = twice(120) catch (e) {\n        switch (e) {\n            case IoError.closed, IoError.full: { \"io\\n\"; }\n            case ParseError.empty, ParseError.too_large: { \"other\\n\"; }\n            case ParseError.bad_digit: { \"bad digit\\n\"; }\n        }\n        return;\n    };\n    \"{d}\\n\";\n}\n```\n\n```text\n7 -1\n8\nbad digit\n```\n\n13. This example shows error-set values in an array and in a struct field, each with an initializer:\n\n```cint error_values.ci\nerror ParseError { empty, bad_digit }\nstruct Rec {\n    I64 n;\n    ParseError why;\n}\nvoid main() {\n    ParseError[2] es = [ParseError.bad_digit, .empty];\n    Rec r = Rec(4, .bad_digit);\n    \"{es[0] == r.why} {es[1] == ParseError.empty}\\n\";\n}\n```\n\n```text\ntrue true\n```\n\n14. Both sets of `IoOrQueue` declare `full`, so the short form names neither:\n\n```cint error_ambiguous.ci\nerror IoError { closed, full }\nerror QueueError { full, stalled }\nerror IoOrQueue = IoError | QueueError;\nIoOrQueue!void push(I64 n) {\n    if (n > 3) {\n        return .full;\n    }\n    return;\n}\nvoid main() {\n    _ = push(5);\n}\n```\n\n```text\nerror[C2044]: type rule\n  --> error_ambiguous.ci:6:16\n   |\n 6 |         return .full;\n   |                ^\n```\n\n15. An array of an error set has no value to start from:\n\n```cint error_zero_fill.ci\nerror ParseError { empty, bad_digit }\nvoid main() {\n    ParseError[3] es;\n    \"{es[0] == ParseError.empty}\\n\";\n}\n```\n\n```text\nerror[C2054]: type rule\n  --> error_zero_fill.ci:3:5\n   |\n 3 |     ParseError[3] es;\n   |     ^\n```\n\n**Notes**"
  },
  {
   "id": "spec-04p:error-sets-and-error-unions-p4",
   "edition": "SPEC-04P.2",
   "title": "6.3.7 Error sets and error unions (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#error-sets-and-error-unions",
   "internal": 0,
   "content": "16. A caller that needs more detail than an error value carries passes an argument for it, such as an `inout` struct. An error-set type for array elements and fields lets a program record why each of many inputs failed."
  },
  {
   "id": "spec-04p:arena-pool-and-handle-types",
   "edition": "SPEC-04P.2",
   "title": "6.3.8 Arena, pool and handle types",
   "clauses": "LS-50",
   "url": "/specifications/spec-04p/2/#arena-pool-and-handle-types",
   "internal": 0,
   "content": "#### 6.3.8 Arena, pool and handle types\n\nThe arena, pool and handle types name storage that a program sets aside once and reuses. An *arena* is a region of a fixed number of elements of one type, from which runs of elements are taken and then released together. A *pool* is a fixed number of slots of one type, taken and released one at a time. A *handle* is a checked reference into one of them: using a handle whose storage has been released faults instead of reading other data. Their declarations, operations and faults are specified in 6.14.\n\n**Semantics**\n\n1. The type forms are these [LS-50]:\n\n| Form | Names |\n|---|---|\n| `Arena(T, capacity)` | in a module-level declaration, an arena of `capacity` elements of type `T` |\n| `Arena(T)` | the type of an arena parameter or of a child arena |\n| `Pool(T, capacity)` | in a module-level declaration, a pool of `capacity` slots of type `T` |\n| `Pool(T)` | the type of a pool parameter |\n| `Handle(T[])` | a run of elements taken from an arena of `T` |\n| `Handle(T)` | one slot of a pool of `T` |\n\n**Examples**\n\n2. This example shows a run of 4 elements from an arena and a slot of a pool:\n\n```cint memory_types.ci\nstruct Body {\n    I64 id;\n    I64 mass;\n}\nArena(I64, 64) scratch;\nPool(Body, 8) bodies;\nvoid main() {\n    Handle(I64[]) h = scratch.alloc(4);\n    scratch[h][2] = 7;\n    Handle(Body) b = bodies.insert(Body(1, 50));\n    bodies[b].mass += 5;\n    \"{scratch[h][2]} {len(scratch[h])} {bodies[b].mass}\\n\";\n}\n```\n\n```text\n7 4 55\n```"
  },
  {
   "id": "spec-04p:lexical-elements",
   "edition": "SPEC-04P.2",
   "title": "6.4 Lexical elements",
   "clauses": "LS-296",
   "url": "/specifications/spec-04p/2/#lexical-elements",
   "internal": 0,
   "content": "### 6.4 Lexical elements\n\nThe source text of a module is read as a sequence of tokens: identifiers, keywords, literals and punctuators, separated by white space and comments. Each lexical subclause below gives its part of the lexical grammar; Annex A collects them [LS-296]."
  },
  {
   "id": "spec-04p:source-text",
   "edition": "SPEC-04P.2",
   "title": "6.4.1 Source text",
   "clauses": "LS-4 LS-5 LS-6 LS-7",
   "url": "/specifications/spec-04p/2/#source-text",
   "internal": 0,
   "content": "#### 6.4.1 Source text\n\nSource text is UTF-8. Outside literals and comments it is ASCII. A small set of characters that can make text display differently from how it is read is rejected everywhere.\n\n**Constraints**\n\n1. <a id=\"LS-4\"></a>Source text shall be valid UTF-8 without a byte-order mark. A byte-order mark at the start of the file, an invalid UTF-8 sequence, or a byte 0x00 anywhere in the file is C1002 [LS-4].\n2. <a id=\"LS-5\"></a>Outside string literals, character literals and comments, only ASCII characters may appear. Any other character is C1013 [LS-5].\n3. <a id=\"LS-6\"></a>The following characters shall not appear unescaped anywhere, comments and string literals included. Each is C1003, reported at the character [LS-4, LS-6]:\n   - the bidirectional formatting characters U+202A to U+202E and U+2066 to U+2069;\n   - the separators U+2028 and U+2029, which some editors display as line breaks;\n   - every code point with the Unicode property `Default_Ignorable_Code_Point`, such as U+200B, U+200D, U+2060 and U+FEFF after the start of the file.\n4. <a id=\"LS-7\"></a>A control character other than horizontal tab (U+0009), line feed (U+000A), and a carriage return immediately followed by a line feed shall not appear unescaped (C1004) [LS-7].\n\n**Semantics**\n\n5. A character excluded by paragraph 3 may be written in a string literal as an escape, such as `\\u{200D}` (6.4.8) [LS-6].\n\n**Examples**\n\n6. The zero-width space U+200B, written as an escape, is three bytes of UTF-8 in the string:\n\n```cint zero_width.ci\nI64 size_of[n](in U8[n] s) {\n    return n;\n}\nI64 k = size_of(\"a\\u{200B}b\");\n\"{k}\\n\";\n```\n\n```text\n5\n```\n\n**Notes**"
  },
  {
   "id": "spec-04p:source-text-p1",
   "edition": "SPEC-04P.2",
   "title": "6.4.1 Source text (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#source-text",
   "internal": 0,
   "content": "7. Rejecting the bidirectional and invisible characters rules out the forms of the attack known as Trojan Source (CVE-2021-42574) that rely on those characters, in which code displays differently from how a compiler reads it. Characters that look alike but differ, inside string literals and comments, are not rejected."
  },
  {
   "id": "spec-04p:lines-columns-and-white-space",
   "edition": "SPEC-04P.2",
   "title": "6.4.2 Lines, columns and white space",
   "clauses": "LS-10 LS-11 LS-12 LS-9",
   "url": "/specifications/spec-04p/2/#lines-columns-and-white-space",
   "internal": 0,
   "content": "#### 6.4.2 Lines, columns and white space\n\nA line ends at a line feed, or at a carriage return followed by one. Positions in diagnostics and fault reports count lines and columns from 1.\n\n**Constraints**\n\n1. <a id=\"LS-9\"></a>A line ends at a line feed (LF) or at a carriage return followed by a line feed (CR LF). A carriage return not followed by a line feed is C1004 [LS-9].\n\n**Semantics**\n\n2. <a id=\"LS-10\"></a>Lines are numbered from 1. Columns are numbered from 1 and count Unicode scalar values from the start of the line; a tab counts as one column [LS-10].\n3. <a id=\"LS-11\"></a>White space, which is spaces, tabs and line ends, separates tokens and has no other meaning. Indentation has no meaning [LS-11].\n4. <a id=\"LS-12\"></a>Tokens are formed by *maximal munch*: at each point, the longest sequence of characters that forms a valid token is taken. `a+%b` is `a`, `+%`, `b`, and `x<<%2` is `x`, `<<%`, `2` [LS-12].\n\n**Examples**\n\n5. In the second line, a tab comes before `U8` and another after `=`. The `+` is at the eleventh column, counting each tab as one, and the caret line repeats the tabs so that the caret stands under the `+` (5.1.3):\n\n```cint tabs.ci\nU8 a = 200;\n\tU8 b =\ta + a;\n\"{b}\\n\";\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> tabs.ci:2:11\n   |\n 2 | \tU8 b =\ta + a;\n   | \t      \t  ^ add.checked.u8\n   ...\n```\n\n6. Maximal munch reads `a--b` as `a`, `--`, `b`, and `--` cannot appear in an expression. With a space, `a - -b` subtracts a negated `b`:\n\n```cint munch.ci\nI64 a = 5;\nI64 b = 2;\nI64 c = a - -b;\nI64 d = a--b;\n\"{c} {d}\\n\";\n```\n\n```text\nerror[C1042]: `++` or `--` used as an expression\n  --> munch.ci:4:10\n   |\n 4 | I64 d = a--b;\n   |          ^\n```"
  },
  {
   "id": "spec-04p:comments",
   "edition": "SPEC-04P.2",
   "title": "6.4.3 Comments",
   "clauses": "LS-13 LS-14",
   "url": "/specifications/spec-04p/2/#comments",
   "internal": 0,
   "content": "#### 6.4.3 Comments\n\nA comment is text for the reader, and counts as white space. A line comment runs to the end of its line; a block comment runs to its matching end, and block comments nest.\n\n**Syntax**\n\n```ebnf\nLINE_COMMENT  = \"//\" { line_char } ;\nBLOCK_COMMENT = \"/*\" { BLOCK_COMMENT | any_char } \"*/\" ;\nline_char     = (* any Unicode scalar value except a line end *) ;\nany_char      = (* any Unicode scalar value *) ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-14\"></a>A block comment without its matching `*/` is C1005, reported at its `/*` [LS-14].\n\n**Semantics**\n\n2. <a id=\"LS-13\"></a>`//` begins a comment that ends at the end of the line. `/*` begins a comment that ends at the matching `*/` [LS-13].\n3. Block comments nest: `/* a /* b */ c */` is one comment [LS-14].\n4. `///` begins a line comment like `//` [LS-14].\n\n**Examples**\n\n5. This example shows comments of each kind:\n\n```cint comments.ci\n/* outer /* inner */ still a comment */\n// line comment\nI64 x = 7 /* inside an expression */ + 1; // after a statement\n/// Doubles a value.\nI64 twice(I64 v) {\n    return 2 * v;\n}\n\"{twice(x)}\\n\";\n```\n\n```text\n16\n```\n\n**Notes**\n\n6. A comment that begins with `///` is a documentation comment, which a tool may attach to the declaration that follows it.\n7. In C, block comments do not nest, so commenting out code that holds a comment ends the comment early. In cint the outer comment continues to its own `*/`."
  },
  {
   "id": "spec-04p:identifiers-and-keywords",
   "edition": "SPEC-04P.2",
   "title": "6.4.4 Identifiers and keywords",
   "clauses": "LS-15 LS-17 LS-18 LS-19",
   "url": "/specifications/spec-04p/2/#identifiers-and-keywords",
   "internal": 0,
   "content": "#### 6.4.4 Identifiers and keywords\n\nAn identifier names something the program declares. Keywords are reserved and cannot be names. The names of the built-in types and functions are not keywords, but they are declared already and cannot be declared again.\n\n**Syntax**\n\n```ebnf\nletter = \"A\" .. \"Z\" | \"a\" .. \"z\" | \"_\" ;\ndigit  = \"0\" .. \"9\" ;\nIDENT  = letter { letter | digit } ;    (* not a KEYWORD; at most 255 bytes *)\n```\n\n**Constraints**\n\n1. <a id=\"LS-15\"></a>An identifier is a letter or `_` followed by letters, digits and `_`. Identifiers are case-sensitive and at most 255 bytes long; a longer identifier is C1012 on every implementation [LS-15].\n2. <a id=\"LS-17\"></a>A name that is a capital `I`, `U`, `Q` or `T` followed only by digits is reserved for type names, whether or not a type of that name exists, and is C1010 when declared: `Q32` is not a valid variable name [LS-17].\n3. <a id=\"LS-18\"></a><a id=\"LS-19\"></a>These words are keywords and shall not be used as identifiers. Where a name is expected, a keyword is C4012 [LS-18, LS-19]:\n\n```text\nas          assert      break       by          case        catch\nconst       continue    default     defer       distinct    do\nelse        enum        errdefer    error       expect_fault\nexport      fallthrough false       for         if          import\nin          in_place    inout       kernel      out         over\nprofile     reduce      return      schedule    secret      static_assert\nstruct      switch      test        true        try         type\nvar         void        where       while\n```\n\n   No construct of this edition uses eight of these keywords; they are reserved, and A.2, paragraph 7 names them."
  },
  {
   "id": "spec-04p:identifiers-and-keywords-p1",
   "edition": "SPEC-04P.2",
   "title": "6.4.4 Identifiers and keywords (part 2)",
   "clauses": "LS-20 LS-21 LS-22 LS-23 LS-297",
   "url": "/specifications/spec-04p/2/#identifiers-and-keywords",
   "internal": 0,
   "content": "4. <a id=\"LS-22\"></a>The names of the built-in functions, such as `len`, `min`, `sum` and `count`, are not keywords, but they are visible in every module without an import, as if declared before its first line, and shall not be declared again (C3001). 7.1 lists them [LS-22].\n5. <a id=\"LS-23\"></a><a id=\"LS-297\"></a>A fault name, such as `E_OVERFLOW` in a test header (6.15.3), is an identifier checked against the fault codes of 5.2.3. A name that begins `E_` and is not one of them is C1011 [LS-23, LS-297].\n\n**Semantics**\n\n6. <a id=\"LS-20\"></a>`round` and `at` are identifiers that the grammar matches by spelling in the positions where it names them: `round` right after the target type of a conversion (`x as I32 round floor`) and right after a fraction literal (`0.1 round half_even`), and `at` in a test header (6.15.3). Elsewhere each is an ordinary identifier [LS-20, LS-297].\n7. <a id=\"LS-21\"></a>The built-in type names are `I8`, `I16`, `I32`, `I64`, `U8`, `U16`, `U32`, `U64`, `I128`, `I256`, `I512`, `I1024`, `U128`, `U256`, `U512`, every fixed-point name `Q<i>.<f>`, `Bool`, `Arena`, `Pool` and `Handle`, which 6.3 defines. The built-in error set is `ArithError` (6.3.7). The name `Str` is reserved and names no type in this edition [LS-21].\n8. Every built-in type name starts with a capital letter [LS-21].\n\n**Examples**\n\n9. Identifiers are case-sensitive, and `round` is an ordinary name outside a rounding clause:\n\n```cint names.ci\nI64 count2 = 2;\nI64 Count2 = 3;\nI64 _tmp = 4;\nI64 round = 5;\n\"{count2} {Count2} {_tmp} {round}\\n\";\n```\n\n```text\n2 3 4 5\n```\n\n10. This example shows a name of the reserved form:\n\n```cint reserved_q.ci\nI64 Q32 = 1;\n\"{Q32}\\n\";\n```\n\n```text\nerror[C1010]: invalid name\n  --> reserved_q.ci:1:5\n   |\n 1 | I64 Q32 = 1;\n   |     ^\n```\n\n11. This example shows a keyword where a name is expected:\n\n```cint keyword_name.ci\nI64 kernel = 1;\n\"{kernel}\\n\";\n```"
  },
  {
   "id": "spec-04p:identifiers-and-keywords-p2",
   "edition": "SPEC-04P.2",
   "title": "6.4.4 Identifiers and keywords (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#identifiers-and-keywords",
   "internal": 0,
   "content": "```text\nerror[C4012]: statement form not permitted\n  --> keyword_name.ci:1:1\n   |\n 1 | I64 kernel = 1;\n   | ^\n```\n\n12. A built-in function name cannot be declared again:\n\n```cint builtin_name.ci\nI64 count = 3;\n\"{count}\\n\";\n```\n\n```text\nerror[C3001]: duplicate name\n  --> builtin_name.ci:1:5\n   |\n 1 | I64 count = 3;\n   |     ^\n```\n\n13. This example shows a misspelled fault name:\n\n```cint fault_name.ci\ntest \"bad name\" expect_fault E_OVERFLW {\n    I8 a = 127;\n    a += 1;\n}\n\"x\\n\";\n```\n\n```text\nerror[C1011]: invalid name\n  --> fault_name.ci:1:30\n   |\n 1 | test \"bad name\" expect_fault E_OVERFLW {\n   |                              ^\n```\n\n**Notes**\n\n14. Identifiers are ASCII only. C and C++ admit other characters in identifiers; cint does not, which keeps out the names that look alike because of characters outside ASCII.\n15. The examples of this document name declared types with a capital letter too, such as a struct `Body` or an error set `IoError`; the grammar does not require it."
  },
  {
   "id": "spec-04p:integer-literals",
   "edition": "SPEC-04P.2",
   "title": "6.4.5 Integer literals",
   "clauses": "LS-25 LS-26 LS-27 LS-29 LS-31",
   "url": "/specifications/spec-04p/2/#integer-literals",
   "internal": 0,
   "content": "#### 6.4.5 Integer literals\n\nAn integer literal writes an exact integer in decimal, hexadecimal, binary, octal or balanced ternary. It has no type of its own: it takes one from where it is used (6.5). A minus sign written before a literal is part of the literal, so `-128` is one value, not the negation of 128.\n\n**Syntax**\n\n```ebnf\nINT_LIT     = DEC_INT | HEX_INT | OCT_INT | BIN_INT | TERN_INT ;\nDEC_INT     = \"0\" | nonzero { [ sep ] digit } ;\nHEX_INT     = \"0x\" hexdigit { [ sep ] hexdigit } ;\nOCT_INT     = \"0o\" octdigit { [ sep ] octdigit } ;\nBIN_INT     = \"0b\" bindigit { [ sep ] bindigit } ;\nTERN_INT    = \"0t\" terndigit { [ sep ] terndigit } ;\nnonzero     = \"1\" .. \"9\" ;\nhexdigit    = digit | \"a\" .. \"f\" | \"A\" .. \"F\" ;\noctdigit    = \"0\" .. \"7\" ;\nbindigit    = \"0\" | \"1\" ;\nterndigit   = \"N\" | \"0\" | \"P\" ;\nsep         = \"_\" ;                                (* only between two digits *)\nneg_literal = \"-\" ( INT_LIT | CHAR_LIT | FRAC_LIT [ round_clause ] ) ;\n```\n\n`CHAR_LIT` is defined in 6.4.7, `FRAC_LIT` in 6.4.6 and `round_clause` in 6.7.15.\n\n**Constraints**\n\n1. <a id=\"LS-25\"></a>The prefix letter is lower case: `0X1F` is C1020 [LS-25].\n2. <a id=\"LS-26\"></a>A single `_` may stand between two digits. It shall not lead, trail, follow the prefix or repeat: `1__0`, `1_` and `0x_1F` are C1021, and `_1` is an identifier [LS-26].\n3. <a id=\"LS-27\"></a>A decimal literal of more than one digit shall not begin with `0`: `007` is C1022. A lone `0` is decimal [LS-27].\n4. A prefix with no digits after it, or a digit outside the prefix's radix, such as `0x`, `0b102` or `0o8`, is C1024.\n5. <a id=\"LS-31\"></a>The magnitude of a literal shall be at most `2^4096 - 1`. A larger literal is C1023, reported at its first character, on every implementation; it is never truncated [LS-31].\n6. <a id=\"LS-29\"></a>There are no type suffixes [LS-29].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:integer-literals-p1",
   "edition": "SPEC-04P.2",
   "title": "6.4.5 Integer literals (part 2)",
   "clauses": "IM-19 IM-20 IM-25 LS-24 LS-28 LS-29 LS-30",
   "url": "/specifications/spec-04p/2/#integer-literals",
   "internal": 0,
   "content": "7. <a id=\"LS-24\"></a><a id=\"IM-19\"></a>The forms and their values are these [LS-24, IM-19]:\n\n| Form | Digits | Example | Value |\n|---|---|---|---|\n| Decimal | `0`, or a nonzero digit and then digits | `1_000_000` | 1000000 |\n| Hexadecimal | `0x`, then digits `0` to `9` and `a` to `f` in either case | `0xDEAD_beef` | 3735928559 |\n| Binary | `0b`, then `0` and `1` | `0b1010_0101` | 165 |\n| Octal | `0o`, then `0` to `7` | `0o755` | 493 |\n| Balanced ternary | `0t`, then `N`, `0` and `P` | `0tP0N` | 8 |\n\n8. A literal denotes a value in Z, never a bit pattern: `0xFFFFFFFF` is 4294967295 wherever it appears. It takes its type from its context and shall fit that type (6.5) [IM-20, LS-29].\n9. <a id=\"LS-30\"></a>A balanced-ternary literal lists its digits most significant first, with `N` for -1, `0` for 0 and `P` for +1, so `0tP0N` is 9 - 1 = 8 and `0tN` is -1. It is an ordinary integer literal, typed by context like the others [LS-30].\n10. <a id=\"LS-28\"></a><a id=\"IM-25\"></a>A `-` in operand position followed by an integer, character or fraction literal forms one *negative literal*, whatever white space or comments stand between the two. `-128`, `- 128` and `-/* c */128` are each the value -128, which fits `I8`, and `-0.5` is the value -1/2. A `round` clause (6.7.15) after a negative fraction literal rounds the negative value (6.5): in the fixed-point type `Q8.8` (6.3.2), `-0.1 round floor` is -26/256 and `-0.1 round ceil` is -25/256. A `-` before anything else, including a parenthesized literal or another negative literal, is the negation operator: `-(128)` and `- -128` are negations (6.7.5) [LS-28, IM-25].\n\n**Examples**\n\n11. This example shows each form, and a negative balanced-ternary literal:\n\n```cint int_forms.ci\nI64 d = 1_000_000;\nI64 h = 0xDEAD_beef;\nI64 b = 0b1010_0101;\nI64 o = 0o755;\nI64 t = 0tP0N;\nI64 n = -0tP;\n\"{d} {h} {b} {o} {t} {n}\\n\";\n```"
  },
  {
   "id": "spec-04p:integer-literals-p2",
   "edition": "SPEC-04P.2",
   "title": "6.4.5 Integer literals (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#integer-literals",
   "internal": 0,
   "content": "```text\n1000000 3735928559 165 493 8 -1\n```\n\n12. A negative literal, with or without space after the minus sign, holds the least `I8` and `I64` values:\n\n```cint negative.ci\nI8 a = -128;\nI8 b = - 128;\nI8 c = -/* c */128;\nI64 m = -9223372036854775808;\n\"{a} {b} {c} {m}\\n\";\n```\n\n```text\n-128 -128 -128 -9223372036854775808\n```\n\n13. Parentheses make `128` a literal of its own, typed `I8` before the negation applies, and 128 does not fit `I8`:\n\n```cint negated.ci\nI8 a = -(128);\n\"{a}\\n\";\n```\n\n```text\nerror[C2003]: literal does not fit its type\n  --> negated.ci:1:10\n   |\n 1 | I8 a = -(128);\n   |          ^\n```\n\n14. This example shows a decimal literal with a leading zero:\n\n```cint leading_zero.ci\nI64 mode = 0755;\n\"{mode}\\n\";\n```\n\n```text\nerror[C1022]: invalid integer literal\n  --> leading_zero.ci:1:12\n   |\n 1 | I64 mode = 0755;\n   |            ^\n```\n\n**Notes**\n\n15. In C, `0755` is octal and means 493. cint rejects it, and the octal value is written `0o755`.\n16. In C, `-2147483648` is the negation of `2147483648`, which does not fit `int`, so the least `int` cannot be written as a literal. In cint, `-2147483648` is one literal, of value `MIN(I32)` in context `I32`."
  },
  {
   "id": "spec-04p:fraction-literals",
   "edition": "SPEC-04P.2",
   "title": "6.4.6 Fraction literals",
   "clauses": "LS-33 LS-34 LS-35",
   "url": "/specifications/spec-04p/2/#fraction-literals",
   "internal": 0,
   "content": "#### 6.4.6 Fraction literals\n\nA fraction literal writes an exact rational number with digits on both sides of a point, such as `1.5`. It is used for the fixed-point types of 6.3.2, never for an integer type.\n\n**Syntax**\n\n```ebnf\nFRAC_LIT = DEC_FRAC | HEX_FRAC ;\nDEC_FRAC = DEC_INT \".\" digit { [ sep ] digit } ;\nHEX_FRAC = HEX_INT \".\" hexdigit { [ sep ] hexdigit } ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-33\"></a>A fraction literal has at least one digit on each side of the point: `1.` and `.5` are not literals. Digit separators follow 6.4.5 on each side [LS-33].\n2. <a id=\"LS-35\"></a>A fraction literal may take only a fixed-point type. In any other context it is C2004: `I64 x = 1.5;` is rejected [LS-35].\n\n**Semantics**\n\n3. A decimal fraction literal denotes the exact rational its digits write: `0.1` is 1/10. A hexadecimal fraction literal is read in radix 16 on both sides: `0x1.8` is 3/2 [LS-33, LS-35].\n4. <a id=\"LS-34\"></a>Because a fraction needs a digit after the point, `1..5` is the three tokens `1`, `..` and `5`, and `0x1..5` is `0x1`, `..` and `5` [LS-34].\n5. How a fraction literal takes a fixed-point type, and when it must be followed by a `round` clause, is stated in 6.5.\n\n**Examples**\n\n6. This example shows fraction literals in fixed-point contexts. The second line prints each storage integer (6.3.2):\n\n```cint fractions.ci\nQ16.16 half = 0.5;\nQ16.16 h2 = 0x1.8;\nQ8.0 whole = 100.0;\nQ16.16 grouped = 1_000.000_5 round half_even;\n\"{half} {h2} {whole} {grouped}\\n\";\n\"{half.raw} {h2.raw} {whole.raw} {grouped.raw}\\n\";\n```\n\n```text\n0.5 1.5 100.0 1000.0005035400390625\n32768 98304 100 65536033\n```\n\n7. A fraction literal cannot initialize an integer:\n\n```cint fraction_int.ci\nI64 x = 1.5;\n\"{x}\\n\";\n```\n\n```text\nerror[C2004]: a fraction literal cannot have the integer type I64\n...\n```\n\n8. A range of integers is not a fraction:"
  },
  {
   "id": "spec-04p:fraction-literals-p1",
   "edition": "SPEC-04P.2",
   "title": "6.4.6 Fraction literals (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#fraction-literals",
   "internal": 0,
   "content": "```cint range_dots.ci\nfor i in 1..5 {\n    \"{i} \";\n}\n\"\\n\";\n```\n\n```text\n1 2 3 4 \n```"
  },
  {
   "id": "spec-04p:character-literals",
   "edition": "SPEC-04P.2",
   "title": "6.4.7 Character literals",
   "clauses": "IM-20 LS-39",
   "url": "/specifications/spec-04p/2/#character-literals",
   "internal": 0,
   "content": "#### 6.4.7 Character literals\n\nA character literal writes one Unicode character between single quotes and means its code point, as an integer: `'A'` is 65.\n\n**Syntax**\n\n```ebnf\nCHAR_LIT  = \"'\" ( char_char | escape ) \"'\" ;\nchar_char = (* any Unicode scalar value except \"'\", \"\\\" and a line end *) ;\n```\n\n`escape` is defined in 6.4.8.\n\n**Constraints**\n\n1. <a id=\"LS-39\"></a>A character literal holds exactly one Unicode scalar value or one escape: `''` and `'ab'` are C1030 [LS-39].\n2. <a id=\"IM-20\"></a>The escapes are those of string literals (6.4.8), and `\\xHH` is limited to 00 to 7F as in a string: `'\\x41'` is 65 and `'\\xff'` is C1032. An escape `\\u{...}` whose value is a surrogate, U+D800 to U+DFFF, or above U+10FFFF is C1031 [LS-39, IM-20].\n3. The value shall fit the type the literal takes, as 6.5 states: `U8 c = '\\u{100}';` is C2003.\n\n**Semantics**\n\n4. A character literal is an integer literal equal to the code point of its character: `'A'` is 65, `'\u00e9'` is 233 and `'\\u{1F600}'` is 128512. It has no type of its own and takes one from its context like any integer literal (6.5) [LS-39, IM-20].\n\n**Examples**\n\n5. This example shows character literals and escapes:\n\n```cint chars.ci\nI64 a = 'A';\nI64 e = '\u00e9';\nI64 s = '\\u{1F600}';\nI64 n = '\\n';\nI64 q = '\\'';\nI64 x = '\\x41';\nU8 z = '\\0';\n\"{a} {e} {s} {n} {q} {x} {z}\\n\";\n```\n\n```text\n65 233 128512 10 39 65 0\n```\n\n6. A character literal is valid in a case range:\n\n```cint char_case.ci\nU8 c = 'q';\nswitch (c) {\n    case 'a'..='z': { \"lower\\n\"; }\n    default: { \"other\\n\"; }\n}\n```\n\n```text\nlower\n```"
  },
  {
   "id": "spec-04p:string-literals",
   "edition": "SPEC-04P.2",
   "title": "6.4.8 String literals",
   "clauses": "LS-42 LS-43 LS-44 LS-46",
   "url": "/specifications/spec-04p/2/#string-literals",
   "internal": 0,
   "content": "#### 6.4.8 String literals\n\nA string literal writes a sequence of bytes, the UTF-8 encoding of its text with each escape replaced. It is what a print statement writes, the message of an `assert`, the name of a test and the text passed to a function that reads bytes.\n\n**Syntax**\n\n```ebnf\nSTRING   = '\"' { str_char | escape | \"{{\" | \"}}\" | hole } '\"' ;\nstr_char = (* any Unicode scalar value except '\"', \"\\\", \"{\", \"}\" and a line end *) ;\nescape   = \"\\\" ( \"\\\" | '\"' | \"'\" | \"n\" | \"r\" | \"t\" | \"0\"\n               | \"x\" octdigit hexdigit\n               | \"u{\" hexdigit [ hexdigit [ hexdigit [ hexdigit [ hexdigit [ hexdigit ] ] ] ] ] \"}\" ) ;\n```\n\n`hole` is defined in 7.5. A hole `{expr}` prints the value of `expr`.\n\n**Constraints**\n\n1. <a id=\"LS-42\"></a><a id=\"LS-43\"></a>The escapes are these, and any other backslash sequence is C1032, reported at the backslash [LS-42, LS-43]:\n\n| Escape | Bytes |\n|---|---|\n| `\\\\`, `\\\"`, `\\'` | the character after the backslash |\n| `\\n`, `\\r`, `\\t`, `\\0` | 0x0A, 0x0D, 0x09, 0x00 |\n| `\\xHH` | the one byte `HH`, from 00 to 7F |\n| `\\u{H...}`, with 1 to 6 hexadecimal digits | the UTF-8 encoding of the Unicode scalar value; a surrogate, U+D800 to U+DFFF, or a value above U+10FFFF is C1031 |\n\n2. <a id=\"LS-44\"></a>A literal `{` or `}` is written `{{` or `}}` in every string literal. A single `{` begins a hole, an expression whose value is written in its place; a single `}` without its `{` is C1039 [LS-44].\n3. Holes are permitted only in print statements and in the message of an `assert`. A hole anywhere else, such as in the name of a test or in a literal passed as an argument, is C1033 [LS-44].\n4. <a id=\"LS-46\"></a>A string literal shall not contain an unescaped line end (C1034) [LS-46].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:string-literals-p1",
   "edition": "SPEC-04P.2",
   "title": "6.4.8 String literals (part 2)",
   "clauses": "LS-40 LS-42 LS-45",
   "url": "/specifications/spec-04p/2/#string-literals",
   "internal": 0,
   "content": "5. <a id=\"LS-40\"></a>A string literal denotes the bytes of its text in UTF-8, with each escape replaced by its bytes and each `{{` or `}}` by one brace. There is no terminating byte: `\"a\\0b\"` is three bytes, the middle one 0x00 [LS-40, LS-42].\n6. <a id=\"LS-45\"></a>Adjacent string literals are joined during translation: `\"ab\" \"cd\"` is `\"abcd\"` [LS-45].\n7. The bytes of a string literal are storage that lasts for the whole run and cannot be written [LS-40].\n8. A string literal passed as the argument for a parameter `in U8[n]` is a read-only view of its bytes, whose extent `n` is the number of bytes [LS-40].\n9. `len` of a string literal is its number of bytes: `len(\"abc\")` is 3 and `len(\"\u00e9\")` is 2 [LS-40].\n\n**Examples**\n\n10. This example shows escapes and doubled braces in a print statement:\n\n```cint escapes.ci\n\"tab[\\t] quote[\\\"] backslash[\\\\] braces[{{}}] hex[\\x41] smile[\\u{1F600}]\\n\";\n```\n\n```text\ntab[\t] quote[\"] backslash[\\] braces[{}] hex[A] smile[\ud83d\ude00]\n```\n\n11. This example shows string literals as arguments. Adjacent literals are joined, and the extent is the number of bytes:\n\n```cint string_args.ci\nI64 count_a[n](in U8[n] s) {\n    I64 k = 0;\n    for i in 0..n {\n        if (s[i] == 'a') {\n            k += 1;\n        }\n    }\n    return k;\n}\nI64 size_of[n](in U8[n] s) {\n    return n;\n}\nI64 a = count_a(\"banana\");\nI64 b = count_a(\"a\\0b\");\nI64 c = size_of(\"ab\" \"cd\");\nI64 d = size_of(\"\u00e9\");\n\"{a} {b} {c} {d}\\n\";\n```\n\n```text\n3 1 4 2\n```\n\n12. This example shows `len` of a string literal:\n\n```cint string_len.ci\nI64 n = len(\"abc\");\nI64 m = len(\"\u00e9\");\n\"{n} {m}\\n\";\n```\n\n```text\n3 2\n```\n\n13. A hole is not permitted in the name of a test:\n\n```cint hole_name.ci\nI64 x = 1;\ntest \"value {x}\" {\n    assert(1 == 1);\n}\n\"x\\n\";\n```\n\n```text\nerror[C1033]: invalid character or string literal\n  --> hole_name.ci:2:13\n   |\n 2 | test \"value {x}\" {\n   |             ^\n```"
  },
  {
   "id": "spec-04p:string-literals-p2",
   "edition": "SPEC-04P.2",
   "title": "6.4.8 String literals (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#string-literals",
   "internal": 0,
   "content": "14. This example shows an unknown escape:\n\n```cint bad_escape.ci\n\"bad \\q escape\\n\";\n```\n\n```text\nerror[C1032]: invalid character or string literal\n  --> bad_escape.ci:1:6\n   |\n 1 | \"bad \\q escape\\n\";\n   |      ^\n```\n\n**Notes**\n\n15. A string literal in C ends with a hidden zero byte, and a zero byte inside it ends it early for most library functions. A cint string literal has no terminator, and a zero byte is an ordinary byte."
  },
  {
   "id": "spec-04p:punctuators",
   "edition": "SPEC-04P.2",
   "title": "6.4.9 Punctuators",
   "clauses": "LS-48 LS-49",
   "url": "/specifications/spec-04p/2/#punctuators",
   "internal": 0,
   "content": "#### 6.4.9 Punctuators\n\nPunctuators are the operators and separators of the language. Several operators come in three spellings that differ in what happens when the exact result is out of range: the plain spelling faults, the spelling with `%` wraps and the spelling with `|` saturates.\n\n**Semantics**\n\n1. <a id=\"LS-48\"></a>The punctuators are [LS-48]:\n\n```text\n+   -   *   /   %   <<  >>          checked arithmetic and shifts\n+%  -%  *%  <<%                     wrapping forms\n+|  -|  *|                          saturating forms\n&   |   ^   ~                       bitwise\n==  !=  <   <=  >   >=              comparison\n&&  ||  !                           logical\n?   :                               conditional expression\n=   +=  -=  *=  /=  %=  <<=  >>=  &=  |=  ^=\n+%= -%= *%= <<%= +|= -|= *|=        assignment\n++  --                              increment and decrement statements\nas%  as?                            conversions\n..  ..=                             ranges\n(   )   [   ]   {   }   ,   ;   .   @\n!                                   also in error-union types\n```\n\n2. <a id=\"LS-49\"></a>`as%` and `as?` are single tokens with no space inside: `a as % U8` is a syntax error (C1050) [LS-49]. The word `as` itself is a keyword (6.4.4). No production of this edition uses the punctuator `@`.\n\n3. Each operator's meaning, and the faults it can raise, are in 6.7; the conversions are in 6.6.\n\n**Examples**\n\n4. Without spaces, maximal munch (6.4.2) finds the wrapping and saturating operators:\n\n```cint punct.ci\nI64 a = I64.max;\nI64 b = 1;\nI64 c = a+%b;\nI64 d = b<<%63;\nU8 e = 250;\nU8 f = e+|10;\n\"{c} {d} {f}\\n\";\n```\n\n```text\n-9223372036854775808 -9223372036854775808 255\n```"
  },
  {
   "id": "spec-04p:literals-and-context-typing",
   "edition": "SPEC-04P.2",
   "title": "6.5 Literals and context typing",
   "clauses": "IM-20 LS-53 LS-54 LS-58 LS-60",
   "url": "/specifications/spec-04p/2/#literals-and-context-typing",
   "internal": 0,
   "content": "### 6.5 Literals and context typing\n\nA literal has no type of its own. It takes the type its context gives it, such as the type of the variable it initializes or of the other operand of an operator, and it must fit that type exactly. There is no implicit conversion between types afterward, except from an error set to a larger one (6.3.7, 6.6), so a literal's context decides how the arithmetic around it is done.\n\n**Constraints**\n\n1. <a id=\"LS-53\"></a><a id=\"LS-58\"></a>An integer, character or fraction literal shall be exactly representable in the type its context gives it. An integer or character literal that does not fit is C2003, reported at the literal, inside any parentheses or at the `-` of a negative literal [LS-53, IM-20]. Representability is a property of the literal alone: with `I8 x`, `x + 300` is C2003, while `x + 100` is valid and its addition is checked when it runs [LS-58].\n2. <a id=\"LS-54\"></a>An operator expression whose operands are all literals is evaluated during translation with its run-time meaning; a fault there is C6001 (6.8) [LS-54].\n3. <a id=\"LS-60\"></a>A context-typed error value, such as `.overdrawn`, needs a context that gives its error set; with none it is C2007 [LS-60].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:literals-and-context-typing-p1",
   "edition": "SPEC-04P.2",
   "title": "6.5 Literals and context typing (part 2)",
   "clauses": "IM-21 IM-22 IM-24 IM-27 LS-37 LS-53 LS-54 LS-55 LS-56 LS-57 LS-59 LS-60",
   "url": "/specifications/spec-04p/2/#literals-and-context-typing",
   "internal": 0,
   "content": "4. <a id=\"LS-56\"></a><a id=\"IM-21\"></a>A literal takes its type from the first of these rules that applies [LS-56, IM-21]:\n   1. the declared type of the variable, constant, field or element it initializes or is assigned to;\n   2. the parameter type of the argument it gives, in a call of a user function;\n   3. the result type of the function, in a `return` statement;\n   4. the type of the other operand of a binary arithmetic, bitwise or comparison operator, when that operand is typed, except that this rule never types a shift count (paragraph 7);\n   5. the element type, in an array literal whose element type is declared;\n   6. the type of the value a `switch` tests, for a `case` item;\n   7. for an argument of a built-in function whose arguments share one type, such as `min`, `max` or `clamp`, the type of its typed arguments; when none is typed, the declared type that the call's result initializes;\n   8. otherwise `I64`.\n5. <a id=\"IM-22\"></a>An operator expression whose operands are all literals has no type of its own either: the context's type passes to each operand. The expression is then evaluated with the meaning it would have at run time, checked, wrapping or saturating as written; it is never evaluated in Z as a whole [LS-54, IM-22].\n6. <a id=\"LS-55\"></a><a id=\"IM-24\"></a>A named constant is not a literal. Every `const` declaration names its type, and a constant is an ordinary typed operand that never takes its type from its context (6.9.2) [LS-55, IM-24].\n7. <a id=\"LS-57\"></a>The count of `<<`, `<<%` and `>>` may have any integer type and is compared as a value in Z (6.7.8). A literal count has type `I64`. The left operand of a shift is typed by the context of the whole shift, by rules 1 to 3 and 5 to 8, never by rule 4 from the operand of an enclosing operator and never by the count [LS-57, IM-22].\n8. <a id=\"LS-59\"></a>A literal operand of a comparison takes th"
  },
  {
   "id": "spec-04p:literals-and-context-typing-p2",
   "edition": "SPEC-04P.2",
   "title": "6.5 Literals and context typing (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#literals-and-context-typing",
   "internal": 0,
   "content": "**Examples**\n\n12. Literals typed by declarations and by the other operand, with wrapping forms and floor division:\n\n```cint contexts.ci\nconst I64 LIMIT = 1 << 40;\nI16 m = -32768;\nI8 p = 100 +% 100;\nU8 s = 200 +% 100;\nI64 g = 3 * 1_000_000_000_000 / 7;\nI64 fl = 7 / 2;\nI64 neg = -7 / 2;\n\"{LIMIT} {m} {p} {s} {g} {fl} {neg}\\n\";\n```\n\n```text\n1099511627776 -32768 -56 44 428571428571 3 -4\n```\n\n13. A literal that does not fit the type of the other operand is rejected at the literal; one that fits is checked when the operation runs:\n\n```cint operand_fit.ci\nI8 x = 0;\nI8 y = x + 300;\n\"{y}\\n\";\n```\n\n```text\nerror[C2003]: literal does not fit its type\n  --> operand_fit.ci:2:12\n   |\n 2 | I8 y = x + 300;\n   |            ^\n```\n\n```cint operand_run.ci\nI8 x = 100;\nI8 y = x + 100;\n\"{y}\\n\";\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> operand_run.ci:2:10\n   |\n 2 | I8 y = x + 100;\n   |          ^ add.checked.i8\n   ...\n```\n\n14. A literal-only expression is typed by its context and evaluated in that type. Here `40000` does not fit `I16`, and `2_000_000_000 * 2` overflows `I32` during translation:\n\n```cint literal_only.ci\nI16 h = 40000 - 30000;\n\"{h}\\n\";\n```\n\n```text\nerror[C2003]: literal does not fit its type\n  --> literal_only.ci:1:9\n   |\n 1 | I16 h = 40000 - 30000;\n   |         ^\n```\n\n```cint literal_fault.ci\nI32 v = 2_000_000_000 * 2 / 4;\n\"{v}\\n\";\n```\n\n```text\nerror[C6001]: fault during constant evaluation\n  --> literal_fault.ci:1:23\n   |\n 1 | I32 v = 2_000_000_000 * 2 / 4;\n   |                       ^\n   ...\n   = operation: mul.checked.i32\n   = operand-count: 2\n   = operand: I32 2000000000\n   = operand: I32 2\n   = exact:   4000000000\n   = limit:   I32 2147483647\n   ...\n```\n\n15. A constant has its declared type and does not adapt to its context:\n\n```cint typed_const.ci\nconst I64 LIMIT = 1 << 40;\nI32 small = LIMIT;\n\"{small}\\n\";\n```"
  },
  {
   "id": "spec-04p:literals-and-context-typing-p3",
   "edition": "SPEC-04P.2",
   "title": "6.5 Literals and context typing (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#literals-and-context-typing",
   "internal": 0,
   "content": "```text\nerror[C2001]: type mismatch\n  --> typed_const.ci:2:13\n   |\n 2 | I32 small = LIMIT;\n   |             ^\n```\n\n16. The left operand of a shift takes the type of the whole shift's context, not of the count. With an `I8` variable, `x + (1 << 6)` mixes `I8` with an `I64` shift:\n\n```cint shift_type.ci\nU8 k = 40;\nI64 v = 1 << k;\n\"{v}\\n\";\n```\n\n```text\n1099511627776\n```\n\n```cint shift_mix.ci\nI8 x = 0;\nI8 y = x + (1 << 6);\n\"{y}\\n\";\n```\n\n```text\nerror[C2001]: type mismatch\n  --> shift_mix.ci:2:12\n   |\n 2 | I8 y = x + (1 << 6);\n   |            ^\n```\n\n17. A literal argument of `clamp` with no typed argument takes the type the result initializes, `U8` here, and 300 does not fit it:\n\n```cint builtin_args.ci\nI8 x = 100;\nI8 a = min(x, 50);\nI8 b = max(3, 4);\n\"{a} {b}\\n\";\nU8 c = clamp(300, 0, 255);\n```\n\n```text\nerror[C2003]: literal does not fit its type\n  --> builtin_args.ci:5:14\n   |\n 5 | U8 c = clamp(300, 0, 255);\n   |              ^\n```\n\n18. A literal operand is converted from its value in Z; any other literal-only source is typed `I64` first:\n\n```cint literal_convert.ci\nU64 all = -1 as% U64;\nU64 top = (18446744073709551615) as U64;\nI8 low = 300 as% I8;\nU64 q = (5 - 6) as% U64;\n\"{all} {top} {low} {q}\\n\";\n```\n\n```text\n18446744073709551615 18446744073709551615 44 18446744073709551615\n```\n\n19. This example shows fixed-point contexts. `0.1` is not a multiple of `2^-16`, so it needs a `round` clause; a quotient of literals is evaluated with fixed-point division (6.7.7):\n\n```cint fixed_context.ci\nQ16.16 two = 2;\nQ16.16 t2 = 0.1 round half_even;\nQ16.16 third = 1.0 / 3.0;\nQ16.16 mix = 1 / 3.0;\n\"{two.raw} {t2.raw} {third.raw} {mix.raw}\\n\";\n```\n\n```text\n131072 6554 21845 21845\n```\n\n```cint fixed_inexact.ci\nQ16.16 tenth = 0.1;\n\"{tenth}\\n\";\n```\n\n```text\nerror[C2006]: 0.1 is not a multiple of 2^-16, the resolution of Q16.16\n...\n```\n\n20. This example shows an error value with no context:"
  },
  {
   "id": "spec-04p:literals-and-context-typing-p4",
   "edition": "SPEC-04P.2",
   "title": "6.5 Literals and context typing (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#literals-and-context-typing",
   "internal": 0,
   "content": "```cint error_context.ci\nerror Ledger { overdrawn, closed }\nBool b = .overdrawn == .closed;\n\"{b}\\n\";\n```\n\n```text\nerror[C2007]: fraction, fixed-point, enum literal, or rounding rule\n  --> error_context.ci:2:10\n   |\n 2 | Bool b = .overdrawn == .closed;\n   |          ^\n```\n\n**Notes**\n\n21. C gives an integer constant a type from its value and suffix and then converts operands by the usual arithmetic conversions. cint does neither: a literal takes the type of its context, and operands of different types are rejected (C2001) unless converted with `as` (6.6)."
  },
  {
   "id": "spec-04p:conversions",
   "edition": "SPEC-04P.2",
   "title": "6.6 Conversions",
   "clauses": "IM-10 IM-50 IM-9 LS-134 LS-135",
   "url": "/specifications/spec-04p/2/#conversions",
   "internal": 0,
   "content": "### 6.6 Conversions\n\nA value changes type only through a conversion that the program writes. `x as T` converts `x` to the type `T` and faults when the value does not fit; `x as% T` wraps the value into `T`; `x as? T` returns an error instead of faulting. There are no implicit conversions: not in arithmetic, not in assignment, and not from a narrower integer type to a wider one. The one exception is a value of an error set, which converts to a larger set (6.3.7). A conversion that changes a fixed-point value's resolution or makes it an integer rounds once, by the mode its `round` clause names, or by `half_even` when it has none.\n\n**Syntax**\n\n```ebnf\nconv_expr    = unary_expr { conv_op type [ round_clause ] } ;\nconv_op      = \"as\" | \"as%\" | \"as?\" ;\nround_clause = \"round\" IDENT ;\n```\n\n1. `as%` and `as?` are single tokens (6.4.9). The `IDENT` after `round` is the name of a rounding mode (6.7.15).\n\n**Constraints**\n\n2. <a id=\"IM-50\"></a><a id=\"LS-134\"></a>A value of one numeric type shall not be used where another type is required. An operand, an initializer, an argument or a returned value of the wrong type is diagnosed C2001, even when every value of its type fits the required type: with `I32 a` and `I64 b`, `b + a` is diagnosed, and `b + (a as I64)` is valid [IM-9, IM-50, LS-134].\n\n3. <a id=\"LS-135\"></a>A conversion from `Bool` shall be written with `as`, and its target shall be an integer type: `as%` and `as?` from a `Bool`, and a conversion in either direction between `Bool` and a fixed-point type, are diagnosed C2008. A conversion whose source is a struct is diagnosed C2008 as well [LS-135].\n\n4. There is no conversion from an integer to `Bool`: `n as Bool` is diagnosed C2056, and a comparison such as `n != 0` gives a `Bool` [IM-10, LS-135]."
  },
  {
   "id": "spec-04p:conversions-p1",
   "edition": "SPEC-04P.2",
   "title": "6.6 Conversions (part 2)",
   "clauses": "IM-50 IM-68 IM-69 LS-133 LS-136",
   "url": "/specifications/spec-04p/2/#conversions",
   "internal": 0,
   "content": "5. <a id=\"IM-69\"></a><a id=\"LS-133\"></a>A `round` clause is permitted only on a conversion that rounds: from a fixed-point type to an integer type, or to a fixed-point type with fewer fraction bits (paragraphs 11 and 12). On any other conversion it is diagnosed C2009. The name after `round` shall be a rounding mode (C3007) [IM-69, LS-133].\n\n6. <a id=\"LS-136\"></a>A conversion binds tighter than every binary operator, and conversions group from left to right: `a as I64 + b` is `(a as I64) + b`, and `x as I32 as% I16` converts twice. A unary operator directly before a conversion needs parentheses (6.7.2) [LS-136].\n\n**Semantics**\n\n7. Each conversion has three forms. For a source value `x`, a target type `T` and the value `v` that paragraphs 9 to 13 define [IM-50, LS-133]:\n   - `x as T`, the *checked conversion*, gives `v` when `in(T, v)` and otherwise faults;\n   - `x as% T`, the *wrapping conversion*, gives `wrap(T, v)` for an integer `T`, and for a fixed-point `T` the value whose raw value is `wrap(S, v)`, where `S` is the storage type of `T` and `v` the raw value the conversion computes;\n   - `x as? T`, the *result-returning conversion*, gives a value of type `ArithError!T`: `v` where `x as T` would give it, and `ArithError.narrow` where `x as T` would fault. It is consumed with `try`, `catch` or `_ =` (6.11).\n\n8. A conversion to a type whose range holds every value of the source type, such as `I32` to `I64` or `U8` to `I16`, gives the source value and never faults. Between two integer types of the same width, `as%` keeps the bit pattern: `-1` as `I8` becomes 255 as `U8` [IM-50].\n\n9. From an integer type to an integer type, `v` is the value of `x` [IM-50].\n\n10. <a id=\"IM-68\"></a>From an integer type to `Q<i>.<f>`, the conversion is exact: `v` is the raw value `x * 2^f`, and the checked conversion faults when it is outside the storage type [IM-68]."
  },
  {
   "id": "spec-04p:conversions-p2",
   "edition": "SPEC-04P.2",
   "title": "6.6 Conversions (part 3)",
   "clauses": "IM-10 IM-26 IM-57 IM-68 IM-69 LS-135 LS-38",
   "url": "/specifications/spec-04p/2/#conversions",
   "internal": 0,
   "content": "11. From `Q<i>.<f>` to `Q<j>.<g>`: when `g >= f`, `v` is the raw value of `x` times 2^(g - f), exact; when `g < f`, `v` is the raw value of `x` divided by 2^(f - g), rounded once by the mode of the `round` clause, `half_even` when there is none. The range check or the wrap applies to `v` after the rounding [IM-68, IM-69].\n\n12. From `Q<i>.<f>` to an integer type, `v` is the value of `x` rounded once to an integer by the mode of the `round` clause, `half_even` when there is none. The range check or the wrap applies to `v` after the rounding [IM-68, IM-69].\n\n13. From `Bool` to an integer type, `v` is 0 for `false` and 1 for `true` [IM-10, LS-135].\n\n14. <a id=\"IM-26\"></a>When the source of a conversion is a literal operand (6.5) of an integer or character literal, the conversion applies to the literal's value in Z, which has no type: `(18446744073709551615) as U64` is valid, and `-1 as% U64` is 18446744073709551615. Any other source whose operands are all literals is typed `I64` first (6.5): `(200 + 100) as% U8` converts the `I64` value 300 [IM-26].\n\n15. <a id=\"IM-57\"></a><a id=\"LS-38\"></a>`x.raw`, for `x` of `Q<i>.<f>`, is the raw value of `x` as a value of the storage type. `Q.raw(n)` is the value of the fixed-point type `Q` whose raw value is `n`; `n` shall have exactly the storage type of `Q` (C2001). Both are exact and never fault: `Q16.16.raw(n)` with the `I32` 98304 is 1.5, and its `.raw` is 98304 again [IM-57, LS-38].\n\n**Faults**"
  },
  {
   "id": "spec-04p:conversions-p3",
   "edition": "SPEC-04P.2",
   "title": "6.6 Conversions (part 4)",
   "clauses": "IM-132 IM-133 IM-184 IM-26 IM-50 IM-68",
   "url": "/specifications/spec-04p/2/#conversions",
   "internal": 0,
   "content": "16. <a id=\"IM-132\"></a><a id=\"IM-133\"></a>The fault `E_NARROW` is raised by `x as T` when `v` is outside the range of `T`. The fault record holds the operation identifier `as.checked.s.t`, where `s` and `t` are the source and target types in lower case. A fixed-point type is written with `_` for its point (`q16_16`), and the identifier ends with `.mode` when the conversion rounds, whether its mode was written or not. The record holds one operand, the source value. Its exact result is `v`, which is a raw value when the target is a fixed-point type, and its limit is the bound of `T` that `v` crossed, a value of type `T`. Its position is the `as` token [IM-50, IM-68, IM-132, IM-133]. `as%` and `as?` raise no fault.\n\n17. <a id=\"IM-184\"></a>A checked conversion whose source is a literal operand is decided at translation (6.8). When the value does not fit, the program is rejected with C6001, and the fault it reports has the operation identifier `unassigned`, which names a checked conversion of a literal decided at translation (B.3), the operand as a value in Z (`Z 300`), the exact result and the bound of `T` as the limit [IM-26, IM-184].\n\n**Examples**\n\n18. This example shows checked conversions that fit, and wrapping conversions that keep the low bits:\n\n```cint convert_int.ci\nI64 x = 2147483648;\n\"{x as% I32} {x as I128}\\n\";\nI64 m = -1;\n\"{m as% U64} {m as% U8}\\n\";\nU64 u = 9223372036854775808;\n\"{u as% I64}\\n\";\nI64 n = -129;\n\"{n as% I8} {n as I16}\\n\";\n```\n\n```text\n-2147483648 2147483648\n18446744073709551615 255\n-9223372036854775808\n127 -129\n```\n\n19. 300 does not fit `U8`. `as%` gives 300 - 256, and `as` stops the program:\n\n```cint convert_narrow.ci\nI64 big = 300;\n\"{big as% U8}\\n\";\nU8 small = big as U8;\n\"{small}\\n\";\n```"
  },
  {
   "id": "spec-04p:conversions-p4",
   "edition": "SPEC-04P.2",
   "title": "6.6 Conversions (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#conversions",
   "internal": 0,
   "content": "```text\n44\nfault[E_NARROW]: the value does not fit the destination type\n  --> convert_narrow.ci:3:16\n   |\n 3 | U8 small = big as U8;\n   |                ^ as.checked.i64.u8\n   |\n   = operation: as.checked.i64.u8\n   = operand-count: 1\n   = operand: I64 300\n   = exact:   300\n   = limit:   U8 255\n   ...\n```\n\n20. `as?` with `catch` gives a fallback value instead of a fault:\n\n```cint convert_result.ci\nI64 big = 300;\nI64 ok = 200;\nU8 a = big as? U8 catch U8.max;\nU8 b = ok as? U8 catch U8.max;\n\"{a} {b}\\n\";\n```\n\n```text\n255 200\n```\n\n21. A conversion binds tighter than `+`:\n\n```cint convert_precedence.ci\nI32 a = 5;\nI64 b = 7;\nI64 c = a as I64 + b;\n\"{c}\\n\";\n```\n\n```text\n12\n```\n\n22. Without the conversion, the addition mixes `I64` and `I32`:\n\n```cint convert_implicit.ci\nI32 a = 5;\nI64 b = 7;\nI64 c = b + a;\n\"{c}\\n\";\n```\n\n```text\nerror[C2001]: type mismatch\n  --> convert_implicit.ci:3:13\n   |\n 3 | I64 c = b + a;\n   |             ^\n```\n\n23. Literal operands convert from their values in Z:\n\n```cint convert_literal.ci\nU64 top = (18446744073709551615) as U64;\nU64 all = -1 as% U64;\nU8 low = (200 + 100) as% U8;\n\"{top} {all} {low}\\n\";\n```\n\n```text\n18446744073709551615 18446744073709551615 44\n```\n\n24. A checked conversion of a literal that does not fit is found at translation:\n\n```cint convert_literal_fault.ci\nU8 k = 300 as U8;\n\"{k}\\n\";\n```\n\n```text\nerror[C6001]: fault during constant evaluation\n  --> convert_literal_fault.ci:1:12\n   |\n 1 | U8 k = 300 as U8;\n   |            ^\n   |\nfault[E_NARROW]: the value does not fit the destination type\n  --> convert_literal_fault.ci:1:12\n   |\n 1 | U8 k = 300 as U8;\n   |            ^ unassigned\n   |\n   = operation: unassigned\n   = operand-count: 1\n   = operand: Z 300\n   = exact:   300\n   = limit:   U8 255\n   ...\n```\n\n25. An integer does not convert to `Bool`:\n\n```cint convert_bool.ci\nI64 n = 3;\nBool b = n as Bool;\n\"{b}\\n\";\n```"
  },
  {
   "id": "spec-04p:conversions-p5",
   "edition": "SPEC-04P.2",
   "title": "6.6 Conversions (part 6)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#conversions",
   "internal": 0,
   "content": "```text\nerror[C2056]: integer used as `Bool`\n  --> convert_bool.ci:2:10\n   |\n 2 | Bool b = n as Bool;\n   |          ^\n```\n\n26. A conversion between integer types does not round, so it takes no `round` clause:\n\n```cint convert_round_clause.ci\nI64 n = 4;\nI32 m = n as I32 round floor;\n\"{m}\\n\";\n```\n\n```text\nerror[C2009]: fraction, fixed-point, enum literal, or rounding rule\n  --> convert_round_clause.ci:2:11\n   |\n 2 | I32 m = n as I32 round floor;\n   |           ^\n```\n\n27. From fixed point to an integer, -2.5 rounds to -2 by `half_even` and to -3 by `floor` and `half_away`. From an integer, and to a type with more fraction bits, the conversion is exact. From `Q32.32` to `Q16.16`, the value 2^-32 rounds to 0 by `half_even` and to 2^-16 by `ceil`:\n\n```cint convert_fixed.ci\nQ16.16 x = -2.5;\n\"{x as I32} {x as I32 round floor} {x as I32 round half_away}\\n\";\nI64 n = 3;\nQ16.16 q = n as Q16.16;\n\"{q} raw {q.raw}\\n\";\nQ32.32 fine = q as Q32.32;\n\"{fine} raw {fine.raw}\\n\";\nQ32.32 tiny = Q32.32.raw(1);\nQ16.16 t0 = tiny as Q16.16;\nQ16.16 t1 = tiny as Q16.16 round ceil;\n\"{t0.raw} {t1.raw}\\n\";\n```\n\n```text\n-2 -3 -3\n3.0 raw 196608\n3.0 raw 12884901888\n0 1\n```\n\n28. 300.75 rounds to 301 by `half_even`, which does not fit `I8`. The operand is shown with its raw value, 300.75 times 2^16 and the operation identifier names the rounding mode, which was not written:\n\n```cint convert_fixed_narrow.ci\nQ16.16 x = 300.75;\nI8 c = x as I8;\n\"{c}\\n\";\n```\n\n```text\nfault[E_NARROW]: the value does not fit the destination type\n  --> convert_fixed_narrow.ci:2:10\n   |\n 2 | I8 c = x as I8;\n   |          ^ as.checked.q16_16.i8.half_even\n   |\n   = operation: as.checked.q16_16.i8.half_even\n   = operand-count: 1\n   = operand: Q16.16 raw 19709952\n   = exact:   301\n   = limit:   I8 127\n   ...\n```"
  },
  {
   "id": "spec-04p:conversions-p6",
   "edition": "SPEC-04P.2",
   "title": "6.6 Conversions (part 7)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#conversions",
   "internal": 0,
   "content": "29. 40000 does not fit `Q16.16`, whose largest value is 32768 - 2^-16. When the target is fixed point, the exact result and the limit are raw values:\n\n```cint convert_to_fixed_narrow.ci\nI64 n = 40000;\nQ16.16 w = n as Q16.16;\n\"{w}\\n\";\n```\n\n```text\nfault[E_NARROW]: the value does not fit the destination type\n  --> convert_to_fixed_narrow.ci:2:14\n   |\n 2 | Q16.16 w = n as Q16.16;\n   |              ^ as.checked.i64.q16_16\n   |\n   = operation: as.checked.i64.q16_16\n   = operand-count: 1\n   = operand: I64 40000\n   = exact:   2621440000\n   = limit:   Q16.16 raw 2147483647\n   ...\n```\n\n30. `as%` rounds first and then wraps: 300.75 rounds to 301, which wraps to 45 in `U8`, and truncates to 300, which wraps to 44. 40000 times 2^16 does not fit `I32`, so its raw value wraps. `as?` reports the value that does not fit `I8`:\n\n```cint convert_fixed_wrap.ci\nQ16.16 x = 300.75;\nU8 a = x as% U8;\nU8 b = x as% U8 round trunc;\n\"{a} {b}\\n\";\nI64 n = 40000;\nQ16.16 w = n as% Q16.16;\n\"{w}\\n\";\nI8 c = x as? I8 catch I8.max;\n\"{c}\\n\";\n```\n\n```text\n45 44\n-25536.0\n127\n```\n\n31. `Q16.16.raw` builds a value from its raw value, which is an `I32` (paragraph 15):\n\n```cint convert_raw.ci\nI32 n = 98304;\nQ16.16 x = Q16.16.raw(n);\nQ16.16 y = Q16.16.raw(-1);\n\"{x} {y}\\n\";\nI32 back = y.raw;\n\"{back}\\n\";\n```\n\n```text\n1.5 -0.0000152587890625\n-1\n```\n\n**Notes**\n\n32. In C, the usual arithmetic conversions and assignment convert values without a cast, and converting an out-of-range value to a signed integer type gives an implementation-defined result. In cint every conversion is written, and `as` faults where C would give such a result.\n\n33. `as%` is the only conversion that reinterprets a bit pattern. A program that means to wrap writes `as%`; a program that expects every value to fit writes `as` and learns of a value that does not."
  },
  {
   "id": "spec-04p:expressions",
   "edition": "SPEC-04P.2",
   "title": "6.7 Expressions",
   "clauses": "IM-28",
   "url": "/specifications/spec-04p/2/#expressions",
   "internal": 0,
   "content": "### 6.7 Expressions\n\nAn expression computes a value from operands. This subclause defines the operators of cint from those that bind tightest to those that bind loosest, then the result forms, which report an arithmetic failure as an error value, then assignment, and last the rounding modes that every rounding operation names. Literals and their typing are in 6.4 and 6.5, conversions in 6.6, the order in which operands are evaluated in 6.2.4, and the operations called by name in clause 7.\n\nThe operators apply to every integer type of 6.3.1, from `I8` to `I1024` and from `U8` to `U512`, with the same meaning at every width: a wide type is an ordinary integer type. The arithmetic operators, the comparisons and negation also apply to fixed-point types (6.3.2), as each subclause states.\n\n**Semantics**\n\n1. An arithmetic operator has up to three spellings, one for each form: the plain spelling is a checked operator, the spelling with `%` a wrapping operator, and the spelling with `|` a saturating operator (3.5 to 3.7). The spelling alone chooses the form; no mode, option or build setting changes it [IM-28].\n\n| Operation | Checked | Wrapping | Saturating | Result form (6.7.12) |\n|---|---|---|---|---|\n| Add | `a + b` | `a +% b` | `a +\\| b` | `add_result(a, b)` |\n| Subtract | `a - b` | `a -% b` | `a -\\| b` | `sub_result(a, b)` |\n| Multiply | `a * b` | `a *% b` | `a *\\| b` | `mul_result(a, b)` |\n| Divide | `a / b` | none | none | `div_result(a, b)` |\n| Remainder | `a % b` | none | none | `rem_result(a, b)` |\n| Shift left | `a << k` | `a <<% k` | none | `shl_result(a, k)` |\n| Shift right | `a >> k` | none | none | none |\n| Negate | `-a` | `-%a` | `0 -\\| a` | `sub_result(0, a)` |\n\nConversions have forms of their own (6.6)."
  },
  {
   "id": "spec-04p:expressions-p1",
   "edition": "SPEC-04P.2",
   "title": "6.7 Expressions (part 2)",
   "clauses": "IM-31",
   "url": "/specifications/spec-04p/2/#expressions",
   "internal": 0,
   "content": "2. <a id=\"IM-31\"></a>A wrapping or saturating operator never faults on overflow. Two conditions still fault in every form: a shift count outside its range (6.7.8) and a divisor of 0 (6.7.7) [IM-31].\n\n3. As 6.2.4 states, every intermediate result has the type of the operation that produced it: no operand is promoted, and nothing is computed in a wider type except inside the built-in operations that say so (clause 7).\n\n**Notes**\n\n4. A fault record names the faulting operation by an operation identifier (3.12) of the form `name.form.t` (B.3). `form` is `checked`, `wrap` or `sat`, and `t` is the token of the operand type: the type's name in lower case (`i8`, `u64`, `i128`), or `q<i>_<f>` for the fixed-point type `Q<i>.<f>` (`q16_16`). An operation that rounds adds the rounding mode it used: `mul.checked.q16_16.half_even`. Annex B lists every operation identifier, and 8.1 describes the whole record."
  },
  {
   "id": "spec-04p:precedence-and-associativity",
   "edition": "SPEC-04P.2",
   "title": "6.7.1 Precedence and associativity",
   "clauses": "LS-149",
   "url": "/specifications/spec-04p/2/#precedence-and-associativity",
   "internal": 0,
   "content": "#### 6.7.1 Precedence and associativity\n\nWhen an expression has no parentheses, the precedence of its operators decides which operands each operator takes, and their associativity decides how operators of one level group. The order is close to C's. The differences are: the bitwise operators bind tighter than the comparisons; comparisons do not chain, and some mixtures need parentheses (6.7.2); a conversion binds tighter than the binary operators; `catch` binds loosest; and assignment is a statement (6.7.14).\n\n**Syntax**\n\n```ebnf\nexpr         = cond_expr [ \"catch\" ( \"(\" IDENT \")\" block | cond_expr ) ] ;\ncond_expr    = or_expr [ \"?\" expr \":\" cond_expr ] ;\nor_expr      = and_expr { \"||\" and_expr } ;\nand_expr     = cmp_expr { \"&&\" cmp_expr } ;\ncmp_expr     = bor_expr [ cmp_op bor_expr ] ;\nbor_expr     = bxor_expr { \"|\" bxor_expr } ;\nbxor_expr    = band_expr { \"^\" band_expr } ;\nband_expr    = shift_expr { \"&\" shift_expr } ;\nshift_expr   = add_expr { ( \"<<\" | \">>\" | \"<<%\" ) add_expr } ;\nadd_expr     = mul_expr { ( \"+\" | \"-\" | \"+%\" | \"-%\" | \"+|\" | \"-|\" ) mul_expr } ;\nmul_expr     = conv_expr { ( \"*\" | \"/\" | \"%\" | \"*%\" | \"*|\" ) conv_expr } ;\nconv_expr    = unary_expr { conv_op type [ round_clause ] } ;\nconv_op      = \"as\" | \"as%\" | \"as?\" ;\nunary_expr   = neg_literal | ( \"-\" | \"-%\" | \"~\" | \"!\" | \"try\" ) unary_expr | postfix_expr ;\npostfix_expr = ( call | primary ) { \"[\" index_list \"]\" | \".\" IDENT } ;\n```\n\n**Semantics**\n\n1. <a id=\"LS-149\"></a>The operators have these levels, from the tightest to the loosest [LS-149]:"
  },
  {
   "id": "spec-04p:precedence-and-associativity-p1",
   "edition": "SPEC-04P.2",
   "title": "6.7.1 Precedence and associativity (part 2)",
   "clauses": "LS-149 LS-150",
   "url": "/specifications/spec-04p/2/#precedence-and-associativity",
   "internal": 0,
   "content": "| Level | Operators | Grouping | Defined in |\n|---|---|---|---|\n| 1 | call `f(...)`, index `a[...]`, member `x.f` | left to right | 6.7.4 |\n| 2 | unary `-` `-%` `~` `!` `try` | right to left | 6.7.5, 6.11 |\n| 3 | `as` `as%` `as?`, each with an optional `round` clause | left to right | 6.6 |\n| 4 | `*` `/` `%` `*%` `*\\|` | left to right | 6.7.7 |\n| 5 | `+` `-` `+%` `-%` `+\\|` `-\\|` | left to right | 6.7.6 |\n| 6 | `<<` `>>` `<<%` | left to right | 6.7.8 |\n| 7 | `&` | left to right | 6.7.9 |\n| 8 | `^` | left to right | 6.7.9 |\n| 9 | `\\|` | left to right | 6.7.9 |\n| 10 | `==` `!=` `<` `<=` `>` `>=` | none | 6.7.10 |\n| 11 | `&&` | left to right | 6.7.11 |\n| 12 | `\\|\\|` | left to right | 6.7.11 |\n| 13 | `? :` | right to left | 6.7.13 |\n| 14 | `catch` | none | 6.11 |\n\n2. An operator of a tighter level takes its operands before an operator of a looser level: `a + b * c` is `a + (b * c)`, and `b + a as I64` is `b + (a as I64)`. Operators of one level group as the table says: `a - b - c` is `(a - b) - c`, and `p ? x : q ? y : z` is `p ? x : (q ? y : z)` [LS-149].\n3. The two levels without grouping do not chain. A comparison whose operand is an unparenthesized comparison is rejected (6.7.2), and a second `catch` after a fallback, as in `f() catch 0 catch 1`, is a syntax error (C1050) [LS-149].\n4. Parentheses override the levels: a parenthesized expression is one operand, whatever operators it contains [LS-149].\n5. <a id=\"LS-150\"></a>The bitwise operators bind tighter than the comparisons, so `flags & MASK == 0` is `(flags & MASK) == 0` [LS-150].\n6. A few combinations that the levels would accept are rejected unless they are parenthesized (6.7.2).\n\n**Examples**\n\n7. This example shows levels and grouping:\n\n```cint prec_basic.ci\nI64 a = 2 + 3 * 4;\nI64 b = 10 - 4 - 3;\nI64 c = 100 / 10 / 5;\nI64 d = -2 * 3;\nI32 n = 7;\nI64 e = a + n as I64;\n\"{a} {b} {c} {d} {e}\\n\";\n```"
  },
  {
   "id": "spec-04p:precedence-and-associativity-p2",
   "edition": "SPEC-04P.2",
   "title": "6.7.1 Precedence and associativity (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#precedence-and-associativity",
   "internal": 0,
   "content": "```text\n14 3 2 -6 21\n```\n\n8. A bitwise operation inside a comparison needs no parentheses:\n\n```cint prec_flags.ci\nU8 flags = 6;\nU8 mask = 1;\nBool clear = flags & mask == 0;\n\"{clear}\\n\";\n```\n\n```text\ntrue\n```\n\n9. `catch` (6.7.12) binds loosest of all, so its fallback here is `0 + 1`, not `0`:\n\n```cint prec_catch.ci\nI64 big = I64.max;\nI64 v = add_result(big, 1) catch 0 + 1;\n\"{v}\\n\";\n```\n\n```text\n1\n```\n\n**Notes**\n\n10. In C, `==` binds tighter than `&`, so `flags & mask == 0` means `flags & (mask == 0)`. The same text in cint tests the masked bits."
  },
  {
   "id": "spec-04p:required-parentheses-and-unchained-comparisons",
   "edition": "SPEC-04P.2",
   "title": "6.7.2 Required parentheses and unchained comparisons",
   "clauses": "IM-48 LS-151 LS-153",
   "url": "/specifications/spec-04p/2/#required-parentheses-and-unchained-comparisons",
   "internal": 0,
   "content": "#### 6.7.2 Required parentheses and unchained comparisons\n\nSome combinations of operators are often misread, or are read one way by a C programmer and another way by a reader of other languages. cint rejects them until parentheses say which grouping is meant.\n\n**Constraints**\n\n1. <a id=\"LS-151\"></a>Each of these combinations shall be parenthesized. Without the parentheses it is diagnosed C2101, at the first character of the expression that needs them [LS-151]:\n   - `&&` and `||` in one expression: `a && b || c`;\n   - a shift with an operand that is an arithmetic operation (`+`, `-`, `*`, `/` or `%`, in any form): `1 << n + 1`;\n   - a bitwise operator (`&`, `|` or `^`) with an operand that is an arithmetic operation: `a & b + 1`;\n   - two different bitwise operators: `a & b | c`;\n   - a unary operator `-`, `-%`, `~` or `!` directly followed by a conversion: `-x as I32`, whatever the values involved.\n2. A negative literal (6.4.5) is one operand, not a unary operator applied to a literal, so `-1 as% U64` and `- 1 as% U64` need no parentheses [LS-151].\n3. <a id=\"LS-153\"></a>An operand of a comparison shall not be an unparenthesized comparison: `a < b < c`, `0 <= i < n` and `a == b == c` are diagnosed C2102, at the first character of the expression. A parenthesized comparison is an ordinary `Bool` operand, so `(a < b) == c` is valid when `c` is a `Bool` [LS-153, IM-48].\n\n**Examples**\n\n4. This example shows mixed `&&` and `||`:\n\n```cint paren_logic.ci\nBool a = true;\nBool b = false;\nBool c = true;\nBool d = a && b || c;\n\"{d}\\n\";\n```\n\n```text\nerror[C2101]: parentheses required\n  --> paren_logic.ci:4:10\n   |\n 4 | Bool d = a && b || c;\n   |          ^\n```\n\n5. This example shows the same operations with the parentheses in place. A shift or a comparison as the operand of a bitwise operator needs none, and neither does a negative literal before a conversion:"
  },
  {
   "id": "spec-04p:required-parentheses-and-unchained-comparisons-p1",
   "edition": "SPEC-04P.2",
   "title": "6.7.2 Required parentheses and unchained comparisons (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#required-parentheses-and-unchained-comparisons",
   "internal": 0,
   "content": "```cint paren_ok.ci\nBool a = true;\nBool b = false;\nBool c = true;\nI64 n = 3;\nI64 x = 5;\nU8 m = 12;\nBool d = (a && b) || c;\nI64 s = 1 << (n + 1);\nU8 t = (m & 10) | 3;\nBool z = m << 1 & 3 == 0;\nU64 u = -1 as% U64;\nI8 v = (-x) as% I8;\n\"{d} {s} {t} {z} {u} {v}\\n\";\n```\n\n```text\ntrue 16 11 true 18446744073709551615 -5\n```\n\n6. This example shows a unary operator directly before a conversion:\n\n```cint paren_unary.ci\nI64 x = 5;\nI32 y = -x as I32;\n\"{y}\\n\";\n```\n\n```text\nerror[C2101]: parentheses required\n  --> paren_unary.ci:2:9\n   |\n 2 | I32 y = -x as I32;\n   |         ^\n```\n\n7. This example shows a chained comparison:\n\n```cint paren_chain.ci\nI64 i = 5;\nI64 n = 10;\nBool ok = 0 <= i < n;\n\"{ok}\\n\";\n```\n\n```text\nerror[C2102]: chained comparison\n  --> paren_chain.ci:3:11\n   |\n 3 | Bool ok = 0 <= i < n;\n   |           ^\n```\n\n**Notes**\n\n8. In C, `0 <= i < n` compiles: it compares the result of `0 <= i`, which is 0 or 1, with `n`, and so is true for every `i` when `n` is greater than 1.\n9. A program writes `(-x) as I32` or `-(x as I32)`, whichever is meant, in place of `-x as I32`, and `0 <= i && i < n` in place of `0 <= i < n`."
  },
  {
   "id": "spec-04p:primary-expressions",
   "edition": "SPEC-04P.2",
   "title": "6.7.3 Primary expressions",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#primary-expressions",
   "internal": 0,
   "content": "#### 6.7.3 Primary expressions\n\nA primary expression is an operand that no operator builds: a literal, a name, a parenthesized expression, an array literal, an error value typed by its context, or a property of a type. Each is defined where its type is; this subclause collects them.\n\n**Syntax**\n\n```ebnf\nprimary      = literal\n             | STRING { STRING }\n             | IDENT\n             | ( INT_TYPE | \"Bool\" | FIXED_TYPE ) [ \".\" IDENT ]\n             | FIXED_TYPE \".\" \"raw\" \"(\" [ args ] \")\"\n             | \"(\" expr \")\"\n             | array_literal\n             | \".\" IDENT ;\nliteral      = INT_LIT | CHAR_LIT | FRAC_LIT [ round_clause ] | bool_literal ;\n```\n\n`bool_literal` is defined in 6.3.3 and `array_literal` in 6.12.1. A `STRING` operand is a string literal passed as an argument (6.4.8).\n\n**Semantics**\n\n1. A literal denotes a value in Z, or a rational number for a fraction literal. It has no type of its own and takes the type of its context (6.4.5 to 6.4.8, 6.5). A fraction literal appears only where the context is a fixed-point type, and one that is not on that type's grid needs a `round` clause (6.4.6, 6.7.15).\n2. A name denotes a variable, constant, parameter, function, type or imported module in scope (6.2.3). As an operand, a variable or a parameter gives its current value.\n3. A parenthesized expression has the type and the value of the expression it encloses. Parentheses group (6.7.1) and do not convert, and a literal in parentheses is still a literal operand (6.5).\n4. An array literal `[a, b, c]` lists the elements of an array in order; nested array literals give arrays of rank 2 and above (6.12.1).\n5. `.name` is a value of an error set, typed by its context (6.3.7, 6.11).\n6. `T.min` and `T.max` give the bounds of the integer or fixed-point type `T` (6.3.1, 6.3.2), and `Q<i>.<f>.raw(n)` gives the fixed-point value whose raw value is `n` (6.3.2)."
  },
  {
   "id": "spec-04p:primary-expressions-p1",
   "edition": "SPEC-04P.2",
   "title": "6.7.3 Primary expressions (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#primary-expressions",
   "internal": 0,
   "content": "**Examples**\n\n7. A type property, a parenthesized operand and a character literal typed by its context:\n\n```cint primary.ci\nI8 top = I8.max;\nI64 x = (2 + 3) * 4;\nU8 c = 'A';\n\"{top} {x} {c}\\n\";\n```\n\n```text\n127 20 65\n```"
  },
  {
   "id": "spec-04p:postfix-expressions",
   "edition": "SPEC-04P.2",
   "title": "6.7.4 Postfix expressions",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#postfix-expressions",
   "internal": 0,
   "content": "#### 6.7.4 Postfix expressions\n\nA postfix expression is a call or a primary expression, followed by any number of indexes and member selections. They bind tighter than every other operator and are read from left to right.\n\n**Syntax**\n\n```ebnf\npostfix_expr = ( call | primary ) { \"[\" index_list \"]\" | \".\" IDENT } ;\ncall         = IDENT [ \".\" IDENT ] \"(\" [ args ] \")\" ;\nargs         = arg { \",\" arg } [ \",\" ] ;\narg          = [ IDENT \"=\" ] expr ;\nindex_list   = index { \",\" index } ;\nindex        = expr\n             | [ expr ] \"..\" [ expr ] [ \"by\" expr ]\n             | [ expr ] \"..=\" expr [ \"by\" expr ] ;\n```\n\n**Constraints**\n\n1. The callee of a call shall name a function, a built-in operation, a struct type (a constructor, 6.9.6) or a kernel (a dispatch, 6.13.4), either directly or after the name or alias of an imported module (`alias.f`, 6.15.1); or, after the name of an arena or a pool, one of its members, such as `scratch.alloc(4)` (6.14). A callee name that denotes anything else, such as a variable, is diagnosed C3007.\n\n**Semantics**"
  },
  {
   "id": "spec-04p:postfix-expressions-p1",
   "edition": "SPEC-04P.2",
   "title": "6.7.4 Postfix expressions (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#postfix-expressions",
   "internal": 0,
   "content": "2. Postfix operators bind tighter than every other operator and apply from left to right, as 6.7.1 states: `-grid[0, 1]` is `-(grid[0, 1])`, and `p.x + p.y` adds two fields.\n3. A call evaluates its arguments from left to right, each completely, and then calls the function (6.2.4). Arguments match parameters by position, or by name, written `name = value` (6.9.5). Calling a struct type with values for its fields builds a struct value (6.9.6).\n4. A built-in operation is called with the same syntax (clause 7). Some built-in operations take a type or a rounding-mode name as an argument; that argument is a bare name, not a value (6.7.15, 7.1).\n5. A call of a function that returns no result (`void`) has no value. It stands only as a statement (6.10.1); as an operand it is diagnosed C2001.\n6. `a[i]` gives an element of an array or view, `m[i, j]` an element of an array of rank 2, and `a[lo..hi]` a slice. Their meaning and their faults are in 6.12.2 and 6.12.3.\n7. `s.f` gives the field `f` of the struct value `s` (6.3.6, 6.9.6).\n8. `++` and `--` are statements, not postfix operators (6.7.14).\n\n**Examples**\n\n9. This example shows a call, two fields, an element of a rank-2 array and a negated element:\n\n```cint postfix.ci\nstruct Point {\n    I64 x;\n    I64 y;\n}\nI64 area(I64 width, I64 height) {\n    return width * height;\n}\nvoid main() {\n    I64[2, 3] grid = [[1, 2, 3], [4, 5, 6]];\n    Point p = Point(3, 4);\n    \"{area(2, 5)} {p.x + p.y} {grid[1, 2]} {-grid[0, 1]}\\n\";\n}\n```\n\n```text\n10 7 6 -2\n```\n\n10. Precedence decides which operands an operator takes, not when they are evaluated. The operands below are evaluated from left to right, although `*` is applied before `+`:\n\n```cint postfix_order.ci\nI64 trace(I64 k) {\n    \"{k} \";\n    return k;\n}\nI64 v = trace(1) + trace(2) * trace(3);\n\"= {v}\\n\";\n```\n\n```text\n1 2 3 = 7\n```"
  },
  {
   "id": "spec-04p:unary-operators",
   "edition": "SPEC-04P.2",
   "title": "6.7.5 Unary operators",
   "clauses": "IM-34 IM-47 IM-60",
   "url": "/specifications/spec-04p/2/#unary-operators",
   "internal": 0,
   "content": "#### 6.7.5 Unary operators\n\n`-` negates, `-%` negates with wrapping, `~` complements the bits of an integer, and `!` negates a `Bool`. The absolute value is the built-in operation `abs`, checked like `-`, and `uabs` gives it in the unsigned type of the same width, where it always fits.\n\n**Syntax**\n\n```ebnf\nunary_expr   = neg_literal\n             | ( \"-\" | \"-%\" | \"~\" | \"!\" | \"try\" ) unary_expr\n             | postfix_expr ;\n```\n\n`abs(a)` and `uabs(a)` are calls (6.7.4). `try` is defined in 6.11.\n\n**Constraints**\n\n1. <a id=\"IM-60\"></a>The operand of `-` shall have an integer or a fixed-point type. The operand of `-%` and of `~` shall have an integer type. Any other operand type is diagnosed C2103 [IM-47, IM-60].\n2. The operand of `!` shall have type `Bool` (6.3.3); any other type is diagnosed C2002.\n3. <a id=\"IM-34\"></a>The argument of `abs` shall have an integer or a fixed-point type. The argument of `uabs` shall have a signed integer type from `I8` to `I512`; any other type, `I1024` included, is diagnosed C2103 [IM-34].\n4. A `-` directly before a numeric or character literal forms a negative literal (6.4.5), which is one operand and not a negation.\n\n**Semantics**"
  },
  {
   "id": "spec-04p:unary-operators-p1",
   "edition": "SPEC-04P.2",
   "title": "6.7.5 Unary operators (part 2)",
   "clauses": "IM-28 IM-33 IM-34 IM-47 IM-60",
   "url": "/specifications/spec-04p/2/#unary-operators",
   "internal": 0,
   "content": "5. <a id=\"IM-33\"></a>`-a` is the checked negation: the result is `-a` when `in(T, -a)`, and otherwise the operation faults. For a signed type only `-MIN(T)` is out of range; for an unsigned type, `-a` faults for every `a` other than 0 [IM-33].\n6. `-%a` is `wrap(T, -a)`, the same value as `0 -% a`. It never faults. The saturating negation is written `0 -| a` [IM-28].\n7. `~a` inverts every bit of the two's complement pattern of `a`, of width `w`, and has type `T`. So `~a` is `-a - 1` for a signed type and `MAX(T) - a` for an unsigned type. It never faults [IM-47].\n8. `!b` is `true` when `b` is `false`, and `false` when `b` is `true`.\n9. `abs(a)` is the checked absolute value: `|a|` when it is in range, and a fault for `abs(MIN(T))` [IM-34].\n10. `uabs(a)` is `|a|` as a value of the unsigned type of the same width: `I8` gives `U8`, and so on up to `I512`, which gives `U512`. It never faults [IM-34].\n11. On a fixed-point operand, `-a` and `abs(a)` act on the raw value with the integer meaning above. Nothing rounds [IM-60].\n\n**Faults**\n\n12. The fault `E_OVERFLOW` is raised by `-a` when `-a` is out of range. The record holds the operation identifier `neg.checked.t`, the one operand, the exact result `-a`, and the bound it crossed as the limit. Its position is the `-` token [IM-33].\n13. The fault `E_OVERFLOW` is raised by `abs(a)` when `|a|` is out of range. The record holds `abs.checked.t`, the operand, the exact result `|a|` and the limit `MAX(T)`. Its position is the callee name `abs` [IM-34].\n\n**Examples**\n\n14. This example shows negation, complement and the two absolute values:\n\n```cint unary.ci\nI8 s = 5;\nU8 a = 0b1100;\nI8 m = -128;\n\"{-s} {~s} {~a} {~m}\\n\";\n\"{abs(m + 1)} {uabs(m)}\\n\";\n```\n\n```text\n-5 -6 243 127\n127 128\n```\n\n15. An unsigned value has no negation other than 0:\n\n```cint neg_unsigned.ci\nU8 zero = 0;\nU8 one = 1;\n\"{-zero}\\n\";\nU8 b = -one;\n\"{b}\\n\";\n```"
  },
  {
   "id": "spec-04p:unary-operators-p2",
   "edition": "SPEC-04P.2",
   "title": "6.7.5 Unary operators (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#unary-operators",
   "internal": 0,
   "content": "```text\n0\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> neg_unsigned.ci:4:8\n   |\n 4 | U8 b = -one;\n   |        ^ neg.checked.u8\n   |\n   = operation: neg.checked.u8\n   = operand-count: 1\n   = operand: U8 1\n   = exact:   -1\n   = limit:   U8 0\n   ...\n```\n\n16. This example shows `abs` of the minimum of a signed type:\n\n```cint abs_min.ci\nI8 m = -128;\nI8 c = abs(m);\n\"{c}\\n\";\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> abs_min.ci:2:8\n   |\n 2 | I8 c = abs(m);\n   |        ^ abs.checked.i8\n   |\n   = operation: abs.checked.i8\n   = operand-count: 1\n   = operand: I8 -128\n   = exact:   128\n   = limit:   I8 127\n   ...\n```\n\n17. This example shows wrapping and saturating negation of `I64.min`:\n\n```cint neg_forms.ci\nI64 m = I64.min;\nI64 x = 5;\n\"{-%x} {-%m} {0 -| m}\\n\";\n```\n\n```text\n-5 -9223372036854775808 9223372036854775807\n```\n\n18. This example shows `uabs` of a wide type, and negation and `abs` on fixed point:\n\n```cint unary_wide_fixed.ci\nI128 w = I128.min;\nU128 u = uabs(w);\nQ16.16 q = -2.5;\n\"{u} {-q} {abs(q)}\\n\";\n```\n\n```text\n170141183460469231731687303715884105728 2.5 2.5\n```\n\n19. The minimum of `Q16.16` has no negation. The record holds raw values: the exact result, raw 2147483648, is 32768.0, one raw unit above the maximum:\n\n```cint neg_fixed_min.ci\nQ16.16 m = Q16.16.min;\nQ16.16 n = -m;\n\"{n}\\n\";\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> neg_fixed_min.ci:2:12\n   |\n 2 | Q16.16 n = -m;\n   |            ^ neg.checked.q16_16\n   |\n   = operation: neg.checked.q16_16\n   = operand-count: 1\n   = operand: Q16.16 raw -2147483648\n   = exact:   2147483648\n   = limit:   Q16.16 raw 2147483647\n   ...\n```\n\n**Notes**"
  },
  {
   "id": "spec-04p:unary-operators-p3",
   "edition": "SPEC-04P.2",
   "title": "6.7.5 Unary operators (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#unary-operators",
   "internal": 0,
   "content": "20. In C, negating an unsigned value wraps without notice, and `abs(INT_MIN)` is undefined behavior. In cint the first faults unless the value is 0, and the second faults; `-%` and `uabs` give the wrapped value and the unsigned magnitude when a program wants them."
  },
  {
   "id": "spec-04p:additive-operators",
   "edition": "SPEC-04P.2",
   "title": "6.7.6 Additive operators",
   "clauses": "IM-29 LS-152 LS-156",
   "url": "/specifications/spec-04p/2/#additive-operators",
   "internal": 0,
   "content": "#### 6.7.6 Additive operators\n\n`+` adds and `-` subtracts. Each has three spellings that differ only in what happens when the exact result is outside the range of the type: the plain operator faults, the wrapping operator reduces the result modulo 2^`w`, and the saturating operator clamps it to the nearer bound. On fixed-point operands the six operators act on the raw values and do not round.\n\n**Syntax**\n\n```ebnf\nadd_expr = mul_expr { ( \"+\" | \"-\" | \"+%\" | \"-%\" | \"+|\" | \"-|\" ) mul_expr } ;\n```\n\n**Constraints**\n\n1. <a id=\"IM-29\"></a>Both operands shall have the same integer type, or the same fixed-point type, after a literal operand takes its type from the other operand (6.5). There is no implicit conversion: mixing `I32` with `I64`, `I64` with `U64` or `Q16.16` with `I32` or with another fixed-point type, is diagnosed C2001 [IM-29, LS-156].\n2. <a id=\"LS-152\"></a>The six operators have the same precedence and group from left to right, so plain, wrapping and saturating forms may be mixed: `a +% b + c` is `(a +% b) + c` [LS-152].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:additive-operators-p1",
   "edition": "SPEC-04P.2",
   "title": "6.7.6 Additive operators (part 2)",
   "clauses": "IM-30 IM-32 IM-60",
   "url": "/specifications/spec-04p/2/#additive-operators",
   "internal": 0,
   "content": "3. <a id=\"IM-32\"></a>The result has the type `T` of the operands. Let `v` be `a + b` or `a - b`, computed in Z [IM-32].\n4. <a id=\"IM-30\"></a>For `+` and `-`, the result is `v` when `in(T, v)`. Otherwise the operation faults [IM-30].\n5. For `+%` and `-%`, the result is `wrap(T, v)` [IM-30].\n6. For `+|` and `-|`, the result is `sat(T, v)` [IM-30].\n7. For an unsigned type, `a - b` with `a < b` has a negative exact result and therefore faults; `a -% b` wraps and `a -| b` gives 0 [IM-32].\n8. When `T` is a fixed-point type, the operators act on the raw values `A` and `B` of the operands (6.3.2): `v` is `A + B` or `A - B`, paragraphs 4 to 6 apply to `v` with the range of the raw values, and the result is the value of `T` whose raw value that gives. Nothing rounds. A literal operand denotes its exact value in `T`, so with `a` of type `Q16.16`, `a + 1` adds 1.0 [IM-60].\n9. For an integer type, the result forms `add_result(a, b)` and `sub_result(a, b)` give `v` when it is in range and the error `ArithError.overflow` otherwise (6.7.12).\n\n**Faults**\n\n10. The fault `E_OVERFLOW` is raised by `+` or `-` when `v` is outside the range of `T`. The fault record holds the operation identifier `add.checked.t` or `sub.checked.t`, where `t` is the token of `T` (`i64`, `u8`, `i128`, `q16_16`); both operands; the exact result `v`; and, as the limit, the bound that `v` crossed. For a fixed-point `T`, the exact result and the limit are raw values. Its position is the operator token. The wrapping and saturating forms raise no fault.\n\n**Examples**\n\n11. This example shows results at the edge of `I64`, whose maximum is 9223372036854775807, and of `U8`:\n\n```cint additive.ci\nI64 big = I64.max;\n\"{big +% 1}\\n\";\n\"{big +| 1}\\n\";\nU8 a = 3;\nU8 b = 5;\n\"{a -% b} {a -| b}\\n\";\n```\n\n```text\n-9223372036854775808\n9223372036854775807\n254 0\n```\n\n12. The plain operator stops the program instead:"
  },
  {
   "id": "spec-04p:additive-operators-p2",
   "edition": "SPEC-04P.2",
   "title": "6.7.6 Additive operators (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#additive-operators",
   "internal": 0,
   "content": "```cint additive_fault.ci\nU8 a = 3;\nU8 b = 5;\nU8 d = a - b;\n\"{d}\\n\";\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> additive_fault.ci:3:10\n   |\n 3 | U8 d = a - b;\n   |          ^ sub.checked.u8\n   |\n   = operation: sub.checked.u8\n   = operand-count: 2\n   = operand: U8 3\n   = operand: U8 5\n   = exact:   -2\n   = limit:   U8 0\n   ...\n```\n\n13. This example shows the same rule at 128 bits:\n\n```cint additive_wide.ci\nI128 top = I128.max;\n\"{top +% 1}\\n\";\nI128 c = top + 1;\n\"{c}\\n\";\n```\n\n```text\n-170141183460469231731687303715884105728\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> additive_wide.ci:3:14\n   |\n 3 | I128 c = top + 1;\n   |              ^ add.checked.i128\n   |\n   = operation: add.checked.i128\n   = operand-count: 2\n   = operand: I128 170141183460469231731687303715884105727\n   = operand: I128 1\n   = exact:   170141183460469231731687303715884105728\n   = limit:   I128 170141183460469231731687303715884105727\n   ...\n```\n\n14. Fixed-point sums, a literal operand and the two other forms at the top of `Q16.16`, whose raw values are those of `I32`:\n\n```cint additive_fixed.ci\nQ16.16 a = 0.75;\nQ16.16 b = 1.5;\n\"{a + b} {a - b} {(a - b).raw} {a + 1}\\n\";\nQ16.16 big = Q16.16.max;\nQ16.16 step = Q16.16.raw(1);\n\"{big +| step} {big +% step}\\n\";\n```\n\n```text\n2.25 -0.75 -49152 1.75\n32767.9999847412109375 -32768.0\n```\n\n15. The checked sum one raw unit past the top of `Q16.16`. The operands, the exact result and the limit are raw values:\n\n```cint additive_fixed_fault.ci\nQ16.16 big = Q16.16.max;\nQ16.16 step = Q16.16.raw(1);\nQ16.16 c = big + step;\n\"{c}\\n\";\n```"
  },
  {
   "id": "spec-04p:additive-operators-p3",
   "edition": "SPEC-04P.2",
   "title": "6.7.6 Additive operators (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#additive-operators",
   "internal": 0,
   "content": "```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> additive_fixed_fault.ci:3:16\n   |\n 3 | Q16.16 c = big + step;\n   |                ^ add.checked.q16_16\n   |\n   = operation: add.checked.q16_16\n   = operand-count: 2\n   = operand: Q16.16 raw 2147483647\n   = operand: Q16.16 raw 1\n   = exact:   2147483648\n   = limit:   Q16.16 raw 2147483647\n   ...\n```\n\n**Notes**\n\n16. In C, signed overflow of `+` is undefined behavior and unsigned arithmetic wraps without notice. In cint both fault, and a program that wants wrapping says so with `+%`."
  },
  {
   "id": "spec-04p:multiplicative-operators",
   "edition": "SPEC-04P.2",
   "title": "6.7.7 Multiplicative operators",
   "clauses": "IM-29 IM-66 LS-156 LS-160",
   "url": "/specifications/spec-04p/2/#multiplicative-operators",
   "internal": 0,
   "content": "#### 6.7.7 Multiplicative operators\n\n`*` multiplies, `/` divides and `%` gives the remainder. Integer `/` rounds the quotient toward negative infinity, called floor division, and `%` gives the remainder that goes with it, which has the sign of the divisor. On fixed-point operands, `*` and `/` form the exact product or quotient and round it once, half to even unless another mode is named.\n\n**Syntax**\n\n```ebnf\nmul_expr = conv_expr { ( \"*\" | \"/\" | \"%\" | \"*%\" | \"*|\" ) conv_expr } ;\n```\n\n**Constraints**\n\n1. Both operands shall have the same integer type, or for `*`, `*%`, `*|` and `/` the same fixed-point type, after a literal operand takes its type from the other operand (6.5). Mixing two types is diagnosed C2001, including two fixed-point types of different formats and a fixed-point type with an integer type. The built-in operations `qmul` and `mul_int` multiply such pairs (7.2.4) [IM-29, LS-156].\n2. <a id=\"LS-160\"></a><a id=\"IM-66\"></a>`%` is not defined on fixed point; a fixed-point operand of `%` is diagnosed C2103 [LS-160, IM-66].\n3. The five operators have the same precedence and group from left to right, as 6.7.1 states: `a / b * c` is `(a / b) * c`.\n\n**Semantics**"
  },
  {
   "id": "spec-04p:multiplicative-operators-p1",
   "edition": "SPEC-04P.2",
   "title": "6.7.7 Multiplicative operators (part 2)",
   "clauses": "IM-30 IM-32 IM-35 IM-39 IM-40 IM-41 IM-44 IM-61 IM-62 IM-65 IM-66 LS-158",
   "url": "/specifications/spec-04p/2/#multiplicative-operators",
   "internal": 0,
   "content": "4. On integers, let `v` be `a * b` computed in Z. `*` gives `v` when `in(T, v)` and otherwise faults; `*%` gives `wrap(T, v)`; `*|` gives `sat(T, v)` [IM-32, IM-30].\n5. <a id=\"IM-35\"></a><a id=\"LS-158\"></a>For `b` other than 0, `a / b` is `floor(a / b)`: the rational quotient rounded toward negative infinity [IM-35, LS-158].\n6. For `b` other than 0, `a % b` is `a - b * (a / b)`. So `a == (a / b) * b + a % b` holds, `|a % b| < |b|`, and a remainder other than 0 has the sign of the divisor: `-7 / 2` is -4 and `-7 % 2` is 1 [IM-35, LS-158].\n7. <a id=\"IM-39\"></a>When `b` is 0, `/` and `%` fault, `0 / 0` included [IM-39].\n8. <a id=\"IM-40\"></a>When `T` is signed, `a` is `MIN(T)` and `b` is -1, the quotient `-MIN(T)` is out of range, so `/` faults. The remainder is 0, which is in range, so `MIN(T) % -1` is 0 and does not fault, on every implementation, including one whose processor traps on that division [IM-39, IM-40].\n9. <a id=\"IM-41\"></a>There is no wrapping or saturating form of `/` or `%` [IM-41]. Truncating and Euclidean division are built-in operations (7.2).\n10. <a id=\"LS-159\"></a><a id=\"IM-44\"></a>Integer division under another rounding mode is the built-in operation `div_round(a, b, mode)`: the rational quotient `a / b`, rounded once by `mode` (6.7.15) and then checked against `T`. `div_round(a, b, floor)` equals `a / b`, and `div_round(a, b, trunc)` equals `div_trunc(a, b)` [LS-159, IM-44].\n11. <a id=\"IM-61\"></a><a id=\"IM-62\"></a>On a fixed-point type `Q<i>.<f>`, let `A` and `B` be the raw values of `a` and `b`. `a * b` forms the exact product `A * B`, then the raw result `R = round(A * B / 2^f, half_even)`; `*` checks `R` against the range of the raw values, `*%` wraps it and `*|` saturates it [IM-61, IM-62, LS-160].\n12. <a id=\"IM-65\"></a>On a fixed-point type, `a / b` forms the exact `A * 2^f` and gives the raw result `R = round(A * 2^f / B, half_even)`, checked"
  },
  {
   "id": "spec-04p:multiplicative-operators-p2",
   "edition": "SPEC-04P.2",
   "title": "6.7.7 Multiplicative operators (part 3)",
   "clauses": "IM-32 IM-39 IM-62 IM-66",
   "url": "/specifications/spec-04p/2/#multiplicative-operators",
   "internal": 0,
   "content": "**Faults**\n\n15. The fault `E_OVERFLOW` is raised by `*` when the result is out of range, and by `/` when `a` is `MIN(T)` and `b` is -1. The record holds `mul.checked.t` or `div.checked.t`, both operands, the exact result, and the bound it crossed as the limit. Its position is the operator token [IM-32, IM-39].\n16. The fault `E_DIV_ZERO` is raised by `/` and `%` when `b` is 0. The record holds `div.checked.t` or `rem.checked.t` and both operands; it has no exact result and no limit. Its position is the operator token [IM-39].\n17. On fixed point, the operation identifier also names the rounding mode, written or defaulted: `mul.checked.q16_16.half_even` for `*`, `div.checked.q16_16.floor` for `div(a, b, floor)`. The operands are recorded with their raw values, and the exact result is the rounded raw value `R`. The position is the operator token, or the callee name for `mul` and `div`. `*%`, `*|`, `mul_wrap` and `mul_sat` raise no fault [IM-62, IM-66].\n\n**Examples**\n\n18. This example shows floor division and its remainder for each combination of signs:\n\n```cint floor_div.ci\nI64 a = 7;\nI64 b = 2;\n\"{a / b} {a % b}\\n\";\n\"{-a / b} {-a % b}\\n\";\n\"{a / -b} {a % -b}\\n\";\n\"{-a / -b} {-a % -b}\\n\";\n```\n\n```text\n3 1\n-4 1\n-4 -1\n3 -1\n```\n\n19. `MIN(T) % -1` is 0, and `MIN(T) / -1` faults:\n\n```cint div_min.ci\nI64 m = I64.min;\nI64 neg = -1;\n\"{m % neg}\\n\";\nI64 q = m / neg;\n\"{q}\\n\";\n```\n\n```text\n0\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> div_min.ci:4:11\n   |\n 4 | I64 q = m / neg;\n   |           ^ div.checked.i64\n   |\n   = operation: div.checked.i64\n   = operand-count: 2\n   = operand: I64 -9223372036854775808\n   = operand: I64 -1\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n   ...\n```\n\n20. This example shows a divisor of 0:\n\n```cint div_zero.ci\nI64 a = 5;\nI64 z = 0;\nI64 r = a % z;\n\"{r}\\n\";\n```"
  },
  {
   "id": "spec-04p:multiplicative-operators-p3",
   "edition": "SPEC-04P.2",
   "title": "6.7.7 Multiplicative operators (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#multiplicative-operators",
   "internal": 0,
   "content": "```text\nfault[E_DIV_ZERO]: division by zero\n  --> div_zero.ci:3:11\n   |\n 3 | I64 r = a % z;\n   |           ^ rem.checked.i64\n   |\n   = operation: rem.checked.i64\n   = operand-count: 2\n   = operand: I64 5\n   = operand: I64 0\n   = exact:   none\n   = limit:   none\n   ...\n```\n\n21. This example shows the three forms of `*`:\n\n```cint products.ci\nI32 a = 65536;\nI32 b = 32768;\nI8 c = 100;\nI8 m = -128;\n\"{-a * b} {a *% b} {a *| b}\\n\";\n\"{c *% 3} {m *| -1} {m *% -1}\\n\";\n```\n\n```text\n-2147483648 -2147483648 2147483647\n44 127 -128\n```\n\n22. An intermediate result has the type of its operands, so `a * b / 4` faults at `*` although the final value would fit `I32`. A program that needs the wider product converts first (or calls `muldiv`, 7.2):\n\n```cint no_promotion.ci\nI32 a = 2_000_000_000;\nI32 b = 2;\nI32 d = ((a as I64) * (b as I64) / 4) as I32;\n\"{d}\\n\";\nI32 c = a * b / 4;\n\"{c}\\n\";\n```\n\n```text\n1000000000\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> no_promotion.ci:5:11\n   |\n 5 | I32 c = a * b / 4;\n   |           ^ mul.checked.i32\n   |\n   = operation: mul.checked.i32\n   = operand-count: 2\n   = operand: I32 2000000000\n   = operand: I32 2\n   = exact:   4000000000\n   = limit:   I32 2147483647\n   ...\n```\n\n23. This example shows floor division at 128 bits:\n\n```cint div_wide.ci\nI128 m = I128.min;\n\"{m / 3} {m % 3}\\n\";\n```\n\n```text\n-56713727820156410577229101238628035243 1\n```\n\n24. This example shows fixed-point products and quotients. The raw value 1 times 1.5 is 1.5 raw units, which `half_even` rounds to 2, `floor` to 1 and `ceil` to 2; 1.0 / 3.0 rounds to raw 21845, and three times that is raw 65535, not 1.0:"
  },
  {
   "id": "spec-04p:multiplicative-operators-p4",
   "edition": "SPEC-04P.2",
   "title": "6.7.7 Multiplicative operators (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#multiplicative-operators",
   "internal": 0,
   "content": "```cint fixed_muldiv.ci\nQ16.16 a = 1.5;\nQ16.16 b = 2.25;\n\"{a * b} {b / a}\\n\";\nQ16.16 tiny = Q16.16.raw(1);\n\"{(tiny * a).raw} {mul(tiny, a, floor).raw} {mul(tiny, a, ceil).raw}\\n\";\nQ16.16 one = 1.0;\nQ16.16 three = 3.0;\nQ16.16 third = one / three;\n\"{third} {third.raw} {(third * three).raw} {div(one, three, ceil).raw}\\n\";\n```\n\n```text\n3.375 1.5\n2 1 2\n0.3333282470703125 21845 65535 21846\n```\n\n25. The wrapping and saturating products at the top of `Q16.16`, where 256.0 * 128.0 is 32768.0, one raw unit past the range:\n\n```cint fixed_sat.ci\nQ16.16 a = 256.0;\nQ16.16 b = 128.0;\n\"{a *| b} {a *% b} {mul_sat(a, b, floor)}\\n\";\n```\n\n```text\n32767.9999847412109375 -32768.0 32767.9999847412109375\n```\n\n26. This example shows the checked product of the same operands. The identifier names `half_even`, the mode that `*` uses without writing it, and the exact result is the rounded raw value:\n\n```cint fixed_mul_fault.ci\nQ16.16 a = 256.0;\nQ16.16 b = 128.0;\nQ16.16 c = a * b;\n\"{c}\\n\";\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> fixed_mul_fault.ci:3:14\n   |\n 3 | Q16.16 c = a * b;\n   |              ^ mul.checked.q16_16.half_even\n   |\n   = operation: mul.checked.q16_16.half_even\n   = operand-count: 2\n   = operand: Q16.16 raw 16777216\n   = operand: Q16.16 raw 8388608\n   = exact:   2147483648\n   = limit:   Q16.16 raw 2147483647\n   ...\n```\n\n27. This example shows `%` on fixed point:\n\n```cint fixed_rem.ci\nQ16.16 a = 2.5;\nQ16.16 b = 1.0;\nQ16.16 r = a % b;\n\"{r}\\n\";\n```\n\n```text\nerror[C2103]: operator not defined for the operand type\n  --> fixed_rem.ci:3:12\n   |\n 3 | Q16.16 r = a % b;\n   |            ^\n```\n\n**Notes**"
  },
  {
   "id": "spec-04p:multiplicative-operators-p5",
   "edition": "SPEC-04P.2",
   "title": "6.7.7 Multiplicative operators (part 6)",
   "clauses": "IM-37",
   "url": "/specifications/spec-04p/2/#multiplicative-operators",
   "internal": 0,
   "content": "28. <a id=\"IM-37\"></a>C's integer `/` truncates toward 0, so `-7 / 2` is -3 in C and -4 in cint; the two differ, without any fault, whenever the operands have opposite signs and the division is inexact. Code ported from C writes `div_trunc(a, b)` for C's `a / b` and `rem_trunc(a, b)` for C's `a % b` (7.2) [IM-37].\n29. In C, `INT_MIN / -1` and `INT_MIN % -1` are undefined behavior. In cint the first faults and the second is 0."
  },
  {
   "id": "spec-04p:shifts-and-rotations",
   "edition": "SPEC-04P.2",
   "title": "6.7.8 Shifts and rotations",
   "clauses": "IM-45 IM-60 LS-156",
   "url": "/specifications/spec-04p/2/#shifts-and-rotations",
   "internal": 0,
   "content": "#### 6.7.8 Shifts and rotations\n\n`<<` shifts left and `>>` shifts right. A left shift is a multiplication by a power of 2, checked like `*`; `<<%` keeps the low `w` bits instead. A right shift is a floor division by a power of 2, which never overflows. A shift count outside 0 to `w - 1` faults in every form; it is never reduced modulo `w`. The built-in operations `rotl` and `rotr` rotate the bits of an unsigned integer.\n\n**Syntax**\n\n```ebnf\nshift_expr = add_expr { ( \"<<\" | \">>\" | \"<<%\" ) add_expr } ;\n```\n\n`rotl(a, k)` and `rotr(a, k)` are calls (6.7.4).\n\n**Constraints**\n\n1. The left operand shall have an integer type; a shift of a `Bool` or of a fixed-point value is diagnosed C2103 [IM-60].\n2. <a id=\"IM-45\"></a><a id=\"LS-156\"></a>The count, the right operand, may have any integer type, independent of the type of the left operand. A literal count has type `I64`, and a literal left operand takes its type from the context of the whole shift, not from the count (6.5) [IM-45, LS-156].\n3. The first argument of `rotl` and `rotr` shall have an unsigned integer type; a signed argument is diagnosed C2103. Their count may have any integer type [IM-45].\n4. A shift with an arithmetic operand needs parentheses (6.7.2).\n\n**Semantics**"
  },
  {
   "id": "spec-04p:shifts-and-rotations-p1",
   "edition": "SPEC-04P.2",
   "title": "6.7.8 Shifts and rotations (part 2)",
   "clauses": "IM-185 IM-45 IM-46 LS-156 LS-157",
   "url": "/specifications/spec-04p/2/#shifts-and-rotations",
   "internal": 0,
   "content": "5. The result has the type `T` of the left operand, of width `w`. The type of the count never affects it [IM-45].\n6. <a id=\"LS-157\"></a>The count `k` is compared as a value in Z. Every shift form, `<<%` and `>>` included and `rotl` and `rotr`, require `0 <= k <= w - 1` and fault otherwise. A count is never reduced modulo `w`: `x << 64` on `I64` faults; it does not give `x` and does not give 0 [IM-45, LS-157].\n7. `a << k` is `v = a * 2^k` computed in Z: the result is `v` when `in(T, v)`, and otherwise the operation faults [IM-45, LS-156].\n8. `a <<% k` is `wrap(T, a * 2^k)`: the low `w` bits of the two's complement pattern shifted left [IM-45].\n9. `a >> k` is `floor(a / 2^k)`. For a signed type it is an arithmetic shift and for an unsigned type a logical one. It never overflows [IM-45].\n10. <a id=\"IM-46\"></a>There is no logical right shift of a signed type. `I1024` has no unsigned type of its width [IM-46].\n11. `rotl(a, k)` and `rotr(a, k)` rotate the `w`-bit pattern of `a` left or right by `k` bits [IM-45].\n\n**Faults**\n\n12. <a id=\"IM-185\"></a>The fault `E_SHIFT` is raised by a shift or a rotation whose count `k` is outside 0 to `w - 1`. The record holds `shl.checked.t` for `<<`, `shl.wrap.t` for `<<%`, `shr.checked.t` for `>>` or `rotl.checked.t` or `rotr.checked.t`, where `t` names the type of the left operand only; as operands, the left operand and then the count, the count with its own type; no exact result; and as the limit `w - 1` as an `I64`, for every count out of range, negative counts included. Its position is the operator token, or the callee name of a rotation [IM-45, IM-185].\n13. The fault `E_OVERFLOW` is raised by `<<` when `a * 2^k` is out of range. The record holds `shl.checked.t`, both operands, the exact result `a * 2^k`, and the bound it crossed as the limit. Its position is the operator token [IM-45].\n\n**Examples**"
  },
  {
   "id": "spec-04p:shifts-and-rotations-p2",
   "edition": "SPEC-04P.2",
   "title": "6.7.8 Shifts and rotations (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#shifts-and-rotations",
   "internal": 0,
   "content": "14. This example shows shifts at the edges of `I64` and of the unsigned types:\n\n```cint shifts.ci\nI64 one = 1;\nI64 m1 = -1;\nI64 m7 = -7;\n\"{one << 62} {m1 << 63} {one <<% 63}\\n\";\n\"{m7 >> 1} {m1 >> 63}\\n\";\nU8 x = 255;\nU64 u = U64.max;\n\"{x <<% 4} {u >> 63}\\n\";\n```\n\n```text\n4611686018427387904 -9223372036854775808 -9223372036854775808\n-4 -1\n240 1\n```\n\n15. The count's type does not affect the result, and a literal left operand is typed by its declaration, not by the count:\n\n```cint shift_count.ci\nU8 k = 40;\nI64 v = 1 << k;\nI8 s = 3;\nU8 b = 1;\nU8 w = b << s;\n\"{v} {w}\\n\";\n```\n\n```text\n1099511627776 8\n```\n\n16. This example shows a count equal to the width:\n\n```cint shift_wide_count.ci\nI64 x = 1;\n\"start\\n\";\nI64 v = x << 64;\n\"{v}\\n\";\n```\n\n```text\nstart\nfault[E_SHIFT]: shift count outside 0..w-1\n  --> shift_wide_count.ci:3:11\n   |\n 3 | I64 v = x << 64;\n   |           ^ shl.checked.i64\n   |\n   = operation: shl.checked.i64\n   = operand-count: 2\n   = operand: I64 1\n   = operand: I64 64\n   = exact:   none\n   = limit:   I64 63\n   ...\n```\n\n17. This example shows a negative count, recorded with its own type `I8`:\n\n```cint shift_negative.ci\nI64 x = 1;\nI8 k = -1;\nI64 v = x >> k;\n\"{v}\\n\";\n```\n\n```text\nfault[E_SHIFT]: shift count outside 0..w-1\n  --> shift_negative.ci:3:11\n   |\n 3 | I64 v = x >> k;\n   |           ^ shr.checked.i64\n   |\n   = operation: shr.checked.i64\n   = operand-count: 2\n   = operand: I64 1\n   = operand: I8 -1\n   = exact:   none\n   = limit:   I64 63\n   ...\n```\n\n18. A logical right shift of a signed value, written with a conversion and two rotations:\n\n```cint shift_logical.ci\nI64 a = -8;\nU64 b = (a as% U64) >> 60;\nU32 x = 0x80000001;\n\"{b} {a >> 60}\\n\";\n\"{rotl(x, 1)} {rotr(x, 1)}\\n\";\n```\n\n```text\n15 -1\n3 3221225472\n```\n\n19. This example shows the same rules at 128 bits:\n\n```cint shift_i128.ci\nI128 one = 1;\nI128 v = one << 100;\n\"{v} {v >> 99} {one <<% 127}\\n\";\n```"
  },
  {
   "id": "spec-04p:shifts-and-rotations-p3",
   "edition": "SPEC-04P.2",
   "title": "6.7.8 Shifts and rotations (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#shifts-and-rotations",
   "internal": 0,
   "content": "```text\n1267650600228229401496703205376 2 -170141183460469231731687303715884105728\n```\n\n20. This example shows a logical right shift of an `I128`, through `U128`:\n\n```cint shift_u128.ci\nI128 a = -8;\nU128 b = (a as% U128) >> 124;\n\"{b} {a >> 124}\\n\";\n```\n\n```text\n15 -1\n```\n\n21. This example shows a left shift past the top of `U128`. The count keeps its own type, `I64`:\n\n```cint shift_u128_fault.ci\nU128 top = U128.max;\nU128 v = top << 1;\n\"{v}\\n\";\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> shift_u128_fault.ci:2:14\n   |\n 2 | U128 v = top << 1;\n   |              ^ shl.checked.u128\n   |\n   = operation: shl.checked.u128\n   = operand-count: 2\n   = operand: U128 340282366920938463463374607431768211455\n   = operand: I64 1\n   = exact:   680564733841876926926749214863536422910\n   = limit:   U128 340282366920938463463374607431768211455\n   ...\n```\n\n**Notes**\n\n22. In C, a shift count equal to or greater than the width, or negative, is undefined behavior and x86 processors mask the count to 5 or 6 bits. In cint such a count faults. A left shift of a negative signed value, undefined in C, is the product `a * 2^k` in cint, checked like `*`.\n23. A logical right shift of a signed value converts it to the unsigned type of the same width with `as%` (6.6) first: `(a as% U64) >> k` for `I64`, and `U128` to `U512` for `I128` to `I512`.\n24. The message of `E_SHIFT` writes the valid counts as `0..w-1`, meaning 0 to `w - 1` inclusive."
  },
  {
   "id": "spec-04p:bitwise-operators",
   "edition": "SPEC-04P.2",
   "title": "6.7.9 Bitwise operators",
   "clauses": "IM-47 LS-156",
   "url": "/specifications/spec-04p/2/#bitwise-operators",
   "internal": 0,
   "content": "#### 6.7.9 Bitwise operators\n\n`&`, `|` and `^` combine the bits of two integers of one type: and, or, and exclusive or. They work on the two's complement pattern of the type's width and do not fault.\n\n**Syntax**\n\n```ebnf\nbor_expr  = bxor_expr { \"|\" bxor_expr } ;\nbxor_expr = band_expr { \"^\" band_expr } ;\nband_expr = shift_expr { \"&\" shift_expr } ;\n```\n\n**Constraints**\n\n1. <a id=\"IM-47\"></a>Both operands shall have the same integer type, after a literal operand takes its type from the other operand (6.5); mixing types is diagnosed C2001 [IM-47, LS-156].\n2. The bitwise operators are not defined on `Bool`, where `&&`, `||` and `!` apply (6.7.11) or on fixed point, whose raw values `.raw` gives (6.3.2). Such an operand is diagnosed C2103 [IM-47].\n3. Two different bitwise operators, or a bitwise operator with an arithmetic operand, need parentheses (6.7.2).\n\n**Semantics**\n\n4. `a & b`, `a | b` and `a ^ b` apply and or and exclusive or to each bit of the two's complement patterns of `a` and `b`, of width `w` and give the value of type `T` with the resulting pattern. They never fault [IM-47].\n5. `&` binds tighter than `^`, and `^` tighter than `|`; all three bind tighter than the comparisons (6.7.1).\n\n**Examples**\n\n6. This example shows the three operators, and the patterns of a signed wide type:\n\n```cint bitwise.ci\nU8 a = 0b1100;\nU8 b = 0b1010;\nI128 big = I128.max;\n\"{a & b} {a | b} {a ^ b}\\n\";\n\"{~big} {big & 255} {big ^ big}\\n\";\n```\n\n```text\n8 14 6\n-170141183460469231731687303715884105728 255 0\n```\n\n7. This example shows `&` on `Bool`:\n\n```cint bitwise_bool.ci\nBool a = true;\nBool b = false;\nBool c = a & b;\n\"{c}\\n\";\n```\n\n```text\nerror[C2103]: operator not defined for the operand type\n  --> bitwise_bool.ci:3:10\n   |\n 3 | Bool c = a & b;\n   |          ^\n```\n\n**Notes**"
  },
  {
   "id": "spec-04p:bitwise-operators-p1",
   "edition": "SPEC-04P.2",
   "title": "6.7.9 Bitwise operators (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#bitwise-operators",
   "internal": 0,
   "content": "8. In C, `&` and `|` accept `bool` operands and do not short-circuit. In cint a program writes `&&` or `||` for conditions."
  },
  {
   "id": "spec-04p:comparisons",
   "edition": "SPEC-04P.2",
   "title": "6.7.10 Comparisons",
   "clauses": "IM-48 LS-153",
   "url": "/specifications/spec-04p/2/#comparisons",
   "internal": 0,
   "content": "#### 6.7.10 Comparisons\n\n`==`, `!=`, `<`, `<=`, `>` and `>=` compare two values of one type and give a `Bool`. They compare mathematical values, not bit patterns, and they do not fault.\n\n**Syntax**\n\n```ebnf\ncmp_expr = bor_expr [ cmp_op bor_expr ] ;\ncmp_op   = \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\" ;\n```\n\n**Constraints**\n\n1. <a id=\"IM-48\"></a>Both operands shall have the same type, after a literal operand takes the type of the other operand (6.5). Comparing `I64` with `U64` or with `I32` is diagnosed C2001; a literal that does not fit the other operand's type is diagnosed C2003 [IM-48, LS-153].\n2. `Bool` operands take only `==` and `!=`; the four ordering operators on `Bool` are diagnosed C2103 [IM-48].\n3. Values of an error set take only `==` and `!=` (6.3.7). Arrays, structs, arenas, pools and handles have no comparison operators (6.12, 6.3.6, 6.14).\n4. A comparison does not chain (6.7.2).\n\n**Semantics**\n\n5. A comparison compares the mathematical values of its operands and gives `true` or `false`. It never faults [IM-48].\n6. Values of one fixed-point type compare by their raw values, which orders them as their values are ordered [IM-48].\n\n**Examples**\n\n7. This example shows comparisons at the edges of the range:\n\n```cint compare.ci\nBool a = true;\nBool b = false;\nI64 m = I64.min;\nU64 u = U64.max;\n\"{a == b} {a != b}\\n\";\n\"{m < 0} {u > 0} {u == 18446744073709551615}\\n\";\n```\n\n```text\nfalse true\ntrue true true\n```\n\n8. This example shows a signed and an unsigned operand:\n\n```cint compare_mixed.ci\nI64 a = 5;\nU64 b = 5;\nBool c = a < b;\n\"{c}\\n\";\n```\n\n```text\nerror[C2001]: type mismatch\n  --> compare_mixed.ci:3:14\n   |\n 3 | Bool c = a < b;\n   |              ^\n```\n\n9. The literal takes the type `I8` from `x`, and 1000 is not an `I8`. `(x as I16) < 1000` is the comparison the program means:\n\n```cint compare_literal.ci\nI8 x = 0;\nBool b = x < 1000;\n\"{b}\\n\";\n```"
  },
  {
   "id": "spec-04p:comparisons-p1",
   "edition": "SPEC-04P.2",
   "title": "6.7.10 Comparisons (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#comparisons",
   "internal": 0,
   "content": "```text\nerror[C2003]: literal does not fit its type\n  --> compare_literal.ci:2:14\n   |\n 2 | Bool b = x < 1000;\n   |              ^\n```\n\n10. This example shows fixed-point comparisons, with a literal operand:\n\n```cint compare_fixed.ci\nQ16.16 a = -0.5;\nQ16.16 b = 0.25;\n\"{a < b} {a == b} {a >= b} {b < 1}\\n\";\n```\n\n```text\ntrue false false true\n```\n\n**Notes**\n\n11. In C, comparing a signed with an unsigned operand converts the signed one, so `-1 < 0u` is false. cint rejects the mixed comparison, and the program states the conversion it wants."
  },
  {
   "id": "spec-04p:logical-operators",
   "edition": "SPEC-04P.2",
   "title": "6.7.11 Logical operators",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#logical-operators",
   "internal": 0,
   "content": "#### 6.7.11 Logical operators\n\n`&&` and `||` combine two conditions. Each evaluates its right operand only when the left operand does not already decide the result, so the right operand can rely on what the left one tested. `!` is in 6.7.5.\n\n**Syntax**\n\n```ebnf\nor_expr  = and_expr { \"||\" and_expr } ;\nand_expr = cmp_expr { \"&&\" cmp_expr } ;\n```\n\n**Constraints**\n\n1. Each operand shall have type `Bool` (6.3.3); an operand of another type is diagnosed C2002. An integer `x` is tested as `x != 0`.\n2. `&&` and `||` in one expression need parentheses (6.7.2).\n\n**Semantics**\n\n3. `a && b` is `true` when both operands are `true`. `b` is evaluated only when `a` is `true` (6.2.4).\n4. `a || b` is `true` when either operand is `true`. `b` is evaluated only when `a` is `false` (6.2.4).\n\n**Examples**\n\n5. The right operands divide by `b` only when `b` is not 0:\n\n```cint logical.ci\nI64 a = 5;\nI64 b = 0;\nBool ok = b != 0 && a / b > 1;\nBool ok2 = b == 0 || a / b > 1;\n\"{ok} {ok2}\\n\";\n```\n\n```text\nfalse true\n```\n\n6. An integer is not a condition:\n\n```cint logical_int.ci\nI64 a = 5;\nBool ok = a && true;\n\"{ok}\\n\";\n```\n\n```text\nerror[C2002]: condition is not `Bool`\n  --> logical_int.ci:2:11\n   |\n 2 | Bool ok = a && true;\n   |           ^\n```"
  },
  {
   "id": "spec-04p:result-forms",
   "edition": "SPEC-04P.2",
   "title": "6.7.12 Result forms",
   "clauses": "IM-188 IM-28 IM-29 IM-30",
   "url": "/specifications/spec-04p/2/#result-forms",
   "internal": 0,
   "content": "#### 6.7.12 Result forms\n\nA result form computes what a checked operator computes, but where the operator would fault it returns an error instead. A program uses one where an overflow, a divisor of 0 or a bad shift count is an expected outcome that it handles: the result is an error union (6.3.7), and the program consumes it with `try` or `catch` (6.11).\n\n**Syntax**\n\nThe result forms are calls of built-in operations (6.7.4): `add_result(a, b)`, `sub_result(a, b)`, `mul_result(a, b)`, `div_result(a, b)`, `rem_result(a, b)` and `shl_result(a, k)`. The conversion `x as? T` is the result form of `as` (6.6).\n\n**Constraints**\n\n1. <a id=\"IM-28\"></a>The operands shall have the types the checked operator requires: two integers of one type, a literal operand taking its type from the other operand and two literal operands having type `I64`; for `shl_result`, a left operand of an integer type and a count of any integer type. Two types are diagnosed C2001, and a `Bool` operand C2103 [IM-29, IM-28].\n2. A result form has the type `ArithError!T`, where `T` is the operand type. Like every error union it shall be consumed by `try`, by `catch` or by `_ =` (6.11); a result form used in any other way is diagnosed C2040 [IM-30].\n\n**Semantics**\n\n3. <a id=\"IM-188\"></a>`ArithError` is a built-in error set (6.3.7) with four values, in this order: `overflow`, `div_zero`, `shift` and `narrow`. Its values are numbered 1 to 4 in that order, with an underlying type `U16`. Each value mirrors one fault code: `overflow` mirrors `E_OVERFLOW`, `div_zero` `E_DIV_ZERO`, `shift` `E_SHIFT`, and `narrow` `E_NARROW` [IM-188].\n4. A result form holds the value that its checked operation gives when that operation does not fault, and otherwise the `ArithError` value that mirrors the fault the operation would raise. It never faults [IM-30, IM-188]:"
  },
  {
   "id": "spec-04p:result-forms-p1",
   "edition": "SPEC-04P.2",
   "title": "6.7.12 Result forms (part 2)",
   "clauses": "IM-28",
   "url": "/specifications/spec-04p/2/#result-forms",
   "internal": 0,
   "content": "| Result form | Checked operation | Errors it can hold |\n|---|---|---|\n| `add_result(a, b)` | `a + b` | `overflow` |\n| `sub_result(a, b)` | `a - b` | `overflow` |\n| `mul_result(a, b)` | `a * b` | `overflow` |\n| `div_result(a, b)` | `a / b` | `div_zero`, `overflow` |\n| `rem_result(a, b)` | `a % b` | `div_zero` |\n| `shl_result(a, k)` | `a << k` | `shift`, `overflow` |\n| `x as? T` | `x as T` (6.6) | `narrow` |\n\n5. The result form of a negation is `sub_result(0, a)` [IM-28].\n\n**Examples**\n\n6. This example shows `catch` with a fallback value:\n\n```cint result_catch.ci\nI64 safe_add(I64 a, I64 b) {\n    I64 r = add_result(a, b) catch 0;\n    return r;\n}\n\"{safe_add(1, 2)} {safe_add(I64.max, 1)}\\n\";\n```\n\n```text\n3 0\n```\n\n7. This example shows binding the error with `catch (e)` and switching on it. A `switch` without `default` lists all four values (6.10.5):\n\n```cint result_switch.ci\nvoid show(ArithError e) {\n    switch (e) {\n        case .overflow: \"overflow\\n\";\n        case .div_zero: \"div_zero\\n\";\n        case .shift: \"shift\\n\";\n        case .narrow: \"narrow\\n\";\n    }\n}\nvoid try_div(I64 a, I64 b) {\n    I64 q = div_result(a, b) catch (e) {\n        show(e);\n        return;\n    };\n    \"{q}\\n\";\n}\ntry_div(7, 2);\ntry_div(7, 0);\ntry_div(I64.min, -1);\n```\n\n```text\n3\ndiv_zero\noverflow\n```\n\n8. `try` passes the error to the caller of a function whose result is an error union:\n\n```cint result_try.ci\nArithError!I64 mean(I64 total, I64 n) {\n    I64 q = try div_result(total, n);\n    return q;\n}\nI64 a = mean(10, 3) catch -1;\nI64 b = mean(10, 0) catch -1;\n\"{a} {b}\\n\";\n```\n\n```text\n3 -1\n```\n\n9. Each form holds what its checked operation gives where that operation does not fault: `rem_result(I64.min, -1)` holds 0, as `%` gives 0:"
  },
  {
   "id": "spec-04p:result-forms-p2",
   "edition": "SPEC-04P.2",
   "title": "6.7.12 Result forms (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#result-forms",
   "internal": 0,
   "content": "```cint result_values.ci\nI64 a = rem_result(I64.min, -1) catch 99;\nI64 b = shl_result(1, 64) catch 99;\nU8 c = sub_result(3 as U8, 5 as U8) catch 0;\nI64 d = sub_result(0, I64.min) catch 7;\n\"{a} {b} {c} {d}\\n\";\n```\n\n```text\n0 99 0 7\n```\n\n10. This example shows a result form whose error is not consumed:\n\n```cint result_unused.ci\nI64 a = 5;\nI64 b = add_result(a, 1);\n\"{b}\\n\";\n```\n\n```text\nerror[C2040]: type rule\n  --> result_unused.ci:2:9\n   |\n 2 | I64 b = add_result(a, 1);\n   |         ^\n```\n\n**Notes**\n\n11. A fault stops the run, and program code cannot catch it (5.2.3). A result form is how a program tests for an arithmetic failure that it expects, without stopping."
  },
  {
   "id": "spec-04p:conditional-expression",
   "edition": "SPEC-04P.2",
   "title": "6.7.13 Conditional expression",
   "clauses": "LS-154",
   "url": "/specifications/spec-04p/2/#conditional-expression",
   "internal": 0,
   "content": "#### 6.7.13 Conditional expression\n\n`c ? x : y` gives `x` when the condition `c` is true and `y` otherwise, and evaluates only the operand it gives.\n\n**Syntax**\n\n```ebnf\ncond_expr = or_expr [ \"?\" expr \":\" cond_expr ] ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-154\"></a>The condition `c` shall have type `Bool`; another type is diagnosed C2002 [LS-154].\n2. `x` and `y` shall have the same type; two types are diagnosed C2001. A literal operand takes the type of the other operand, and when both are literals they take the type of the context (6.5) [LS-154].\n\n**Semantics**\n\n3. `c ? x : y` evaluates `c`, then only the operand it selects: `x` when `c` is `true` and `y` when `c` is `false` [LS-154].\n4. The conditional expression groups from right to left, as 6.7.1 states: `p ? x : q ? y : z` is `p ? x : (q ? y : z)`.\n\n**Examples**\n\n5. Only the selected operand runs:\n\n```cint cond.ci\nI64 pick(I64 k) {\n    \"pick {k}\\n\";\n    return k;\n}\nBool yes = true;\nBool no = false;\nI64 v = yes ? pick(1) : pick(2);\nI64 w = no ? 1 : no ? 2 : 3;\n\"{v} {w}\\n\";\n```\n\n```text\npick 1\n1 3\n```\n\n6. A division by 0 in the operand that is not selected does not run:\n\n```cint cond_guard.ci\nBool c = false;\nI64 z = 0;\nU8 v = c ? 1 : 200;\nI64 w = c ? 10 / z : 3;\n\"{v} {w}\\n\";\n```\n\n```text\n200 3\n```\n\n7. This example shows operands of two types:\n\n```cint cond_types.ci\nBool c = true;\nI64 a = 1;\nI32 b = 2;\nI64 v = c ? a : b;\n\"{v}\\n\";\n```\n\n```text\nerror[C2001]: type mismatch\n  --> cond_types.ci:4:17\n   |\n 4 | I64 v = c ? a : b;\n   |                 ^\n```"
  },
  {
   "id": "spec-04p:assignment",
   "edition": "SPEC-04P.2",
   "title": "6.7.14 Assignment, compound assignment, `++` and `--`",
   "clauses": "LS-164 LS-165 LS-166",
   "url": "/specifications/spec-04p/2/#assignment",
   "internal": 0,
   "content": "#### 6.7.14 Assignment, compound assignment, `++` and `--`\n\nAn assignment stores a value in a place. A compound assignment such as `x += y` combines the place's value with another value and stores the result, and `x++` and `x--` add or subtract 1. All of them are statements: none has a value, and none can appear inside an expression.\n\n**Syntax**\n\n```ebnf\nsimple_stmt = place assign_op expr\n            | place ( \"++\" | \"--\" )\n            | [ \"try\" ] call ;\nplace       = IDENT { \".\" IDENT | \"[\" index_list \"]\" } ;\nassign_op   = \"=\" | \"+=\" | \"-=\" | \"*=\" | \"/=\" | \"%=\" | \"<<=\" | \">>=\" | \"&=\" | \"|=\" | \"^=\"\n            | \"+%=\" | \"-%=\" | \"*%=\" | \"<<%=\" | \"+|=\" | \"-|=\" | \"*|=\" ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-164\"></a><a id=\"LS-166\"></a>Assignment, compound assignment, `++` and `--` are statements, not expressions. An assignment written as the condition of an `if` or a `while` is diagnosed C1041, `++` or `--` inside an expression C1042, and an assignment inside any other expression is a syntax error (C1050) [LS-164, LS-166].\n2. The left side shall be a *place*: a variable, an element of an array or view, or a field of a struct, that the program may write. Assigning to a `const` is diagnosed C2058; the parameters that a function may not write are in 6.9.5.\n3. In `p = e`, the value of `e` shall have the type of `p`, a literal taking that type (6.5); another type is diagnosed C2001.\n4. <a id=\"LS-165\"></a>A compound form exists for every binary arithmetic and bitwise operator: `+=`, `-=`, `*=`, `/=`, `%=`, `<<=`, `>>=`, `&=`, `|=`, `^=`, `+%=`, `-%=`, `*%=`, `<<%=`, `+|=`, `-|=` and `*|=`. `p op= e` has the constraints of `p op e` (6.7.6 to 6.7.9) [LS-165].\n5. The place of `++` and `--` shall have an integer type; a `Bool` place is diagnosed C2103 [LS-166].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:assignment-p1",
   "edition": "SPEC-04P.2",
   "title": "6.7.14 Assignment, compound assignment, `++` and `--` (part 2)",
   "clauses": "LS-165 LS-166",
   "url": "/specifications/spec-04p/2/#assignment",
   "internal": 0,
   "content": "6. `p = e` evaluates and checks the subexpressions of the place, such as its indices, then evaluates `e`, then stores the value (6.2.4).\n7. `p op= e` means `p = p op e`, except that the place `p` is evaluated once [LS-165].\n8. `p++` means `p += 1`, and `p--` means `p -= 1`. Both are checked: at the type's limit they fault [LS-166].\n9. A statement that faults does not store (6.2.4).\n\n**Faults**\n\n10. A compound assignment raises the faults of its operator (6.7.6 to 6.7.9), with that operator's operation identifier, at the position of the compound operator token: `x += 1` with `x` equal to `I8.max` records `add.checked.i8`, with operands `x` and 1 [LS-165].\n11. `p++` and `p--` raise `E_OVERFLOW` at the type's limit. The record holds `add.checked.t` or `sub.checked.t`, with the operands `p` and 1, the exact result and the limit, and its position is the `++` or `--` token [LS-166].\n\n**Examples**\n\n12. This example shows every compound form:\n\n```cint compound.ci\nI64 x = 10;\nx += 5;\n\"{x} \";\nx -= 3;\n\"{x} \";\nx *= 2;\n\"{x} \";\nx /= 5;\n\"{x} \";\nx %= 3;\n\"{x} \";\nx <<= 4;\n\"{x} \";\nx >>= 1;\n\"{x} \";\nx &= 12;\n\"{x} \";\nx |= 3;\n\"{x} \";\nx ^= 5;\n\"{x}\\n\";\nU8 u = 250;\nu +%= 10;\n\"{u} \";\nu -%= 20;\n\"{u} \";\nu *%= 3;\n\"{u} \";\nu <<%= 4;\n\"{u} \";\nu +|= 250;\n\"{u} \";\nu -|= 251;\n\"{u} \";\nu = 20;\nu *|= 20;\n\"{u}\\n\";\n```\n\n```text\n15 12 24 4 1 16 8 8 11 14\n4 240 208 0 250 0 255\n```\n\n13. The place of a compound assignment is evaluated once, so `idx` runs once:\n\n```cint compound_place.ci\nI64 idx(I64 k) {\n    \"idx({k}) \";\n    return k;\n}\nvoid main() {\n    I64[3] a = [10, 20, 30];\n    a[idx(1)] += 5;\n    \"{a[1]}\\n\";\n}\n```\n\n```text\nidx(1) 25\n```\n\n14. This example shows `++` at the top of `I8`:\n\n```cint incr_fault.ci\nI8 i = 126;\ni++;\n\"{i}\\n\";\ni++;\n\"{i}\\n\";\n```"
  },
  {
   "id": "spec-04p:assignment-p2",
   "edition": "SPEC-04P.2",
   "title": "6.7.14 Assignment, compound assignment, `++` and `--` (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#assignment",
   "internal": 0,
   "content": "```text\n127\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> incr_fault.ci:4:2\n   |\n 4 | i++;\n   |  ^ add.checked.i8\n   |\n   = operation: add.checked.i8\n   = operand-count: 2\n   = operand: I8 127\n   = operand: I8 1\n   = exact:   128\n   = limit:   I8 127\n   ...\n```\n\n15. This example shows an assignment where a condition belongs:\n\n```cint assign_cond.ci\nI64 x = 1;\nif (x = 5) {\n    \"five\\n\";\n}\n```\n\n```text\nerror[C1041]: assignment in a condition\n  --> assign_cond.ci:2:5\n   |\n 2 | if (x = 5) {\n   |     ^\n```\n\n16. This example shows `++` inside an expression:\n\n```cint incr_expr.ci\nvoid main() {\n    I64[3] a = [1, 2, 3];\n    I64 i = 0;\n    a[i++] = 5;\n}\n```\n\n```text\nerror[C1042]: `++` or `--` used as an expression\n  --> incr_expr.ci:4:8\n   |\n 4 |     a[i++] = 5;\n   |        ^\n```\n\n17. Compound assignment on fixed point rounds as the operator does:\n\n```cint compound_fixed.ci\nQ16.16 q = 1.5;\nq *= q;\n\"{q}\\n\";\nq /= 2;\n\"{q}\\n\";\nq += 0.25;\n\"{q}\\n\";\n```\n\n```text\n2.25\n1.125\n1.375\n```\n\n**Notes**\n\n18. In C, an assignment is an expression with a value and `i++` yields the old value, so `if (x = 5)` and `a[i++] = a[i]` compile. Neither can be written in cint."
  },
  {
   "id": "spec-04p:rounding-modes-and-the-round-clause",
   "edition": "SPEC-04P.2",
   "title": "6.7.15 Rounding modes and the `round` clause",
   "clauses": "IM-42",
   "url": "/specifications/spec-04p/2/#rounding-modes-and-the-round-clause",
   "internal": 0,
   "content": "#### 6.7.15 Rounding modes and the `round` clause\n\nWhere an operation must turn an exact rational value into an integer, or into a value on the grid of a fixed-point type, it rounds once, by a rounding mode that the program can name. cint has nine modes. `half_even` is the default where a mode may be left out, and no operation rounds a value that is already rounded.\n\n**Syntax**\n\n```ebnf\nround_clause = \"round\" IDENT ;   (* IDENT is a mode name *)\n```\n\n`round` is recognized only after the target type of a conversion and after a fraction literal; elsewhere it is an ordinary name (6.4.4).\n\n**Constraints**\n\n1. <a id=\"IM-42\"></a>The name after `round`, and the name in the mode argument of a built-in operation, shall be one of the nine mode names of the table below. Any other name is diagnosed C3007 [IM-42].\n2. A `round` clause may follow the target type of a conversion that rounds (6.6) and a fraction literal (6.4.6). After a conversion that does not round it is diagnosed C2009 (6.6).\n\n**Semantics**\n\n3. The modes round a rational `x` as follows; the last five columns give the result for five values of `x` [IM-42]:"
  },
  {
   "id": "spec-04p:rounding-modes-and-the-round-clause-p1",
   "edition": "SPEC-04P.2",
   "title": "6.7.15 Rounding modes and the `round` clause (part 2)",
   "clauses": "IM-42 IM-43",
   "url": "/specifications/spec-04p/2/#rounding-modes-and-the-round-clause",
   "internal": 0,
   "content": "| Mode | Rounds `x` to | 2.5 | -2.5 | 2.4 | -2.6 | 3.5 |\n|---|---|---:|---:|---:|---:|---:|\n| `floor` | the integer toward negative infinity | 2 | -3 | 2 | -3 | 3 |\n| `ceil` | the integer toward positive infinity | 3 | -2 | 3 | -2 | 4 |\n| `trunc` | the integer toward 0 | 2 | -2 | 2 | -2 | 3 |\n| `away` | the integer away from 0 | 3 | -3 | 3 | -3 | 4 |\n| `half_even` | the nearest integer; a tie to the even one | 2 | -2 | 2 | -3 | 4 |\n| `half_away` | the nearest integer; a tie away from 0 | 3 | -3 | 2 | -3 | 4 |\n| `half_trunc` | the nearest integer; a tie toward 0 | 2 | -2 | 2 | -3 | 3 |\n| `half_up` | the nearest integer; a tie toward positive infinity | 3 | -2 | 2 | -3 | 4 |\n| `half_down` | the nearest integer; a tie toward negative infinity | 2 | -3 | 2 | -3 | 3 |\n\n4. <a id=\"IM-43\"></a>Every operation that rounds names its mode: in a `round` clause, in a mode argument, or by default. Where the mode may be left out, it is `half_even` [IM-42, IM-43].\n5. An operation rounds once, from its exact rational result, before its range check. No operation rounds an already rounded intermediate, so the result is the one the table gives for the exact value [IM-43].\n6. When a rounding operation faults, the exact result in its record is the rounded value, and its operation identifier ends with the mode it used, written or defaulted: `mul.checked.q16_16.half_even`, `div_round.checked.i64.floor` (8.1).\n7. The operations that round are: fixed-point `*` and `/`, and the built-in operations `mul`, `div`, `mul_wrap` and `mul_sat` (6.7.7); `div_round` (6.7.7); a conversion from fixed point to an integer type, or to a fixed-point type with fewer fraction bits (6.6); a fraction literal that is not on its type's grid (6.4.6); and the built-in operations of clause 7 that take a mode, `muldiv`, `isqrt_round`, the fixed-point `sqrt`, `qmul` and the fixed-point `dot`.\n\n**Examples**"
  },
  {
   "id": "spec-04p:rounding-modes-and-the-round-clause-p2",
   "edition": "SPEC-04P.2",
   "title": "6.7.15 Rounding modes and the `round` clause (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#rounding-modes-and-the-round-clause",
   "internal": 0,
   "content": "8. `div_round` under each mode, for the five values of the table: 5 / 2 is 2.5, 12 / 5 is 2.4, -13 / 5 is -2.6 and 7 / 2 is 3.5:\n\n```cint round_modes.ci\nvoid row(I64 a, I64 b) {\n    \"{a:>3} / {b}: {div_round(a, b, floor):>2} {div_round(a, b, ceil):>2} {div_round(a, b, trunc):>2}\";\n    \" {div_round(a, b, away):>2} {div_round(a, b, half_even):>2} {div_round(a, b, half_away):>2}\";\n    \" {div_round(a, b, half_trunc):>2} {div_round(a, b, half_up):>2} {div_round(a, b, half_down):>2}\\n\";\n}\nrow(5, 2);\nrow(-5, 2);\nrow(12, 5);\nrow(-13, 5);\nrow(7, 2);\n```\n\n```text\n  5 / 2:  2  3  2  3  2  3  2  3  2\n -5 / 2: -3 -2 -2 -3 -2 -3 -2 -2 -3\n 12 / 5:  2  3  2  3  2  2  2  2  2\n-13 / 5: -3 -2 -2 -3 -3 -3 -3 -3 -3\n  7 / 2:  3  4  3  4  4  4  3  4  3\n```\n\n9. `round` clauses on conversions and on fraction literals. -2.5 converts to -2 by default (`half_even`), and 0.1 is raw 6553.6 in `Q16.16`, which `half_even` rounds to 6554:\n\n```cint round_clause.ci\nQ16.16 x = -2.5;\nI32 a = x as I32;\nI32 b = x as I32 round floor;\nI32 c = x as I32 round half_away;\nQ16.16 t = 0.1 round half_even;\nQ16.16 u = -0.1 round ceil;\n\"{a} {b} {c} {t.raw} {u.raw}\\n\";\n```\n\n```text\n-2 -3 -3 6554 -6553\n```\n\n10. This example shows a rounding operation that faults. Its identifier ends with the mode named in the call, and the exact result is the raw value after that one rounding:\n\n```cint round_fault.ci\nQ16.16 a = 256.0;\nQ16.16 c = mul(a, a, floor);\n\"{c}\\n\";\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> round_fault.ci:2:12\n   |\n 2 | Q16.16 c = mul(a, a, floor);\n   |            ^ mul.checked.q16_16.floor\n   |\n   = operation: mul.checked.q16_16.floor\n   = operand-count: 2\n   = operand: Q16.16 raw 16777216\n   = operand: Q16.16 raw 16777216\n   = exact:   4294967296\n   = limit:   Q16.16 raw 2147483647\n   ...\n```\n\n11. This example shows a name that is not a mode:"
  },
  {
   "id": "spec-04p:rounding-modes-and-the-round-clause-p3",
   "edition": "SPEC-04P.2",
   "title": "6.7.15 Rounding modes and the `round` clause (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#rounding-modes-and-the-round-clause",
   "internal": 0,
   "content": "```cint round_name.ci\nI64 a = 7;\nI64 b = 2;\nI64 v = div_round(a, b, nearest);\n\"{v}\\n\";\n```\n\n```text\nerror[C3007]: undefined or unusable name\n  --> round_name.ci:3:25\n   |\n 3 | I64 v = div_round(a, b, nearest);\n   |                         ^\n```\n\n**Notes**\n\n12. `half_even` is also the default rounding of IEEE 754 binary floating point. `trunc` is the rounding of C's integer division and of C's conversion from a floating type to an integer type."
  },
  {
   "id": "spec-04p:constant-expressions-and-compile-time-evaluation",
   "edition": "SPEC-04P.2",
   "title": "6.8 Constant expressions and compile-time evaluation",
   "clauses": "IM-23 LS-264",
   "url": "/specifications/spec-04p/2/#constant-expressions-and-compile-time-evaluation",
   "internal": 0,
   "content": "### 6.8 Constant expressions and compile-time evaluation\n\nSome values are computed while the program is translated: the initializer of a `const` declaration, the extent of a module-level array, a `case` item, the condition of `static_assert` and every maximal constant expression (paragraph 4). This *compile-time evaluation* uses the operators and the types of a run. A constant expression is typed first and then evaluated with checked, wrapping or saturating arithmetic exactly as it would be at run time, so a computation gives the same value whether it is done at translation or at run time. A fault at translation is reported as the diagnostic C6001, with the fault's operands.\n\n**Constraints**\n\n1. <a id=\"LS-264\"></a>The following shall be constant expressions: the initializer of a `const` declaration (6.9.2); the initializer of a module-level variable of an importable module (6.9.3); an extent of a module-level array (6.12.1, 6.12.6) and of an array in a kernel body (6.13.3); a `case` item (6.10.5); the condition of `static_assert` (6.10.9); and the capacity of an arena or a pool (6.14.1). Anything else in these places is diagnosed C6004, except in an extent of an array in a kernel body, where it is diagnosed C9102 (6.13.3) [LS-264].\n\n**Semantics**\n\n2. <a id=\"IM-23\"></a>A *constant expression* is an expression built only from literals, names declared with `const`, the type properties `T.min`, `T.max` and `Q.epsilon`, the operators of 6.7, the conversions `as` and `as%`, the constructor `Q.raw(n)` and the named operations of 7.2, each with constant operands. A variable, a function call, the member `.raw`, `as?` and `catch` are not constant expressions [IM-23]."
  },
  {
   "id": "spec-04p:constant-expressions-and-compile-time-evaluation-p1",
   "edition": "SPEC-04P.2",
   "title": "6.8 Constant expressions and compile-time evaluation (part 2)",
   "clauses": "IM-103 IM-23 LS-264 LS-265",
   "url": "/specifications/spec-04p/2/#constant-expressions-and-compile-time-evaluation",
   "internal": 0,
   "content": "3. <a id=\"IM-103\"></a><a id=\"LS-265\"></a>A constant expression is typed by the rules of 6.5, exactly as if it were evaluated at run time, and is then evaluated with the meaning of 6.6, 6.7 and 7.2: the checked, wrapping and saturating forms, the rules for shift counts and the rounding of fixed point apply unchanged. No expression is evaluated in Z as a whole: every intermediate result has the type of its operation, as at run time [IM-23, IM-103, LS-265].\n\n4. The unit of compile-time evaluation is the *maximal constant expression*: a constant expression that is not an operand of a larger constant expression. Every maximal constant expression is evaluated at translation, wherever it appears, including inside an expression that is evaluated at run time [IM-23, LS-264].\n\n5. Inside a maximal constant expression, `&&`, `||` and `?:` evaluate only the operands that their result requires, as at run time (6.2.4). An operand they skip is type-checked and its literals are checked against their types, but it is not evaluated: `false && (1 / 0 == 0)` is `false`, and `true ? 1 : 1 / 0` is 1 [IM-23].\n\n6. A constant operand that `&&`, `||` or `?:` of a non-constant expression may skip is not evaluated at translation. It is evaluated at run time when the run reaches it, and faults then if its evaluation faults. With `I64 x`, `x == 2 && (1 / 0 == 0)` is translated, and faults `E_DIV_ZERO` when it is evaluated with `x` equal to 2 [IM-23, LS-264].\n\n7. A constant expression that its statement always evaluates is evaluated at translation, even when the statement is in a branch that a run does not reach [IM-23, LS-264].\n\n8. A checked conversion whose source is a literal operand (6.6) is decided at translation wherever it appears, in an operand that `&&`, `||` or `?:` skips as well [IM-23]."
  },
  {
   "id": "spec-04p:constant-expressions-and-compile-time-evaluation-p2",
   "edition": "SPEC-04P.2",
   "title": "6.8 Constant expressions and compile-time evaluation (part 3)",
   "clauses": "IM-103 IM-23 LS-265 LS-268 LS-270",
   "url": "/specifications/spec-04p/2/#constant-expressions-and-compile-time-evaluation",
   "internal": 0,
   "content": "9. When a program has several errors of this kind, the first in this order is reported. Evaluation runs in the order of 6.2.4, and each literal is checked against its type when it is evaluated: a literal that does not fit is C2003, and a fault is C6001. When evaluation ends without a fault, every literal of a skipped operand is checked against its type (C2003), and then the checked conversions of literal operands in skipped operands are decided, in source order [IM-23].\n\n10. <a id=\"LS-268\"></a>Compile-time evaluation reads no clock, no environment variable and no file. Its result depends only on the program's text [IM-103, LS-268].\n\n11. <a id=\"LS-270\"></a>Compile-time evaluation computes values and nothing else: it generates no code, and it inspects no declaration other than through `T.min`, `T.max` and `Q.epsilon` [LS-270].\n\n**Faults**\n\n12. A fault during compile-time evaluation is not raised at run time. The program is rejected with C6001 at the position the fault would have at run time, and the diagnostic reports the fault as a fault record would: its fault code, the operation identifier, the operands, the exact result and the limit [IM-23, IM-103, LS-265].\n\n**Examples**\n\n13. This example shows constants built from type properties, wrapping and saturating operators, conversions and named operations:\n\n```cint const_expressions.ci\nconst I64 A = min(3, 4);\nconst I64 B = div_round(7, 2, half_even);\nconst I8 C = I8.max;\nconst I64 D = abs(-5) + isqrt(50);\nconst U8 E = 200 +| 100;\nconst I64 F = (300 as% U8) as I64;\n\"{A} {B} {C} {D} {E} {F}\\n\";\n```\n\n```text\n3 4 127 12 255 44\n```\n\n14. The literals take the type `I8` from the declaration, so the first addition is done in `I8` and overflows. Evaluation stops there, and the literal 150, which does not fit `I8` either, is not reached:\n\n```cint const_fault.ci\nconst I8 X = 100 + 100 - 150;\n\"{X}\\n\";\n```"
  },
  {
   "id": "spec-04p:constant-expressions-and-compile-time-evaluation-p3",
   "edition": "SPEC-04P.2",
   "title": "6.8 Constant expressions and compile-time evaluation (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#constant-expressions-and-compile-time-evaluation",
   "internal": 0,
   "content": "```text\nerror[C6001]: fault during constant evaluation\n  --> const_fault.ci:1:18\n   |\n 1 | const I8 X = 100 + 100 - 150;\n   |                  ^\n   |\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> const_fault.ci:1:18\n   |\n 1 | const I8 X = 100 + 100 - 150;\n   |                  ^ add.checked.i8\n   |\n   = operation: add.checked.i8\n   = operand-count: 2\n   = operand: I8 100\n   = operand: I8 100\n   = exact:   200\n   = limit:   I8 127\n   ...\n```\n\n15. In the other order the literal 150 is evaluated first, and it does not fit:\n\n```cint const_order.ci\nconst I8 Y = 150 - 100 + 100;\n\"{Y}\\n\";\n```\n\n```text\nerror[C2003]: literal does not fit its type\n  --> const_order.ci:1:14\n   |\n 1 | const I8 Y = 150 - 100 + 100;\n   |              ^\n```\n\n16. The final value 1000000000 fits `I32`, but the product is computed in `I32` first, as it would be at run time:\n\n```cint const_typed.ci\nI32 v = 2_000_000_000 * 2 / 4;\n\"{v}\\n\";\n```\n\n```text\nerror[C6001]: fault during constant evaluation\n  --> const_typed.ci:1:23\n   |\n 1 | I32 v = 2_000_000_000 * 2 / 4;\n   |                       ^\n   |\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> const_typed.ci:1:23\n   |\n 1 | I32 v = 2_000_000_000 * 2 / 4;\n   |                       ^ mul.checked.i32\n   |\n   = operation: mul.checked.i32\n   = operand-count: 2\n   = operand: I32 2000000000\n   = operand: I32 2\n   = exact:   4000000000\n   = limit:   I32 2147483647\n   ...\n```\n\n17. This example shows computing in `I64` and converting the result once:\n\n```cint const_widened.ci\nI32 v = ((2_000_000_000 as I64) * 2 / 4) as I32;\n\"{v}\\n\";\n```\n\n```text\n1000000000\n```\n\n18. Operands that `&&` and `?:` skip are not evaluated:\n\n```cint const_skip.ci\nconst Bool B = false && (1 / 0 == 0);\nconst I64 T = true ? 1 : 1 / 0;\n\"{B} {T}\\n\";\n```\n\n```text\nfalse 1\n```"
  },
  {
   "id": "spec-04p:constant-expressions-and-compile-time-evaluation-p4",
   "edition": "SPEC-04P.2",
   "title": "6.8 Constant expressions and compile-time evaluation (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#constant-expressions-and-compile-time-evaluation",
   "internal": 0,
   "content": "19. Here `x == 2` is not constant, so `1 / 0 == 0` is left to run time. The first call skips it; the second evaluates it and faults:\n\n```cint const_runtime.ci\nI64 check(I64 x) {\n    Bool b = x == 2 && (1 / 0 == 0);\n    if (b) {\n        return 1;\n    }\n    return 0;\n}\n\"{check(1)}\\n\";\n\"{check(2)}\\n\";\n```\n\n```text\n0\nfault[E_DIV_ZERO]: division by zero\n  --> const_runtime.ci:2:27\n   |\n 2 |     Bool b = x == 2 && (1 / 0 == 0);\n   |                           ^ div.checked.i64\n   |\n   = operation: div.checked.i64\n   = operand-count: 2\n   = operand: I64 1\n   = operand: I64 0\n   ...\n```\n\n20. `1 / 0` in a declaration is always evaluated by its statement, so the program is rejected although the call does not take the branch:\n\n```cint const_unreached.ci\nI64 check(I64 x) {\n    if (x > 5) {\n        I64 y = 1 / 0;\n        return y;\n    }\n    return x;\n}\n\"{check(1)}\\n\";\n```\n\n```text\nerror[C6001]: fault during constant evaluation\n  --> const_unreached.ci:3:19\n   |\n 3 |         I64 y = 1 / 0;\n   |                   ^\n   |\nfault[E_DIV_ZERO]: division by zero\n  --> const_unreached.ci:3:19\n   |\n 3 |         I64 y = 1 / 0;\n   |                   ^ div.checked.i64\n   ...\n```\n\n21. A function call is not a constant expression:\n\n```cint const_call.ci\nI64 square(I64 x) {\n    return x * x;\n}\nconst I64 K = square(4);\n\"{K}\\n\";\n```\n\n```text\nerror[C6004]: constant expression required\n  --> const_call.ci:4:15\n   |\n 4 | const I64 K = square(4);\n   |               ^\n```\n\n22. Fixed-point constants round as they would at run time. `1.0 / 3.0` rounds to the nearest multiple of 2^-16 before the product, so three times it is not 1.0:\n\n```cint const_fixed.ci\nQ16.16 q = (1.0 / 3.0) * 3.0;\nconst Q16.16 THIRD = 1.0 / 3.0;\n\"{q} {q.raw} {THIRD.raw}\\n\";\n```\n\n```text\n0.9999847412109375 65535 21845\n```\n\n**Notes**"
  },
  {
   "id": "spec-04p:constant-expressions-and-compile-time-evaluation-p5",
   "edition": "SPEC-04P.2",
   "title": "6.8 Constant expressions and compile-time evaluation (part 6)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#constant-expressions-and-compile-time-evaluation",
   "internal": 0,
   "content": "23. A C compiler may fold `2000000000 * 2 / 4` to any value, because signed overflow in C is undefined behavior, and C requires a diagnostic only where a constant expression is required. In cint the folding is done in the declared type and reports the overflow with its operands, as a run would."
  },
  {
   "id": "spec-04p:declarations",
   "edition": "SPEC-04P.2",
   "title": "6.9 Declarations",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#declarations",
   "internal": 0,
   "content": "### 6.9 Declarations\n\nA declaration introduces a name and says what it stands for: a variable, a constant, a function, a struct type or an error set. This subclause gives the form of each declaration, the rules checked when it is translated, and what it does when it runs. The types that declarations name are defined in 6.3, where a name is visible in 6.2.3, and the order in which expressions are evaluated in 6.2.4."
  },
  {
   "id": "spec-04p:variables",
   "edition": "SPEC-04P.2",
   "title": "6.9.1 Variables",
   "clauses": "LS-104 LS-106",
   "url": "/specifications/spec-04p/2/#variables",
   "internal": 0,
   "content": "#### 6.9.1 Variables\n\nA variable declaration names an object, gives its type and gives its first value. A variable of an integer, fixed-point, `Bool` or error-set type always has an initializer, so no object is read before it holds a value (6.2.2). An array or struct variable without an initializer starts with every element and field equal to 0. A *view variable* names a window onto array storage that already exists.\n\n**Syntax**\n\n```ebnf\nvar_decl  = type IDENT [ \"=\" expr ] \";\" ;\nview_decl = ( \"in\" | \"inout\" ) type IDENT \"=\" expr \";\" ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-104\"></a>A variable of an integer type, of a fixed-point type, of `Bool` or of an error-set type shall have an initializer. A declaration without one is diagnosed C2050 at the declared name [LS-104].\n2. An array or struct variable that holds error-set values needs an initializer (C2054, 6.3.7).\n3. <a id=\"LS-106\"></a>A view variable is declared with `in`, which gives read-only access, or `inout`, which gives read and write access, and shall have an initializer: an array or a view of the same element type and rank. Its type writes `_` for each extent, which the initializer supplies. An `inout` view variable shall be initialized from storage that may be written; a read-only source is diagnosed C2067 [LS-106].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:variables-p1",
   "edition": "SPEC-04P.2",
   "title": "6.9.1 Variables (part 2)",
   "clauses": "LS-104 LS-106 LS-107 LS-109",
   "url": "/specifications/spec-04p/2/#variables",
   "internal": 0,
   "content": "4. A declaration runs when control reaches it. Its initializer is evaluated and the result becomes the variable's value. An array or struct variable without an initializer starts with every integer element and field equal to 0 and every `Bool` equal to `false`, so every read of every object returns a value the program wrote or this rule gave [LS-104].\n5. <a id=\"LS-109\"></a>A local variable may be assigned after its declaration. Parameters are read-only unless their mode is `inout` (6.9.5) [LS-109].\n6. A view variable designates the storage of its initializer. Reading an element through the view reads that storage, and writing through an `inout` view writes it, so a write to the array after the declaration is visible through the view [LS-106].\n7. <a id=\"LS-107\"></a>Assigning to a view variable copies the elements of the right side into the storage the view designates. It does not make the view designate other storage. The two sides shall have the same shape, as 6.12.5 states for every copy [LS-107].\n\n**Examples**\n\n8. Scalars need an initializer. Arrays and structs without one start at 0:\n\n```cint decl_zero.ci\nstruct Point { I64 x; I64 y; }\n\nvoid main() {\n    I64 ticks = 3;\n    I32[4] window;\n    Point p;\n    Bool ready = window[0] == 0;\n    \"{ticks} {window[0]} {window[3]} {p.x} {p.y} {ready}\\n\";\n}\n```\n\n```text\n3 0 0 0 0 true\n```\n\n9. A scalar declared without a value is rejected:\n\n```cint decl_uninit.ci\nI64 total;\n\"{total}\\n\";\n```\n\n```text\nerror[C2050]: uninitialized variable\n  --> decl_uninit.ci:1:5\n   |\n 1 | I64 total;\n   |     ^\n```\n\n10. A view variable reads and writes the array it was made from, and assignment to it copies elements:"
  },
  {
   "id": "spec-04p:variables-p2",
   "edition": "SPEC-04P.2",
   "title": "6.9.1 Variables (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#variables",
   "internal": 0,
   "content": "```cint decl_view.ci\nvoid demo() {\n    I64[6] data;\n    for i in 0..6 {\n        data[i] = i * 10;\n    }\n    in I64[_] head = data[0..3];\n    inout I64[_] tail = data[3..];\n    tail[0] = -1;\n    \"{head[2]} {data[3]}\\n\";\n    I64[3] fresh;\n    tail = fresh;\n    \"{data[3]} {data[5]} {len(tail)}\\n\";\n}\n\ndemo();\n```\n\n```text\n20 -1\n0 0 3\n```\n\n**Notes**\n\n11. C leaves an automatic variable without an initializer indeterminate. In cint a scalar without one is rejected, and an array or struct without one starts at 0."
  },
  {
   "id": "spec-04p:constants",
   "edition": "SPEC-04P.2",
   "title": "6.9.2 Constants",
   "clauses": "LS-111",
   "url": "/specifications/spec-04p/2/#constants",
   "internal": 0,
   "content": "#### 6.9.2 Constants\n\nA constant names a value that is computed once, during translation, and does not change. Every constant has a declared type, such as `I64`, `U8` or `Bool`. A constant can be used wherever a constant expression is required (6.8), such as an array extent or a `case` label. A constant declared at the top level of a module is visible in the whole module, before and after its declaration (6.2.3).\n\n**Syntax**\n\n```ebnf\nconst_decl = \"const\" type IDENT \"=\" expr \";\" ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-111\"></a>The initializer shall be a constant expression of the declared type (6.8). It may name other constants, in any order, but a constant shall not depend on itself, directly or through other constants: C6005 [LS-111].\n2. The initializer is evaluated during translation with the meaning it would have at run time. When that evaluation faults, the program is diagnosed C6001 at the faulting operator, and the diagnostic carries the fault's code, operation, operands, exact result and limit [LS-111].\n3. A constant shall not be assigned: C2058 [LS-111].\n\n**Semantics**\n\n4. A use of a constant gives the value of its initializer [LS-111].\n\n**Examples**\n\n5. Constants may refer to each other and be used before their declaration:\n\n```cint const_order.ci\nI64 area() {\n    return WIDTH * HEIGHT;\n}\n\nconst I64 WIDTH = 3 * SCALE;\nconst I64 HEIGHT = 4 * SCALE;\nconst I64 SCALE = 1_000;\n\n\"{area()}\\n\";\n```\n\n```text\n12000000\n```\n\n6. A constant can size an array and label a `case`:\n\n```cint const_use.ci\nconst I64 SLOTS = 4;\nconst I64 LAST = SLOTS - 1;\n\nvoid main() {\n    I64[SLOTS] ring;\n    for i in 0..SLOTS {\n        ring[i] = i * i;\n        switch (i) {\n            case LAST: \"last {ring[i]}\\n\";\n            default: \"slot {ring[i]}\\n\";\n        }\n    }\n}\n```\n\n```text\nslot 0\nslot 1\nslot 4\nlast 9\n```\n\n**Notes**"
  },
  {
   "id": "spec-04p:constants-p1",
   "edition": "SPEC-04P.2",
   "title": "6.9.2 Constants (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#constants",
   "internal": 0,
   "content": "7. A constant takes the place of both C's `#define` of a value and C's `const` object: it has a type, it is checked like any other expression, and no program can write it."
  },
  {
   "id": "spec-04p:module-level-variables",
   "edition": "SPEC-04P.2",
   "title": "6.9.3 Module-level variables",
   "clauses": "LS-113",
   "url": "/specifications/spec-04p/2/#module-level-variables",
   "internal": 0,
   "content": "#### 6.9.3 Module-level variables\n\nA variable declared at the top level of an importable module, or of a program that defines `main`, is a *module-level variable*: it exists as long as the context, keeps its value from one entry to the next (5.2.1), and every function of its module can use it. Its initial value is fixed during translation, so the order in which modules start cannot be observed. The top-level variables of a script are different: they are locals of the script's entry (5.1.2).\n\n**Syntax**\n\n```ebnf\ntop_item    = [ \"export\" ] declaration\n            | test_decl\n            | static_assert\n            | statement ;\ndeclaration = const_decl | var_decl | func_decl | kernel_decl\n            | struct_decl | error_decl | memory_decl ;\n```\n\n`var_decl` is in 6.9.1, `memory_decl` in 6.14.1 and `export` in 6.15.2.\n\n**Constraints**\n\n1. <a id=\"LS-113\"></a>The initializer of a module-level variable shall be a constant expression (6.8). An array literal or a struct constructor whose items are all constant expressions, nested literals and constructors included, is a constant initializer of a variable of its type. Any other initializer is diagnosed C6004 at its first character [LS-113].\n2. The constant initializer is checked as the same initializer of a local variable would be, and a fault during its evaluation is diagnosed C6001 [LS-113].\n3. An arena or a pool (6.14) is declared at the top level of the module, in a script as well as in an importable module, with a constant capacity; another capacity is diagnosed C6004 [LS-113].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:module-level-variables-p1",
   "edition": "SPEC-04P.2",
   "title": "6.9.3 Module-level variables (part 2)",
   "clauses": "LS-113",
   "url": "/specifications/spec-04p/2/#module-level-variables",
   "internal": 0,
   "content": "4. A module-level variable is created with the context, with the value of its initializer, or with every element and field equal to 0 when it has none. Its items are evaluated once, during translation, in source order [LS-113].\n5. Module-level variables keep their values from one call and one entry to the next. A test starts with the initial values again (6.15.3) [LS-113].\n\n**Examples**\n\n6. A program with `main` keeps its state at module level:\n\n```cint module_state.ci\nI64 calls = 0;\nI64[4] history;\nI64[3] weights = [3, 2, 1];\n\nvoid record(I64 v) {\n    history[calls % 4] = v * weights[calls % 3];\n    calls += 1;\n}\n\nvoid main() {\n    record(10);\n    record(20);\n    record(30);\n    \"{calls} {history[0]} {history[1]} {history[2]} {history[3]}\\n\";\n}\n```\n\n```text\n3 30 40 30 0\n```\n\n7. An initializer that would run code is rejected. The file has only declarations, so it is an importable module, not a script:\n\n```cint module_init.ci\nI64 first() {\n    return 7;\n}\n\nI64 start = first();\n\nvoid main() {\n    \"{start}\\n\";\n}\n```\n\n```text\nerror[C6004]: constant expression required\n  --> module_init.ci:5:13\n   |\n 5 | I64 start = first();\n   |             ^\n```"
  },
  {
   "id": "spec-04p:functions",
   "edition": "SPEC-04P.2",
   "title": "6.9.4 Functions",
   "clauses": "LS-114 LS-116 LS-117",
   "url": "/specifications/spec-04p/2/#functions",
   "internal": 0,
   "content": "#### 6.9.4 Functions\n\nA function is a named block of code with typed parameters and a typed result. Its form is C's: the result type, the name, optional size parameters in brackets, the parameters in parentheses and the body. Functions may be declared in any order and call each other freely; there are no prototypes and no header files.\n\n**Syntax**\n\n```ebnf\nfunc_decl   = result_type IDENT [ size_params ] \"(\" [ params ] \")\" block ;\nresult_type = \"void\" | base_type | union_type ;\nunion_type  = qualified \"!\" ( \"void\" | base_type ) ;\nsize_params = \"[\" IDENT { \",\" IDENT } \"]\" ;\nparams      = param { \",\" param } [ \",\" ] ;\nparam       = [ \"in\" | \"inout\" ] type IDENT ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-114\"></a>The result type is `void`, a type or an error union `E!T` or `E!void`, where `E` names an error set (6.9.7, 6.11) [LS-114].\n2. <a id=\"LS-116\"></a>A function whose result is not `void` or `E!void` shall not be able to reach the closing brace of its body: C4001 at the function's name. A `switch` that covers every value and returns in every case counts as returning. Every loop counts as able to complete, whatever its condition, so a `while (true)` loop that returns still needs a `return` after it [LS-116].\n3. <a id=\"LS-117\"></a>Each size parameter shall be bound by the extent of at least one array or view parameter: C2065 at the size parameter [LS-117].\n4. A function is called with parentheses, as 6.2.4 states (C4010, C4012).\n5. A call whose function returns a result other than `void` uses that result or discards it with `_ =`, as 6.2.4 states (C4011). A call that returns an error union is consumed as 6.11 states.\n\n**Semantics**"
  },
  {
   "id": "spec-04p:functions-p1",
   "edition": "SPEC-04P.2",
   "title": "6.9.4 Functions (part 2)",
   "clauses": "LS-115 LS-117",
   "url": "/specifications/spec-04p/2/#functions",
   "internal": 0,
   "content": "6. <a id=\"LS-115\"></a>Functions may be declared before or after their uses, in any order, within the module [LS-115].\n7. A *size parameter* is a name, bound at each call, for an extent of an array or view argument. Inside the body it is a read-only `I64`. When it appears in the type of several parameters, every extent it names shall be equal at the call. A mismatch that translation can see is diagnosed C2012; otherwise the call faults `E_SHAPE` before the body runs (6.9.5, paragraph 12) [LS-117].\n\n**Examples**\n\n8. A size parameter takes its value from the argument, so one function serves arrays of every length and slices of them:\n\n```cint fn_size.ci\nI64 total[n](in I64[n] a) {\n    I64 t = 0;\n    for i in 0..n {\n        t += a[i];\n    }\n    return t;\n}\n\nvoid main() {\n    I64[5] d;\n    for i in 0..5 {\n        d[i] = i + 1;\n    }\n    \"{total(d)} {total(d[1..3])}\\n\";\n}\n```\n\n```text\n15 5\n```\n\n9. Translation does not follow conditions to decide whether a function returns:\n\n```cint fn_noreturn.ci\nI64 signum(I64 x) {\n    if (x < 0) {\n        return -1;\n    } else if (x > 0) {\n        return 1;\n    }\n}\n\n\"{signum(5)}\\n\";\n```\n\n```text\nerror[C4001]: missing return\n  --> fn_noreturn.ci:1:5\n   |\n 1 | I64 signum(I64 x) {\n   |     ^\n```\n\n10. A result that is neither used nor discarded is rejected:\n\n```cint fn_unused.ci\nI64 twice(I64 x) {\n    return 2 * x;\n}\n\ntwice(3);\n_ = twice(4);\n```\n\n```text\nerror[C4011]: control-flow rule\n  --> fn_unused.ci:5:1\n   |\n 5 | twice(3);\n   | ^\n```\n\n**Notes**"
  },
  {
   "id": "spec-04p:functions-p2",
   "edition": "SPEC-04P.2",
   "title": "6.9.4 Functions (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#functions",
   "internal": 0,
   "content": "11. A call evaluates its arguments, runs the entry checks of 6.9.5, checks the call depth and charges fuel (5.2.5, 5.2.4), and then runs the body. A function may call itself, as deep as the call-depth limit of the entry allows (5.2.5).\n12. A function returns a scalar, a struct, a handle, an error-set value or an error union. To produce an array, it fills an `inout` array parameter (6.9.5, example 15)."
  },
  {
   "id": "spec-04p:parameters-and-arguments",
   "edition": "SPEC-04P.2",
   "title": "6.9.5 Parameters and arguments",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#parameters-and-arguments",
   "internal": 0,
   "content": "#### 6.9.5 Parameters and arguments\n\nEach parameter has a *mode* that says what the function may do with it. `in`, the default, gives read-only access; `inout` lets the function write the caller's array or struct. Arguments are matched to parameters by position or by name. Because an `inout` argument cannot overlap another argument of the same call, a function's reads and writes do not interfere, and an implementation may pass arguments by reference without changing a result.\n\n**Syntax**\n\n```ebnf\nparam = [ \"in\" | \"inout\" ] type IDENT ;\nargs  = arg { \",\" arg } [ \",\" ] ;\narg   = [ IDENT \"=\" ] expr ;\n```\n\n**Constraints**"
  },
  {
   "id": "spec-04p:parameters-and-arguments-p1",
   "edition": "SPEC-04P.2",
   "title": "6.9.5 Parameters and arguments (part 2)",
   "clauses": "LS-119 LS-120 LS-121 LS-122 LS-126",
   "url": "/specifications/spec-04p/2/#parameters-and-arguments",
   "internal": 0,
   "content": "1. <a id=\"LS-119\"></a>A parameter without a mode has mode `in`. `inout` applies to arrays, views and structs; an `inout` parameter of an integer, `Bool` or error-set type is diagnosed C2064 [LS-119].\n2. `out` is a parameter mode of kernels (6.13.2). A function writes an array through an `inout` parameter, and an `out` parameter of a function is diagnosed C5001 at the mode [LS-119].\n3. <a id=\"LS-120\"></a>A parameter is assigned, or written through, only when its mode is `inout`: C2060 otherwise [LS-120].\n4. An `inout` argument shall be storage the caller may write: a variable, a field or element of one or a writable view. A read-only argument for an `inout` parameter is diagnosed C2067 [LS-119].\n5. <a id=\"LS-126\"></a>A call supplies exactly one argument for each parameter. Positional arguments come first, then *named arguments*, written `name = value`. Too few or too many arguments are diagnosed C2022; a parameter that receives two arguments is C2062; a name that is not a parameter is C2063; a positional argument after a named one is C2069 [LS-126].\n6. <a id=\"LS-121\"></a>An `inout` argument shall not overlap any other argument of the same call, read-only or writable. An overlap known during translation is diagnosed C5010; other overlaps are checked when the call is made (paragraph 13). Read-only arguments may overlap each other [LS-121].\n7. <a id=\"LS-122\"></a>An argument that is a module-level variable, or a view of one, shall not be passed in any mode to a function that writes that variable, directly or through any function it calls. A function writes a module-level variable when it assigns it, or calls a function that does, directly or through any chain of calls in the program. A call that breaks this rule is diagnosed C5012 at the argument [LS-122].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:parameters-and-arguments-p2",
   "edition": "SPEC-04P.2",
   "title": "6.9.5 Parameters and arguments (part 3)",
   "clauses": "LS-119 LS-122 LS-123 LS-126",
   "url": "/specifications/spec-04p/2/#parameters-and-arguments",
   "internal": 0,
   "content": "8. An `in` argument is read-only for the duration of the call. A scalar is passed by value. For an array or struct, whether the function receives a copy or a reference cannot be observed, because constraints 6 and 7 rule out every write that could show the difference [LS-119, LS-122].\n9. An `inout` argument is passed by reference: every write the function makes is visible to the caller when the call returns [LS-119].\n10. Named arguments are matched to the parameters of the same name and evaluated in the order they are written, like all arguments (6.2.4) [LS-126].\n11. <a id=\"LS-123\"></a>When a call is made, after its arguments are evaluated and before fuel is charged, its *entry checks* run in this order, and the first that fails is the fault: the permission of each view, the element type and rank, the binding and agreement of shapes and the overlap of `inout` arguments. A handle argument is not among them: passing a handle does not check it, and a handle that is not valid faults with `E_STALE_HANDLE` at its first dereference in the callee (6.14.4) [LS-123].\n\n**Faults**"
  },
  {
   "id": "spec-04p:parameters-and-arguments-p3",
   "edition": "SPEC-04P.2",
   "title": "6.9.5 Parameters and arguments (part 4)",
   "clauses": "LS-117 LS-121 LS-123",
   "url": "/specifications/spec-04p/2/#parameters-and-arguments",
   "internal": 0,
   "content": "12. The fault `E_SHAPE` is raised when two extents that bind the same size parameter differ. The record holds the operation identifier `bind.shape`; three `I64` operands, the index of the parameter whose extent disagrees (from 0), the dimension (from 0) and that extent; no exact result; and, as the limit, the extent that the size parameter was bound to first. Its position is the callee's name at the call, with the caller's stack [LS-117, LS-123].\n13. The fault `E_ALIAS` is raised when an `inout` argument overlaps another argument. The record holds the operation identifier `bind.alias`; two `I64` operands, the index of the `inout` parameter (the lower index when both are `inout`) and the index of the parameter it overlaps; and no exact result and no limit. Its position is the callee's name at the call, with the caller's stack [LS-121].\n\n**Examples**\n\n14. A function writes an array through `inout`. The same function with `out` is rejected, because `out` is for kernels:\n\n```cint param_out.ci\nvoid squares[n](out I64[n] dst) {\n    for i in 0..n {\n        dst[i] = i * i;\n    }\n}\n\nvoid main() {\n    I64[4] sq;\n    squares(sq);\n    \"{sq[3]}\\n\";\n}\n```\n\n```text\nerror[C5001]: parameter mode, alias, or ABI rule\n  --> param_out.ci:1:17\n   |\n 1 | void squares[n](out I64[n] dst) {\n   |                 ^\n```\n\n15. With `inout` the function runs; a kernel, by contrast, declares the array it writes `out`:\n\n```cint param_inout.ci\nvoid squares[n](inout I64[n] dst) {\n    for i in 0..n {\n        dst[i] = i * i;\n    }\n}\n\nkernel square_all[n](in I64[n] src, out I64[n] dst) {\n    dst = src * src;\n}\n\nvoid main() {\n    I64[4] sq;\n    squares(sq);\n    I64[4] again;\n    square_all(sq, again);\n    \"{sq[3]} {again[3]}\\n\";\n}\n```\n\n```text\n9 81\n```\n\n16. An `inout` struct parameter lets a function update the caller's struct:\n\n```cint param_struct.ci\nstruct Acc { I64 sum; I64 n; }"
  },
  {
   "id": "spec-04p:parameters-and-arguments-p4",
   "edition": "SPEC-04P.2",
   "title": "6.9.5 Parameters and arguments (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#parameters-and-arguments",
   "internal": 0,
   "content": "void add(inout Acc a, I64 v) {\n    a.sum += v;\n    a.n += 1;\n}\n\nvoid main() {\n    Acc a = Acc(0, 0);\n    add(a, 5);\n    add(a, 7);\n    \"{a.sum} {a.n}\\n\";\n}\n```\n\n```text\n12 2\n```\n\n17. Named arguments may come in any order after the positional ones:\n\n```cint param_named.ci\nI64 sub(I64 a, I64 b) {\n    return a - b;\n}\n\nI64 r = sub(b = 1, a = 10);\nI64 s = sub(10, b = 3);\n\"{r} {s}\\n\";\n```\n\n```text\n9 7\n```\n\n18. Two slices of one array that do not overlap may be passed together. Overlapping slices fault when the call is made, before the body runs:\n\n```cint param_alias.ci\nvoid add_into[n](inout I64[n] dst, in I64[n] src) {\n    for i in 0..n {\n        dst[i] += src[i];\n    }\n}\n\nvoid main() {\n    I64[6] a;\n    for i in 0..6 {\n        a[i] = i;\n    }\n    add_into(a[0..3], a[3..6]);\n    \"{a[0]} {a[1]} {a[2]}\\n\";\n    add_into(a[0..3], a[2..5]);\n}\n```\n\n```text\n3 5 7\nfault[E_ALIAS]: views overlap\n  --> param_alias.ci:14:5\n   |\n14 |     add_into(a[0..3], a[2..5]);\n   |     ^ bind.alias\n   |\n   = operation: bind.alias\n   = operand-count: 2\n   = operand: I64 0\n   = operand: I64 1\n   = exact:   none\n   = limit:   none\n   ...\n```\n\n19. The shape check comes before the overlap check. Here the slices overlap and also differ in length, and the fault is `E_SHAPE`: parameter 1, dimension 0, has extent 3 where `n` was bound to 4:\n\n```cint param_shape.ci\nvoid add_into[n](inout I64[n] dst, in I64[n] src) {\n    for i in 0..n {\n        dst[i] += src[i];\n    }\n}\n\nvoid go(I64 k) {\n    I64[6] x;\n    add_into(x[0..k], x[2..5]);\n}\n\nvoid main() {\n    go(4);\n}\n```\n\n```text\nfault[E_SHAPE]: shapes do not match\n  --> param_shape.ci:9:5\n   |\n 9 |     add_into(x[0..k], x[2..5]);\n   |     ^ bind.shape\n   |\n   = operation: bind.shape\n   = operand-count: 3\n   = operand: I64 1\n   = operand: I64 0\n   = operand: I64 3\n   = exact:   none\n   = limit:   I64 4\n   ...\n```"
  },
  {
   "id": "spec-04p:parameters-and-arguments-p5",
   "edition": "SPEC-04P.2",
   "title": "6.9.5 Parameters and arguments (part 6)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#parameters-and-arguments",
   "internal": 0,
   "content": "20. A function that writes a module-level array cannot also receive a view of it:\n\n```cint param_global.ci\nI64[8] g;\n\nvoid bump(in I64[_] a) {\n    g[0] = a[1] + 1;\n}\n\nvoid main() {\n    bump(g[..]);\n}\n```\n\n```text\nerror[C5012]: parameter mode, alias, or ABI rule\n  --> param_global.ci:8:10\n   |\n 8 |     bump(g[..]);\n   |          ^\n```\n\n**Notes**\n\n21. In C a function writes through a pointer, and two pointer arguments may point into the same array, so a compiler must assume they alias. In cint the overlap is excluded by constraint 6, so a callee may assume that its writable parameters do not overlap, as C's `restrict` lets a C function assume."
  },
  {
   "id": "spec-04p:structs",
   "edition": "SPEC-04P.2",
   "title": "6.9.6 Structs",
   "clauses": "LS-112 LS-77",
   "url": "/specifications/spec-04p/2/#structs",
   "internal": 0,
   "content": "#### 6.9.6 Structs\n\nA struct groups named fields of fixed types into one value. A struct declaration names the type and its fields; a struct value is made by calling the type's name like a function, with one argument for each field. A field is read and written with `.` (6.7.4): `p.x`, `o.left.v`, `b.cells[1]`. The struct type itself, its values and its copying are described in 6.3.6.\n\n**Syntax**\n\n```ebnf\nstruct_decl = \"struct\" IDENT \"{\" { field } \"}\" ;\nfield       = type IDENT \";\" ;\ncall        = IDENT [ \".\" IDENT ] \"(\" [ args ] \")\" ;\n```\n\nA constructor is a `call` (6.7.4) whose callee names a struct type.\n\n**Constraints**\n\n1. The fields of a struct shall have distinct names: C3001 at the second name [LS-112].\n2. The types a field may have, and the rule that a struct does not contain itself, are stated in 6.3.6.\n3. <a id=\"LS-77\"></a>A constructor supplies every field exactly once, by position in declaration order or by name, under the rules of 6.9.5, constraint 5. A missing field is diagnosed C2020 at the constructor; extra arguments are C2022 [LS-77].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:structs-p1",
   "edition": "SPEC-04P.2",
   "title": "6.9.6 Structs (part 2)",
   "clauses": "LS-77",
   "url": "/specifications/spec-04p/2/#structs",
   "internal": 0,
   "content": "4. A constructor evaluates all its arguments first, in the order written (6.2.4). It then checks the shape of each argument for an array field against the field, in field declaration order, and only then copies each argument into its field. The struct does not share storage with any argument [LS-77].\n5. An argument for an array field shall have the field's shape. A mismatch that translation can see is diagnosed C2012. Otherwise the constructor faults `E_SHAPE` before it copies any field, with the operation identifier `copy.shape`, two `I64` operands, the lowest dimension that differs (from 0) and the argument's extent in it, no exact result and the field's extent as the limit. Its position is the constructor's name [LS-77].\n6. A struct is copied by assignment, by initialization and by passing as an `in` argument, as 6.3.6 states.\n\n**Examples**\n\n7. This example shows positional and named constructors, nested structs and an array field:\n\n```cint struct_use.ci\nstruct Inner { I64 v; }\nstruct Outer { Inner left; Inner right; I64[3] extra; }\n\nOuter build(I64 k) {\n    Outer o;\n    o.left.v = k;\n    o.right = Inner(v = k * 2);\n    o.extra[2] = k * 3;\n    return o;\n}\n\nvoid main() {\n    Outer o = build(5);\n    Outer other = o;\n    other.left.v = 99;\n    \"{o.left.v} {o.right.v} {o.extra[2]} {other.left.v}\\n\";\n}\n```\n\n```text\n5 10 15 99\n```\n\n8. Every field must be supplied:\n\n```cint struct_missing.ci\nstruct Point { I64 x; I64 y; }\n\nvoid main() {\n    Point a = Point(x = 3);\n    \"{a.x}\\n\";\n}\n```\n\n```text\nerror[C2020]: wrong fields or arguments\n  --> struct_missing.ci:4:15\n   |\n 4 |     Point a = Point(x = 3);\n   |               ^\n```\n\n9. A constructor copies an array argument, so a change to the array after the constructor does not reach the struct:\n\n```cint struct_copy.ci\nstruct Box { I64[3] cells; I32 tag; }"
  },
  {
   "id": "spec-04p:structs-p2",
   "edition": "SPEC-04P.2",
   "title": "6.9.6 Structs (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#structs",
   "internal": 0,
   "content": "void main() {\n    I64[3] init;\n    init[1] = 5;\n    Box b = Box(init, 7);\n    init[1] = 6;\n    \"{b.cells[1]} {init[1]} {b.tag}\\n\";\n}\n```\n\n```text\n5 6 7\n```\n\n**Notes**\n\n10. `Body{ ... }`, the brace initialization of C++, and C's `{ ... }` initializer are not constructors in cint; the constructor is a call of the type's name.\n11. Structs have no `==` and no text form. A comparison of two structs is diagnosed C2103, and a struct in a format hole C1037 (7.5); a program compares or prints the fields."
  },
  {
   "id": "spec-04p:error-sets",
   "edition": "SPEC-04P.2",
   "title": "6.9.7 Error sets",
   "clauses": "LS-92 LS-93 LS-97",
   "url": "/specifications/spec-04p/2/#error-sets",
   "internal": 0,
   "content": "#### 6.9.7 Error sets\n\nAn *error set* declares the names of the expected failures a group of functions can report, such as `bad_digit` or `overdrawn`. Each name is a value of the set. A function reports one by returning it through an error union (6.11). Error sets can be combined, so that a function calling into several parts of a program can pass on the errors of all of them.\n\n**Syntax**\n\n```ebnf\nerror_decl = \"error\" IDENT [ \":\" INT_TYPE ]\n             ( \"{\" IDENT { \",\" IDENT } [ \",\" ] \"}\"\n             | \"=\" qualified { \"|\" qualified } \";\" ) ;\n```\n\n**Constraints**\n\n1. The values of one set shall have distinct names: C3001 [LS-92].\n2. The *underlying type*, written after `:`, is the unsigned integer type that holds the tags of the set's values (6.3.7); without it the type is `U16`. A signed underlying type, and a set with more values than its underlying type can number from 1, are diagnosed C2031 [LS-93].\n3. In a *combined set*, `error C = A | B;`, each operand shall name an error set, itself combined or not; any other name is diagnosed C3007 [LS-97].\n\n**Semantics**\n\n4. The values of a set and their tags, the values of a combined set, the short forms of a value, the conversions between sets, and the comparison of error values are stated in 6.3.7.\n\n**Examples**\n\n5. This example shows error values stored in an array and tested with `switch`:\n\n```cint errset_values.ci\nerror Stage { parse, check, emit }\n\nvoid main() {\n    Stage[3] seen = [Stage.emit, .parse, Stage.check];\n    for i in 0..3 {\n        switch (seen[i]) {\n            case .parse: \"parse \";\n            case .check: \"check \";\n            case .emit: \"emit \";\n        }\n    }\n    \"\\n\";\n}\n```\n\n```text\nemit parse check \n```"
  },
  {
   "id": "spec-04p:error-sets-p1",
   "edition": "SPEC-04P.2",
   "title": "6.9.7 Error sets (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#error-sets",
   "internal": 0,
   "content": "6. A combined set numbers the values of `IoError` first and those of `ParseError` after them. `try` converts the tag of `bad_digit` from 2 to 4, and the error that `main` returns is reported with its tag in the combined set (6.11.7):\n\n```cint ingest.ci\nerror IoError : U8 { closed, full }\nerror ParseError { empty, bad_digit, too_large }\nerror IoOrParse = IoError | ParseError;\n\nParseError!I64 digit(I64 c) {\n    if (c < 48 || c > 57) {\n        return .bad_digit;\n    }\n    return c - 48;\n}\n\nIoOrParse!void main() {\n    I64 d = try digit(55);\n    \"digit {d}\\n\";\n    I64 e = try digit(120);\n    \"digit {e}\\n\";\n}\n```\n\n```console\n$ cint run ingest.ci\ndigit 7\nerror: ingest.IoOrParse.bad_digit (tag 4)\n```\n\n7. A name declared by two member sets must be written with its set:\n\n```cint errset_ambiguous.ci\nerror IoError { closed, full }\nerror QueueError { full, stalled }\nerror IoOrQueue = IoError | QueueError;\n\nIoOrQueue!I64 push() {\n    return .full;\n}\n\nI64 v = push() catch 0;\n\"{v}\\n\";\n```\n\n```text\nerror[C2044]: type rule\n  --> errset_ambiguous.ci:6:12\n   |\n 6 |     return .full;\n   |            ^\n```\n\n**Notes**\n\n8. An error set plays the part that `errno` values or negative return codes play in C, with two differences: the compiler knows which errors a function can return, and the caller cannot forget to handle one (6.11)."
  },
  {
   "id": "spec-04p:statements",
   "edition": "SPEC-04P.2",
   "title": "6.10 Statements",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#statements",
   "internal": 0,
   "content": "### 6.10 Statements\n\nA statement is one step of a program. The statements of a block run one after another, in the order written. Every statement either ends with `;` or is a braced construct such as `if` or `while`, and the bodies of all compound statements are blocks in braces. A statement has no value: assignment, `++` and `--` are statements (6.7.14), so an assignment cannot appear inside a condition."
  },
  {
   "id": "spec-04p:blocks-and-simple-statements",
   "edition": "SPEC-04P.2",
   "title": "6.10.1 Blocks and simple statements",
   "clauses": "LS-163 LS-167",
   "url": "/specifications/spec-04p/2/#blocks-and-simple-statements",
   "internal": 0,
   "content": "#### 6.10.1 Blocks and simple statements\n\nA *block* is a sequence of statements in braces. It may stand anywhere a statement may, and it starts a new scope: a name declared in it is visible from its declaration to the closing brace (6.2.3). A *simple statement* is a call, an assignment or an increment, followed by `;`.\n\n**Syntax**\n\n```ebnf\nblock       = \"{\" { statement } \"}\" ;\nstatement   = block\n            | const_decl\n            | var_decl\n            | view_decl\n            | simple_stmt \";\"\n            | discard\n            | print_stmt\n            | if_stmt\n            | [ IDENT \":\" ] loop_stmt\n            | switch_stmt\n            | jump_stmt\n            | defer_stmt\n            | assert_stmt\n            | static_assert\n            | reduce_stmt ;\nsimple_stmt = place assign_op expr\n            | place ( \"++\" | \"--\" )\n            | [ \"try\" ] call ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-163\"></a>There is no empty statement. A `;` where a statement is expected, as in `if (c);` or after the closing brace of a compound statement, is diagnosed C1040 [LS-163].\n2. <a id=\"LS-167\"></a>Only these stand as statements: a declaration, a call (with `try` where its result is an error union, 6.11), an assignment or compound assignment, `++` or `--`, a discard `_ = expr`, a print statement, the compound statements of this clause, and, in a kernel, a `reduce` statement (6.13.5). Any other expression followed by `;`, such as `x + 1;`, is diagnosed C4012 at its first character. A type followed by a keyword where a name is expected, as in `I64 do = 1;`, is also C4012, at the type [LS-167].\n\n**Semantics**\n\n3. The statements of a block run in order. A block ends when its last statement completes, or earlier through `return`, `break`, `continue`, `try` or a fault; the deferred statements of 6.10.7 run when it ends other than by a fault [LS-163].\n\n**Examples**"
  },
  {
   "id": "spec-04p:blocks-and-simple-statements-p1",
   "edition": "SPEC-04P.2",
   "title": "6.10.1 Blocks and simple statements (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#blocks-and-simple-statements",
   "internal": 0,
   "content": "4. A block limits the scope of the names declared in it:\n\n```cint stmt_block.ci\nI64 x = 3;\n{\n    I64 y = x * 2;\n    \"{y}\\n\";\n}\n\"{x}\\n\";\n```\n\n```text\n6\n3\n```\n\n5. An expression whose value would be thrown away is not a statement:\n\n```cint stmt_expr.ci\nI64 x = 3;\nx + 1;\n```\n\n```text\nerror[C4012]: statement form not permitted\n  --> stmt_expr.ci:2:1\n   |\n 2 | x + 1;\n   | ^\n```"
  },
  {
   "id": "spec-04p:the-if-statement",
   "edition": "SPEC-04P.2",
   "title": "6.10.2 The if statement",
   "clauses": "LS-168",
   "url": "/specifications/spec-04p/2/#the-if-statement",
   "internal": 0,
   "content": "#### 6.10.2 The if statement\n\n`if` runs a block when a condition is true and, optionally, another block when it is false. An `else if` chain tests several conditions in turn. The condition is always in parentheses and every branch is a block in braces.\n\n**Syntax**\n\n```ebnf\nif_stmt = \"if\" \"(\" expr \")\" block [ \"else\" ( if_stmt | block ) ] ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-168\"></a>The condition shall be in parentheses and each branch shall be a block in braces: C1043, at the first character of the part that is missing its parentheses or braces [LS-168].\n2. The condition has type `Bool`; an integer condition is diagnosed C2002, and an assignment written in a condition C1041 (6.3.3, 6.7.14) [LS-168].\n\n**Semantics**\n\n3. The condition is evaluated. When it is `true` the first block runs; otherwise the `else` part, if any, runs. In `else if`, the nested `if` is the `else` part, so an `else if` chain does not deepen the nesting of the program, and a chain may have any number of arms (5.3) [LS-168].\n\n**Examples**\n\n4. This example shows an `else if` chain:\n\n```cint if_chain.ci\nvoid grade(I64 score) {\n    if (score >= 90) {\n        \"A\\n\";\n    } else if (score >= 80) {\n        \"B\\n\";\n    } else {\n        \"C\\n\";\n    }\n}\n\ngrade(95);\ngrade(85);\ngrade(10);\n```\n\n```text\nA\nB\nC\n```\n\n5. A branch without braces is rejected:\n\n```cint if_braces.ci\nI64 x = 3;\nif (x > 2) \"big\\n\";\n```\n\n```text\nerror[C1043]: missing parentheses or braces\n  --> if_braces.ci:2:12\n   |\n 2 | if (x > 2) \"big\\n\";\n   |            ^\n```\n\n**Notes**\n\n6. C accepts an integer as a condition and an unbraced body. Both are rejected in cint: the condition is written as a comparison, `if (n != 0)`, and a body is always a block, so a second statement cannot fall outside it."
  },
  {
   "id": "spec-04p:the-while-statement",
   "edition": "SPEC-04P.2",
   "title": "6.10.3 The while statement",
   "clauses": "LS-169",
   "url": "/specifications/spec-04p/2/#the-while-statement",
   "internal": 0,
   "content": "#### 6.10.3 The while statement\n\n`while` runs a block for as long as a condition stays true. The condition is tested before each iteration, so the block may not run at all.\n\n**Syntax**\n\n```ebnf\nwhile_stmt = \"while\" \"(\" expr \")\" block ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-169\"></a>The condition shall be in parentheses and the body shall be a block: C1043. The condition has type `Bool` (C2002) [LS-169].\n\n**Semantics**\n\n2. The condition is evaluated. When it is `true` the body runs and the statement repeats; when it is `false` the statement ends. Each iteration is charged fuel (5.2.4), so a loop that does not end stops at the entry's fuel allowance when it has one (5.2.4) [LS-169].\n\n**Examples**\n\n3. This example shows a loop that counts:\n\n```cint while_count.ci\nI64 n = 1;\nwhile (n < 100) {\n    n *= 3;\n}\n\"{n}\\n\";\n```\n\n```text\n243\n```"
  },
  {
   "id": "spec-04p:the-for-statement",
   "edition": "SPEC-04P.2",
   "title": "6.10.4 The for statement",
   "clauses": "LS-170 LS-172 LS-173 LS-175",
   "url": "/specifications/spec-04p/2/#the-for-statement",
   "internal": 0,
   "content": "#### 6.10.4 The for statement\n\n`for` has two forms. The *range form*, `for i in 0..n`, runs a block once for each integer of a range, which is the common case. The *C form*, `for (init; condition; update)`, is C's loop, for iteration that the range form does not express.\n\n**Syntax**\n\n```ebnf\nfor_stmt = \"for\" IDENT \"in\" range block\n         | \"for\" \"(\" for_init \";\" expr \";\" simple_stmt \")\" block ;\nrange    = expr ( \"..\" | \"..=\" ) expr [ \"by\" expr ] ;\nfor_init = type IDENT \"=\" expr | simple_stmt ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-170\"></a>In both forms the body shall be a block, and in the C form the header shall be in parentheses: C1043 [LS-170].\n2. <a id=\"LS-172\"></a>In the range form, the bounds have type `I64`; a literal bound takes that type. A bound of another type is diagnosed C2001; a conversion, as in `for i in 0..(n as I64)`, gives it the type `I64` [LS-172].\n3. <a id=\"LS-173\"></a>The loop variable of the range form is read-only in the body: an assignment to it is diagnosed C2052 [LS-173].\n4. <a id=\"LS-175\"></a>The step after `by` shall be a constant expression other than 0: C2053 [LS-175].\n5. In the C form, `for_init` declares a variable or is a simple statement, the condition has type `Bool`, and the update is a simple statement [LS-170].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:the-for-statement-p1",
   "edition": "SPEC-04P.2",
   "title": "6.10.4 The for statement (part 2)",
   "clauses": "LS-170 LS-171 LS-172 LS-174 LS-175",
   "url": "/specifications/spec-04p/2/#the-for-statement",
   "internal": 0,
   "content": "6. In the range form, the bounds and the step are evaluated once, from left to right, before the first iteration; a change to a variable used in a bound does not change the range. The loop variable is an `I64` declared for the body [LS-172].\n7. <a id=\"LS-171\"></a>`lo..hi` is *half-open*: the loop variable takes the values `lo`, `lo + 1`, and so on, while it is less than `hi`. `lo..=hi` is *inclusive*: the values continue while they are at most `hi` [LS-171].\n8. With `by s`, the values are `lo`, `lo + s`, `lo + 2s`, and so on. For `s > 0` they continue while less than `hi` (`..`) or at most `hi` (`..=`); for `s < 0`, while greater than `hi` or at least `hi` [LS-171].\n9. <a id=\"LS-174\"></a>When the first value already fails its test, as in `5..5` or `3..=1`, the body does not run [LS-174].\n10. The loop computes no value past the last one it runs, so a range that ends at the maximum of `I64` completes without overflow [LS-175].\n11. In the C form, `for_init` runs once; a variable it declares is visible only in the loop and may be assigned. Then, as long as the condition is `true`, the body runs, followed by the update. The update is an ordinary statement: `i++` past the maximum of the variable's type faults `E_OVERFLOW` at the `++` (6.7.14) [LS-170].\n\n**Examples**\n\n12. This example shows half-open and inclusive ranges, and an empty one:\n\n```cint for_range.ci\nfor i in 0..4 {\n    \"{i} \";\n}\n\"\\n\";\nfor i in 1..=4 {\n    \"{i} \";\n}\n\"\\n\";\nfor i in 5..5 {\n    \"never \";\n}\n\"done\\n\";\n```\n\n```text\n0 1 2 3 \n1 2 3 4 \ndone\n```\n\n13. This example shows a step, upward and downward:\n\n```cint for_step.ci\nfor i in 0..10 by 3 {\n    \"{i} \";\n}\n\"\\n\";\nfor i in 10..0 by -3 {\n    \"{i} \";\n}\n\"\\n\";\n```\n\n```text\n0 3 6 9 \n10 7 4 1 \n```\n\n14. A range may end at the top of `I64`. The bounds of a narrower range are converted to `I64`:"
  },
  {
   "id": "spec-04p:the-for-statement-p2",
   "edition": "SPEC-04P.2",
   "title": "6.10.4 The for statement (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#the-for-statement",
   "internal": 0,
   "content": "```cint for_edge.ci\nI64 n = 0;\nfor i in (I64.max - 2)..=I64.max {\n    n += 1;\n}\nfor i in (I8.min as I64)..=(I8.max as I64) {\n    n += 1;\n}\n\"{n}\\n\";\n```\n\n```text\n259\n```\n\n15. In the C form the update is checked like any statement. An `I8` counter cannot pass 127:\n\n```cint for_c.ci\nfor (I8 k = 125; k <= 127; k++) {\n    \"{k}\\n\";\n}\n```\n\n```text\n125\n126\n127\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> for_c.ci:1:29\n   |\n 1 | for (I8 k = 125; k <= 127; k++) {\n   |                             ^ add.checked.i8\n   |\n   = operation: add.checked.i8\n   = operand-count: 2\n   = operand: I8 127\n   = operand: I8 1\n   = exact:   128\n   = limit:   I8 127\n   ...\n```\n\n16. The loop variable of the range form cannot be assigned; a loop that needs to change its own counter uses the C form:\n\n```cint for_readonly.ci\nfor i in 0..4 {\n    i = 2;\n}\n```\n\n```text\nerror[C2052]: loop variable assigned\n  --> for_readonly.ci:2:5\n   |\n 2 |     i = 2;\n   |     ^\n```\n\n**Notes**\n\n17. `for i in 0..n` corresponds to Python's `for i in range(n)`, half-open in the same way. Unlike a C loop over `int`, the range form cannot overflow its counter."
  },
  {
   "id": "spec-04p:the-switch-statement",
   "edition": "SPEC-04P.2",
   "title": "6.10.5 The switch statement",
   "clauses": "LS-177 LS-178 LS-179 LS-181 LS-182 LS-183",
   "url": "/specifications/spec-04p/2/#the-switch-statement",
   "internal": 0,
   "content": "#### 6.10.5 The switch statement\n\n`switch` selects one of several blocks of statements by the value of an integer, `Bool` or error value. A case lists single values and inclusive ranges. Control does not pass from one case to the next unless the case ends with `fallthrough;`, and every value of the type is handled, by a case or by `default`.\n\n**Syntax**\n\n```ebnf\nswitch_stmt    = \"switch\" \"(\" expr \")\" \"{\" { case_clause } [ default_clause ] \"}\" ;\ncase_clause    = \"case\" case_item { \",\" case_item } \":\" statement { statement } ;\ncase_item      = or_expr [ \"..=\" or_expr ] ;\ndefault_clause = \"default\" \":\" statement { statement } ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-177\"></a>The value tested, the *scrutinee*, has an integer type, `Bool` or an error-set type. Another type is diagnosed C4026 [LS-177].\n2. A case item is a constant expression (6.8) or an inclusive range `lo..=hi` of constant expressions, of the scrutinee's type. An item that is not constant is diagnosed C6004. A half-open range `lo..hi` is diagnosed C4022, and a range with `lo > hi` is C4024 [LS-177].\n3. <a id=\"LS-181\"></a>No value shall appear in two items of one `switch`: C4021 at the second of the two items [LS-181].\n4. <a id=\"LS-179\"></a>A case clause shall have at least one statement: C4023 at its `case`. Values that share a body are listed in one clause, `case 1, 3:` [LS-179].\n5. <a id=\"LS-182\"></a>A `switch` shall have a `default` clause or cover every value of the scrutinee's type: every value of an error set, both values of `Bool` or the full range of an integer type. Otherwise it is diagnosed C4020 at `switch` [LS-182].\n6. <a id=\"LS-183\"></a>`default` shall be the last clause and appear at most once: C4025 [LS-183].\n7. <a id=\"LS-178\"></a>`fallthrough;` shall be the last statement of a clause that another clause follows: C4014 otherwise [LS-178].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:the-switch-statement-p1",
   "edition": "SPEC-04P.2",
   "title": "6.10.5 The switch statement (part 2)",
   "clauses": "LS-177 LS-178 LS-180 LS-183",
   "url": "/specifications/spec-04p/2/#the-switch-statement",
   "internal": 0,
   "content": "8. The scrutinee is evaluated once, and the clause with an item that holds its value runs; when no item holds it, `default` runs [LS-177].\n9. A clause ends at the next `case`, the `default` or the closing brace and control then leaves the `switch`. `fallthrough;` continues into the body of the next clause instead [LS-178].\n10. <a id=\"LS-180\"></a>`break;` in a clause leaves the `switch`. To leave a loop that encloses the `switch`, a labeled `break` names the loop (6.10.6) [LS-180].\n11. Each clause is its own scope [LS-183].\n\n**Examples**\n\n12. This example shows single values, lists, ranges and `fallthrough`:\n\n```cint switch_classify.ci\nvoid classify(I64 code) {\n    switch (code) {\n        case 0:\n            \"ok\\n\";\n        case 1..=4, 9:\n            \"warning {code}\\n\";\n        case 5..=8:\n            \"error {code}\\n\";\n            fallthrough;\n        case 10:\n            \"logged\\n\";\n        default:\n            \"unknown {code}\\n\";\n    }\n}\n\nclassify(0);\nclassify(9);\nclassify(6);\nclassify(42);\n```\n\n```text\nok\nwarning 9\nerror 6\nlogged\nunknown 42\n```\n\n13. Two ranges cover every `U8`, so no `default` is needed:\n\n```cint switch_full.ci\nU8 b = 200;\nswitch (b) {\n    case 0..=127: \"low\\n\";\n    case 128..=255: \"high\\n\";\n}\n```\n\n```text\nhigh\n```\n\n14. A clause with no body is rejected, so C's stacked labels are written as one list:\n\n```cint switch_empty.ci\nI64 c = 5;\nswitch (c) {\n    case 1:\n    case 2: \"small\\n\";\n    default: \"other\\n\";\n}\n```\n\n```text\nerror[C4023]: `switch` rule\n  --> switch_empty.ci:3:5\n   |\n 3 |     case 1:\n   |     ^\n```\n\n**Notes**\n\n15. In C, control falls from one case into the next unless a `break` stops it, and a range of values needs a label for each. cint inverts the default: each case ends by itself, and `fallthrough;` asks for C's behavior where it is meant."
  },
  {
   "id": "spec-04p:break-continue-and-labels",
   "edition": "SPEC-04P.2",
   "title": "6.10.6 break, continue and labels",
   "clauses": "LS-184",
   "url": "/specifications/spec-04p/2/#break-continue-and-labels",
   "internal": 0,
   "content": "#### 6.10.6 break, continue and labels\n\n`break` leaves a loop or a `switch`, and `continue` starts the next iteration of a loop. A loop may carry a label, so that `break` and `continue` can name an outer loop directly. There is no `goto`.\n\n**Syntax**\n\n```ebnf\nloop_stmt = while_stmt | for_stmt ;\njump_stmt = ( \"break\" | \"continue\" ) [ IDENT ] \";\"\n          | return_stmt\n          | \"fallthrough\" \";\" ;\n```\n\nA label is the `IDENT \":\"` that `statement` (6.10.1) allows before a `loop_stmt`. `return_stmt` is in 6.10.8.\n\n**Constraints**\n\n1. <a id=\"LS-184\"></a>`break;` appears inside a loop or a `switch`, and `continue;` inside a loop. `break name;` and `continue name;` appear inside the loop labeled `name`. Any other use is diagnosed C4013 [LS-184].\n\n**Semantics**\n\n2. `break;` ends the innermost enclosing loop or `switch`. `continue;` ends the current iteration of the innermost enclosing loop; in the C form of `for`, the update runs next, then the condition [LS-184].\n3. `break name;` ends the loop labeled `name`, and `continue name;` starts its next iteration, leaving every loop and `switch` in between [LS-184].\n\n**Examples**\n\n4. This example shows a labeled `continue` and `break` in a search over pairs:\n\n```cint jump_label.ci\nvoid find() {\n    rows: for r in 0..4 {\n        for c in 0..4 {\n            if (c > r) {\n                continue rows;\n            }\n            if (r * c == 4) {\n                \"found {r} {c}\\n\";\n                break rows;\n            }\n        }\n    }\n    \"after\\n\";\n}\n\nfind();\n```\n\n```text\nfound 2 2\nafter\n```\n\n5. Inside a `switch`, `break` leaves the `switch` and `continue` continues the loop:\n\n```cint jump_switch.ci\nfor i in 0..6 {\n    switch (i) {\n        case 1: continue;\n        case 3: break;\n        default: \"{i} \";\n    }\n    \"| \";\n}\n\"\\n\";\n```\n\n```text\n0 | 2 | | 4 | 5 | \n```"
  },
  {
   "id": "spec-04p:defer-and-errdefer",
   "edition": "SPEC-04P.2",
   "title": "6.10.7 defer and errdefer",
   "clauses": "LS-187 LS-320 LS-322",
   "url": "/specifications/spec-04p/2/#defer-and-errdefer",
   "internal": 0,
   "content": "#### 6.10.7 defer and errdefer\n\n`defer` schedules a statement to run when the enclosing block ends, so that cleanup is written next to the setup it undoes. `errdefer` schedules a statement that runs only when the function returns an error. Neither runs after a fault: a fault stops the program where it happens (5.2.3).\n\n**Syntax**\n\n```ebnf\ndefer_stmt = ( \"defer\" | \"errdefer\" ) ( block | simple_stmt \";\" | discard ) ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-187\"></a>A deferred statement shall not contain a `return`, `try`, `break` or `continue` that would leave it: C4030. A `break` or `continue` of a loop inside the deferred statement is permitted [LS-187].\n2. <a id=\"LS-320\"></a>A deferred statement may consume an error union with `catch` or `_ =` (6.11); `try` is excluded by constraint 1 [LS-320].\n3. <a id=\"LS-322\"></a>`errdefer` appears only where an error can leave its block: in a function whose result is an error union, and in a test (6.15.3). Elsewhere it could not run and is diagnosed C4031: in a function or kernel whose result is not an error union, at the top level of a script, and inside a deferred statement [LS-322].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:defer-and-errdefer-p1",
   "edition": "SPEC-04P.2",
   "title": "6.10.7 defer and errdefer (part 2)",
   "clauses": "LS-185 LS-186 LS-188 LS-189 LS-316 LS-317 LS-318 LS-319 LS-321",
   "url": "/specifications/spec-04p/2/#defer-and-errdefer",
   "internal": 0,
   "content": "4. <a id=\"LS-185\"></a>`defer` schedules its statement to run when the enclosing block ends by reaching its closing brace, by `return`, `break` or `continue` or by `try` passing an error on. The statements deferred in one block run in the reverse of the order in which they were scheduled [LS-185].\n5. <a id=\"LS-186\"></a>A deferred statement reads its variables when it runs, not when it is scheduled [LS-186].\n6. <a id=\"LS-316\"></a>`return expr;` evaluates `expr`, then runs the pending deferred statements, then returns the value of `expr`. A deferred statement cannot change the value returned [LS-316].\n7. <a id=\"LS-318\"></a>A `defer` in a loop body is scheduled in each iteration and runs when that iteration's block ends, including by `continue` or `break` [LS-318].\n8. <a id=\"LS-319\"></a>A deferred statement scheduled inside a `catch (e) { ... }` block runs when that block ends [LS-319].\n9. <a id=\"LS-321\"></a>At the top level of a script, a deferred statement runs when the script's entry ends normally, by reaching the end of the script or by `return;` [LS-321].\n10. <a id=\"LS-189\"></a>`errdefer` runs only when the function ends by returning an error, through `return .name;` or through `try` or when an error leaves a test (6.15.3). Such statements run together with the deferred statements of the same blocks, in reverse order of scheduling. No form of `errdefer` gives access to the error [LS-189].\n11. <a id=\"LS-317\"></a>Running a deferred statement charges no fuel of its own; the calls and loop iterations inside it are charged as anywhere else (5.2.4). A fault inside a deferred statement is an ordinary fault, at its own position, with the call stack of the function that scheduled it [LS-317].\n12. <a id=\"LS-188\"></a>Deferred statements do not run after a fault. A fault ends the entry at once, and its fault record describes the state at the fault (5.2.3) [LS-188].\n\n**Examples**"
  },
  {
   "id": "spec-04p:defer-and-errdefer-p2",
   "edition": "SPEC-04P.2",
   "title": "6.10.7 defer and errdefer (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#defer-and-errdefer",
   "internal": 0,
   "content": "13. Deferred statements run in reverse order when their block ends, and read variables as they are then:\n\n```cint defer_order.ci\nvoid steps() {\n    I64 n = 1;\n    defer {\n        \"first scheduled, n = {n}\\n\";\n    }\n    defer {\n        \"second scheduled\\n\";\n    }\n    n = 5;\n    {\n        defer {\n            \"inner block ends\\n\";\n        }\n        \"in inner block\\n\";\n    }\n    \"body ends\\n\";\n}\n\nsteps();\n```\n\n```text\nin inner block\ninner block ends\nbody ends\nsecond scheduled\nfirst scheduled, n = 5\n```\n\n14. The returned value is fixed before the deferred statement runs:\n\n```cint defer_return.ci\nI64 counter() {\n    I64 n = 1;\n    defer n = 100;\n    return n;\n}\n\n\"{counter()}\\n\";\n```\n\n```text\n1\n```\n\n15. A `defer` in a loop runs at the end of each iteration, including one that `continue` ends:\n\n```cint defer_loop.ci\nfor i in 0..3 {\n    defer {\n        \"end of {i}\\n\";\n    }\n    if (i == 1) {\n        continue;\n    }\n    \"body {i}\\n\";\n}\n```\n\n```text\nbody 0\nend of 0\nend of 1\nbody 2\nend of 2\n```\n\n16. `errdefer` undoes work only on the error path:\n\n```cint defer_err.ci\nerror StoreError { full, closed }\n\nStoreError!I64 reserve(I64 want, I64 room) {\n    if (want > room) {\n        return .full;\n    }\n    return want;\n}\n\nStoreError!I64 stage(I64 want) {\n    defer {\n        \"leave stage {want}\\n\";\n    }\n    errdefer {\n        \"undo stage {want}\\n\";\n    }\n    I64 got = try reserve(want, 10);\n    \"staged {got}\\n\";\n    return got;\n}\n\nvoid main() {\n    I64 a = stage(4) catch -1;\n    I64 b = stage(40) catch -1;\n    \"{a} {b}\\n\";\n}\n```\n\n```text\nstaged 4\nleave stage 4\nundo stage 40\nleave stage 40\n4 -1\n```\n\n17. After a fault, no deferred statement runs:\n\n```cint defer_fault.ci\nvoid fragile(I8 x) {\n    defer {\n        \"cleanup\\n\";\n    }\n    I8 y = x + 100;\n}\n\n\"start\\n\";\nfragile(100);\n```"
  },
  {
   "id": "spec-04p:defer-and-errdefer-p3",
   "edition": "SPEC-04P.2",
   "title": "6.10.7 defer and errdefer (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#defer-and-errdefer",
   "internal": 0,
   "content": "```text\nstart\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> defer_fault.ci:5:14\n   |\n 5 |     I8 y = x + 100;\n   |              ^ add.checked.i8\n   |\n   = operation: add.checked.i8\n   = operand-count: 2\n   = operand: I8 100\n   = operand: I8 100\n   = exact:   200\n   = limit:   I8 127\n   ...\n```\n\n18. An `errdefer` where no error can leave is rejected:\n\n```cint defer_noerr.ci\nvoid tidy() {\n    errdefer {\n        \"undo\\n\";\n    }\n}\n\ntidy();\n```\n\n```text\nerror[C4031]: control-flow rule\n  --> defer_noerr.ci:2:5\n   |\n 2 |     errdefer {\n   |     ^\n```\n\n19. A deferred statement that would leave by `return` is rejected:\n\n```cint defer_leave.ci\nI64 pick(I64 x) {\n    defer {\n        return 0;\n    }\n    return x;\n}\n\n\"{pick(3)}\\n\";\n```\n\n```text\nerror[C4030]: control-flow rule\n  --> defer_leave.ci:3:9\n   |\n 3 |         return 0;\n   |         ^\n```\n\n**Notes**\n\n20. A print statement is not a simple statement, so a deferred print is written in a block: `defer { \"done\\n\"; }`.\n21. Python's `with` statement runs its cleanup when an exception leaves it. A cint fault is not an exception, and cleanup after a fault belongs to the host program that runs the entry (SPEC-03P.1)."
  },
  {
   "id": "spec-04p:the-return-statement",
   "edition": "SPEC-04P.2",
   "title": "6.10.8 The return statement",
   "clauses": "LS-190",
   "url": "/specifications/spec-04p/2/#the-return-statement",
   "internal": 0,
   "content": "#### 6.10.8 The return statement\n\n`return` ends the current function and gives its result. At the top level of a script it ends the script, and in a test it ends the test.\n\n**Syntax**\n\n```ebnf\nreturn_stmt = \"return\" [ expr ] \";\" ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-190\"></a>`return;` appears in a function whose result is `void` or `E!void`, in a test, and at the top level of a script. `return expr;` appears in a function with any other result. Any other combination is diagnosed C2066 [LS-190].\n2. In a function whose result is `E!T`, `expr` is either a value of type `T` or a value of the error set `E` (6.11.2) [LS-190].\n\n**Semantics**\n\n3. `return` runs the pending deferred statements (6.10.7) and ends the function, giving the value of `expr` to the caller [LS-190].\n4. At the top level of a script, `return;` ends the script's entry normally. In a test, `return;` ends the test as if its body had completed (6.15.3) [LS-190].\n\n**Examples**\n\n5. `return;` ends a script early:\n\n```cint return_script.ci\ndefer {\n    \"script ends\\n\";\n}\n\"before\\n\";\nreturn;\n\"not reached\\n\";\n```\n\n```text\nbefore\nscript ends\n```"
  },
  {
   "id": "spec-04p:assert-and-static-assert",
   "edition": "SPEC-04P.2",
   "title": "6.10.9 assert and static_assert",
   "clauses": "LS-191 LS-192",
   "url": "/specifications/spec-04p/2/#assert-and-static-assert",
   "internal": 0,
   "content": "#### 6.10.9 assert and static_assert\n\n`assert` checks a condition when the program runs and stops it with a fault when the condition is false. `static_assert` checks a condition during translation. When the condition of `assert` is a comparison, the fault record holds both compared values, so the report shows what the values were, not only that the check failed.\n\n**Syntax**\n\n```ebnf\nassert_stmt   = \"assert\" \"(\" expr [ \",\" STRING { STRING } ] \")\" \";\" ;\nstatic_assert = \"static_assert\" \"(\" expr [ \",\" STRING ] \")\" \";\" ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-191\"></a>The condition has type `Bool`: C2002 [LS-191].\n2. <a id=\"LS-192\"></a>The condition of `static_assert` is a constant expression (6.8). When it is `false`, the program is diagnosed C6010 [LS-192].\n\n**Semantics**\n\n3. `assert` evaluates its condition. When it is `true`, the statement completes. When it is `false`, the program faults `E_ASSERT`. The message, including any hole in it, is not evaluated and is not part of the fault record [LS-191].\n4. `assert` is checked in every build and every program; no option removes it [LS-191].\n\n**Faults**\n\n5. The fault `E_ASSERT` is raised by `assert` when its condition is `false`. The record holds the operation identifier `assert.checked.bool`. When the condition is a comparison, its operands are the two compared values, with their types; otherwise it has no operands. It has no exact result and no limit. Its position is the first character of the condition [LS-191].\n\n**Examples**\n\n6. A failed comparison shows both sides:\n\n```cint assert_fail.ci\nI64 total = 7 * 6;\nassert(total == 42);\n\"ok\\n\";\nassert(total < 40, \"total is too large\");\n\"not reached\\n\";\n```"
  },
  {
   "id": "spec-04p:assert-and-static-assert-p1",
   "edition": "SPEC-04P.2",
   "title": "6.10.9 assert and static_assert (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#assert-and-static-assert",
   "internal": 0,
   "content": "```text\nok\nfault[E_ASSERT]: assertion failed\n  --> assert_fail.ci:4:8\n   |\n 4 | assert(total < 40, \"total is too large\");\n   |        ^ assert.checked.bool\n   |\n   = operation: assert.checked.bool\n   = operand-count: 2\n   = operand: I64 42\n   = operand: I64 40\n   = exact:   none\n   = limit:   none\n   ...\n```\n\n7. A static assertion that fails stops translation:\n\n```cint assert_static.ci\nconst I64 SLOTS = 4;\nstatic_assert(SLOTS * 2 == 9, \"eight slots expected\");\n\"x\\n\";\n```\n\n```text\nerror[C6010]: compile-time evaluation rule\n  --> assert_static.ci:2:1\n   |\n 2 | static_assert(SLOTS * 2 == 9, \"eight slots expected\");\n   | ^\n```\n\n**Notes**\n\n8. C's `assert` is removed when `NDEBUG` is defined, and a failure prints only the text of the condition. A cint `assert` stays in every program, and its record holds the values compared."
  },
  {
   "id": "spec-04p:print-statements",
   "edition": "SPEC-04P.2",
   "title": "6.10.10 Print statements",
   "clauses": "LS-193 LS-194 LS-196",
   "url": "/specifications/spec-04p/2/#print-statements",
   "internal": 0,
   "content": "#### 6.10.10 Print statements\n\nA string literal standing as a statement prints itself. Each hole `{...}` in it is replaced by the text of the value inside, as 7.5 describes. Printing is the only output a program has, and its bytes are part of the program's outcome: the same on every implementation, operating system and locale.\n\n**Syntax**\n\n```ebnf\nprint_stmt = STRING { STRING } \";\" ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-196\"></a>A kernel body shall not contain a print statement: C5020 (6.13.3) [LS-196].\n\n**Semantics**\n\n2. <a id=\"LS-193\"></a>A print statement writes the formatted bytes of its string literals, in order, to the program's output. Adjacent literals form one statement [LS-193].\n3. <a id=\"LS-194\"></a>No newline is added. The bytes written are exactly the UTF-8 bytes of the formatted text, and a line feed is written as one byte, 10, on every operating system [LS-194].\n4. The text of each hole is the same on every locale, operating system and executor, as 7.5.1 states.\n5. Printing is an effect of the entry: a recording of a run holds the bytes printed, and replay reproduces them (8.4) [LS-196].\n6. 7.5.1 gives the order in which the holes of a statement are evaluated, and what is written when one of them faults.\n\n**Examples**\n\n7. Adjacent literals form one statement, and no newline is added between statements:\n\n```cint print_adjacent.ci\nI64 n = 7;\n\"line one, \" \"n = {n}\\n\";\n\"no newline here, \";\n\"{{braces}}\\n\";\n```\n\n```text\nline one, n = 7\nno newline here, {braces}\n```\n\n8. A fault in a hole stops the statement before it writes anything:\n\n```cint print_fault.ci\nI8 x = 100;\n\"start\\n\";\n\"x = {x}, doubled = {x + x}\\n\";\n```"
  },
  {
   "id": "spec-04p:print-statements-p1",
   "edition": "SPEC-04P.2",
   "title": "6.10.10 Print statements (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#print-statements",
   "internal": 0,
   "content": "```text\nstart\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> print_fault.ci:3:24\n   |\n 3 | \"x = {x}, doubled = {x + x}\\n\";\n   |                        ^ add.checked.i8\n   |\n   = operation: add.checked.i8\n   = operand-count: 2\n   = operand: I8 100\n   = operand: I8 100\n   = exact:   200\n   = limit:   I8 127\n   ...\n```"
  },
  {
   "id": "spec-04p:errors-and-faults",
   "edition": "SPEC-04P.2",
   "title": "6.11 Errors and faults",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#errors-and-faults",
   "internal": 0,
   "content": "### 6.11 Errors and faults\n\nA program meets two kinds of failure. An *error* is an expected outcome that the program handles: bad input, a full buffer, an account that would be overdrawn. A function reports one by returning a value of an error set, and its caller must deal with it. A *fault* is the stop of a run at an operation that cannot give a correct result (3.9), such as an overflow or an index outside an array: the operation stops the program, and no program code can catch it (5.2.3). This clause defines how errors are returned and handled, and how an error differs from a fault."
  },
  {
   "id": "spec-04p:errors-compared-with-faults",
   "edition": "SPEC-04P.2",
   "title": "6.11.1 Errors compared with faults",
   "clauses": "IM-120 LS-128",
   "url": "/specifications/spec-04p/2/#errors-compared-with-faults",
   "internal": 0,
   "content": "#### 6.11.1 Errors compared with faults\n\n| | Error | Fault |\n|---|---|---|\n| What it is for | An expected outcome the caller handles | An operation that cannot give a correct result |\n| How it starts | `return .overdrawn;`, or `try` passing one on | Raised by an operation or a failed `assert`; no statement names a fault to raise |\n| How it is handled | `try`, `catch` or `_ =`, in the caller | Not by the program: it ends the entry, and the host program or tool that ran the entry reads the fault record |\n| What it is | A value returned through an error union | A fault record (8.1) |\n\n**Semantics**\n\n1. <a id=\"LS-128\"></a>An error is a value of an error set (6.9.7), returned by a function whose result type is an error union (6.11.2). Returning it is an ordinary return: the caller receives it, and no other code runs on the way except the deferred statements of the returning function (6.10.7) [LS-128].\n2. A fault is raised by an operation; no statement raises one by name. Program code cannot construct, catch, inspect or resume a fault; a fault ends the entry with its fault record (5.2.3), and an `expect_fault` test only observes it (6.15.3) [LS-128].\n3. <a id=\"IM-120\"></a>Arithmetic that may legitimately fail, such as a division by a value that may be 0, is written with a *result form*, which returns an error where the plain operator would fault: `div_result(a, b)`, `add_result(a, b)` and the other forms of 6.7.12, and the conversion `x as? T` of 6.6. Their errors are values of the built-in error set `ArithError` and are handled as any other error [IM-120]."
  },
  {
   "id": "spec-04p:error-unions",
   "edition": "SPEC-04P.2",
   "title": "6.11.2 Error unions",
   "clauses": "LS-94 LS-95",
   "url": "/specifications/spec-04p/2/#error-unions",
   "internal": 0,
   "content": "#### 6.11.2 Error unions\n\nAn *error union* `E!T` is the result type of a function that either succeeds with a value of type `T` or fails with a value of the error set `E`. `E!void` is the result of a function that succeeds without a value. Every call of such a function is handled where it is made.\n\n**Syntax**\n\n```ebnf\nresult_type = \"void\" | base_type | union_type ;\nunion_type  = qualified \"!\" ( \"void\" | base_type ) ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-94\"></a>An error union is written only as the result type of a function (6.9.4) [LS-94].\n2. <a id=\"LS-95\"></a>A call whose result is an error union shall be consumed where it appears, by `try` (6.11.3), `catch` (6.11.4) or `_ =` (6.11.5). Any other use, including a call statement on its own and `return f(x);`, is diagnosed C2040 at the call [LS-95].\n3. In a function whose result is `E!T`, `return expr;` gives either a value of type `T` or a value of `E`, or of a set that `E` holds (6.3.7). In a function whose result is `E!void`, `return;` and reaching the closing brace give success [LS-94].\n\n**Semantics**\n\n4. A value of type `E!T` holds either a success value of type `T` or an error value of `E`. A value of `E!void` holds either success, with no value, or an error value [LS-94].\n\n**Examples**\n\n5. A function that can fail, and a caller that supplies a value in place of the error:\n\n```cint union_digit.ci\nerror ParseError { empty, bad_digit, too_large }\n\nParseError!I64 digit(I64 c) {\n    if (c < 48 || c > 57) {\n        return .bad_digit;\n    }\n    return c - 48;\n}\n\nI64 v = digit(55) catch -1;\nI64 w = digit(120) catch -1;\n\"{v} {w}\\n\";\n```\n\n```text\n7 -1\n```\n\n6. A call left unhandled is rejected:\n\n```cint union_unused.ci\nerror E { failed }\n\nE!void check(I64 x) {\n    if (x < 0) {\n        return .failed;\n    }\n}\n\nvoid main() {\n    check(1);\n}\n```"
  },
  {
   "id": "spec-04p:error-unions-p1",
   "edition": "SPEC-04P.2",
   "title": "6.11.2 Error unions (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#error-unions",
   "internal": 0,
   "content": "```text\nerror[C2040]: type rule\n  --> union_unused.ci:10:5\n   |\n10 |     check(1);\n   |     ^\n```"
  },
  {
   "id": "spec-04p:try",
   "edition": "SPEC-04P.2",
   "title": "6.11.3 try",
   "clauses": "LS-129 LS-315",
   "url": "/specifications/spec-04p/2/#try",
   "internal": 0,
   "content": "#### 6.11.3 try\n\n`try` passes an error on. Applied to a call, it gives the call's success value, or, when the call returns an error, returns that error from the current function at once. A chain of functions that each use `try` passes an error back to the first caller that handles it.\n\n**Syntax**\n\n```ebnf\nunary_expr = neg_literal\n           | ( \"-\" | \"-%\" | \"~\" | \"!\" | \"try\" ) unary_expr\n           | postfix_expr ;\n```\n\n`try` is one of the prefix operators of `unary_expr` (6.7.5).\n\n**Constraints**\n\n1. <a id=\"LS-129\"></a>The operand of `try` is a call, or a result form, whose result is an error union. Any other operand, including a kernel dispatch, is diagnosed C2043 [LS-129].\n2. `try` appears in a function whose result is an error union, or in a test. In a function, the function's error set shall hold every value of the operand's set: the same set, or a combined set that includes it (6.3.7). Otherwise it is diagnosed C2042 at the operand [LS-129].\n3. <a id=\"LS-315\"></a>In a test, `try` admits an error of any set [LS-315].\n\n**Semantics**\n\n4. `try` evaluates its operand. On success it gives the success value. On an error, it runs the pending deferred statements of the current function, `errdefer` included (6.10.7) and returns the error from the function, converted to the function's error set [LS-129].\n5. In a test, an error that `try` passes on ends the test and fails it (6.15.3) [LS-315].\n\n**Examples**\n\n6. This example shows two calls that may fail, combined into one function that may fail:\n\n```cint try_chain.ci\nerror ParseError { empty, bad_digit, too_large }\n\nParseError!I64 digit(I64 c) {\n    if (c < 48 || c > 57) {\n        return .bad_digit;\n    }\n    return c - 48;\n}\n\nParseError!I64 two_digits(I64 hi, I64 lo) {\n    I64 a = try digit(hi);\n    I64 b = try digit(lo);\n    return a * 10 + b;\n}"
  },
  {
   "id": "spec-04p:try-p1",
   "edition": "SPEC-04P.2",
   "title": "6.11.3 try (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#try",
   "internal": 0,
   "content": "I64 n = two_digits(52, 50) catch -1;\nI64 m = two_digits(52, 65) catch -1;\n\"{n} {m}\\n\";\n```\n\n```text\n42 -1\n```\n\n7. `try` cannot pass on an error that the function's own set does not hold:\n\n```cint try_wider.ci\nerror E { low }\nerror F { high }\n\nE!I64 check(I64 x) {\n    if (x < 0) {\n        return .low;\n    }\n    return x;\n}\n\nF!I64 relay(I64 x) {\n    I64 v = try check(x);\n    return v;\n}\n\nI64 r = relay(1) catch 0;\n\"{r}\\n\";\n```\n\n```text\nerror[C2042]: type rule\n  --> try_wider.ci:12:13\n   |\n12 |     I64 v = try check(x);\n   |             ^\n```"
  },
  {
   "id": "spec-04p:catch",
   "edition": "SPEC-04P.2",
   "title": "6.11.4 catch",
   "clauses": "LS-130 LS-131",
   "url": "/specifications/spec-04p/2/#catch",
   "internal": 0,
   "content": "#### 6.11.4 catch\n\n`catch` handles an error where the call is made. `f() catch value` gives a value in place of the error. `f() catch (e) { ... }` names the error and runs a block, which must leave: by `return`, `break` or `continue`. Either way, the expression has a value in every case.\n\n**Syntax**\n\n```ebnf\nexpr = cond_expr [ \"catch\" ( \"(\" IDENT \")\" block | cond_expr ) ] ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-130\"></a>The left operand of `catch` is a call, or a result form, whose result is an error union with a success value [LS-130].\n2. In `call catch value`, the value has the success type, which a literal takes from its context (6.5) [LS-130].\n3. <a id=\"LS-131\"></a>In `call catch (e) { ... }`, the block shall not complete by reaching its closing brace: it ends with `return`, `break`, `continue` or another statement that leaves it. A block that can complete is diagnosed C4002 at its opening brace [LS-131].\n4. `catch` binds more loosely than every operator, so its value operand extends as far as an expression can: `f() catch 0 + 1` gives `0 + 1` on an error [LS-130].\n\n**Semantics**\n\n5. The call is evaluated. On success the expression gives the success value. On an error, `catch value` evaluates `value` and gives it; the value is evaluated only in that case [LS-130].\n6. On an error, `catch (e) { ... }` binds `e` to the error value, with the error set of the call as its type, and runs the block. A deferred statement scheduled in the block runs when the block ends (6.10.7) [LS-131].\n\n**Examples**\n\n7. A `catch` block that tells the errors apart with `switch` and leaves with `return`:\n\n```cint catch_block.ci\nerror ParseError { empty, bad_digit, too_large }\n\nParseError!I64 digit(I64 c) {\n    if (c < 48 || c > 57) {\n        return .bad_digit;\n    }\n    return c - 48;\n}"
  },
  {
   "id": "spec-04p:catch-p1",
   "edition": "SPEC-04P.2",
   "title": "6.11.4 catch (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#catch",
   "internal": 0,
   "content": "void show(I64 c) {\n    I64 d = digit(c) catch (e) {\n        switch (e) {\n            case .empty: \"empty\\n\";\n            case .bad_digit: \"bad digit {c}\\n\";\n            case .too_large: \"too large\\n\";\n        }\n        return;\n    };\n    \"digit {d}\\n\";\n}\n\nshow(55);\nshow(65);\n```\n\n```text\ndigit 7\nbad digit 65\n```\n\n8. In a loop, a `catch` block can skip to the next iteration:\n\n```cint catch_loop.ci\nerror E { negative }\n\nE!I64 root_floor(I64 x) {\n    if (x < 0) {\n        return .negative;\n    }\n    return isqrt(x);\n}\n\nI64 total = 0;\nfor i in -2..3 {\n    I64 r = root_floor(i * 5) catch (e) {\n        \"skip {i}\\n\";\n        continue;\n    };\n    total += r;\n}\n\"{total}\\n\";\n```\n\n```text\nskip -2\nskip -1\n5\n```\n\n9. The value after `catch` is a whole expression:\n\n```cint catch_value.ci\nerror E { failed }\n\nE!I64 f(I64 x) {\n    if (x < 0) {\n        return .failed;\n    }\n    return x * 2;\n}\n\nI64 w = f(-1) catch 0 + 1;\nI64 u = f(4) catch 0 + 1;\n\"{w} {u}\\n\";\n```\n\n```text\n1 8\n```\n\n10. A `catch` block must leave:\n\n```cint catch_falls.ci\nerror E { failed }\n\nE!I64 f(I64 x) {\n    if (x > 0) {\n        return .failed;\n    }\n    return x;\n}\n\nI64 y = f(1) catch (e) {\n    \"caught\\n\";\n};\n\"{y}\\n\";\n```\n\n```text\nerror[C4002]: control-flow rule\n  --> catch_falls.ci:10:24\n   |\n10 | I64 y = f(1) catch (e) {\n   |                        ^\n```\n\n**Notes**\n\n11. `catch` resembles Python's `try: ... except E:` with two differences: the handler is attached to one call, not to a region of code, and it handles errors only, not faults."
  },
  {
   "id": "spec-04p:discarding-a-result",
   "edition": "SPEC-04P.2",
   "title": "6.11.5 Discarding a result",
   "clauses": "LS-132",
   "url": "/specifications/spec-04p/2/#discarding-a-result",
   "internal": 0,
   "content": "#### 6.11.5 Discarding a result\n\n`_ = expr;` evaluates an expression and throws away its value. It is the only way to drop an error without handling it, and it is written out where the error is ignored, so a reader sees every place that does so.\n\n**Syntax**\n\n```ebnf\ndiscard = \"_\" \"=\" expr \";\" ;\n```\n\n**Semantics**\n\n1. <a id=\"LS-132\"></a>`_ = expr;` evaluates `expr` and discards its value. When `expr` is a call that returns an error union, the error, if any, is discarded too and the statement completes [LS-132].\n\n**Examples**\n\n2. This example shows discarding the result of a call that may fail:\n\n```cint discard.ci\nerror E { failed }\n\nE!I64 attempt(I64 x) {\n    if (x < 0) {\n        return .failed;\n    }\n    \"attempt {x}\\n\";\n    return x;\n}\n\n_ = attempt(-1);\n_ = attempt(3);\n\"done\\n\";\n```\n\n```text\nattempt 3\ndone\n```"
  },
  {
   "id": "spec-04p:errors-from-arithmetic",
   "edition": "SPEC-04P.2",
   "title": "6.11.6 Errors from arithmetic",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#errors-from-arithmetic",
   "internal": 0,
   "content": "#### 6.11.6 Errors from arithmetic\n\nThe result forms of 6.7.12 and the conversion `x as? T` of 6.6 turn a fault that a program expects into an error that it handles. Their error set is the built-in `ArithError`, whose values name the fault the plain operator would have raised, such as `.div_zero` for `E_DIV_ZERO` and `.narrow` for `E_NARROW`.\n\n**Semantics**\n\n1. The value or error that a result form holds, and the rule that it is consumed with `try`, `catch` or `_ =`, are stated in 6.7.12.\n\n**Examples**\n\n2. A mean that reports an empty input as an error instead of a fault, and a narrowing that falls back to a default:\n\n```cint arith_errors.ci\nArithError!I64 mean(I64 total, I64 n) {\n    I64 q = try div_result(total, n);\n    return q;\n}\n\nI8 narrow_or(I64 v, I8 fallback) {\n    return v as? I8 catch fallback;\n}\n\nI64 a = mean(10, 2) catch -1;\nI64 b = mean(10, 0) catch (e) {\n    if (e == .div_zero) {\n        \"no samples\\n\";\n    }\n    return;\n};\n\"{a} {b}\\n\";\n```\n\n```text\nno samples\n```\n\n3. `as?` binds more tightly than `catch`, so a fallback needs no parentheses:\n\n```cint arith_narrow.ci\nI8 narrow_or(I64 v, I8 fallback) {\n    return v as? I8 catch fallback;\n}\n\n\"{narrow_or(99, -1)} {narrow_or(300, -1)}\\n\";\n```\n\n```text\n99 -1\n```"
  },
  {
   "id": "spec-04p:an-error-result-of-main",
   "edition": "SPEC-04P.2",
   "title": "6.11.7 An error result of main",
   "clauses": "LS-221",
   "url": "/specifications/spec-04p/2/#an-error-result-of-main",
   "internal": 0,
   "content": "#### 6.11.7 An error result of main\n\nA program whose entry is `main` may let `main` return an error, so that a whole program can end with an expected failure that is not a fault. The program defines `IoError!void main()`, or the same with another error set, in place of `void main()` (5.1.2).\n\n**Semantics**\n\n1. When `main` returns an error, the entry ends with that error as its result, as 5.2.1 states. It is not a fault, and no fault record is made.\n2. `cint run` then writes one line to standard error, `error: <set>.<value> (tag <n>)`, where `<set>` is the error set of `main`'s result qualified by its module (a built-in set such as `ArithError` has no module part), `<value>` is the error's name and `<n>` its tag in that set, and exits with the status of 5.2.1, Note 7 [LS-221].\n\n**Examples**\n\n3. This example shows a ledger that refuses to overdraw. The first withdrawal succeeds; the second returns `.overdrawn` through `try`, and `main` ends with that error:\n\n```cint ledger.ci\nerror LedgerError { overdrawn, frozen }\n\nLedgerError!I64 withdraw(I64 balance, I64 amount) {\n    if (amount > balance) {\n        return .overdrawn;\n    }\n    return balance - amount;\n}\n\nLedgerError!void main() {\n    I64 b = try withdraw(100, 30);\n    \"balance {b}\\n\";\n    I64 c = try withdraw(b, 500);\n    \"balance {c}\\n\";\n}\n```\n\n```console\n$ cint run ledger.ci\nbalance 70\nerror: ledger.LedgerError.overdrawn (tag 1)\n$ echo $?\n6\n```"
  },
  {
   "id": "spec-04p:arrays-and-views",
   "edition": "SPEC-04P.2",
   "title": "6.12 Arrays and views",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#arrays-and-views",
   "internal": 0,
   "content": "### 6.12 Arrays and views\n\nAn array holds a fixed number of elements of one type, and a view is a typed, shaped window onto the elements of an array. Arrays are how a program holds data in bulk; views are how it hands that data to functions and kernels without copying it. This section covers declaring arrays (6.12.1), reaching one element (6.12.2), taking part of an array as a view (6.12.3), passing views to functions (6.12.4), the rules for copying between arrays and views (6.12.5), and arrays declared at module level (6.12.6). The built-in operations on arrays and views, such as `len`, `extent`, `copy`, `transpose`, `reverse` and `reshape`, are in 7.4.\n\nThe examples of this section declare their arrays inside functions, most often inside `void main()` (5.1.2)."
  },
  {
   "id": "spec-04p:array-objects-and-initializers",
   "edition": "SPEC-04P.2",
   "title": "6.12.1 Array objects and initializers",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#array-objects-and-initializers",
   "internal": 0,
   "content": "#### 6.12.1 Array objects and initializers\n\nAn array type is an element type followed by a *shape*: a list of *extents* in brackets, one per dimension. `I64[8]` is eight `I64` values; `I32[3, 4]` is three rows of four `I32` values. The number of extents is the array's *rank*. Declaring a variable of an array type creates the array, with every element set to 0 unless an initializer gives the elements.\n\n**Syntax**\n\n```ebnf\ntype          = base_type [ shape ] ;\nbase_type     = INT_TYPE | \"Bool\" | FIXED_TYPE | memory_type | qualified ;\nshape         = \"[\" [ extent { \",\" extent } ] \"]\" ;\nextent        = \"_\" | expr ;\narray_literal = \"[\" [ expr { \",\" expr } [ \",\" ] ] \"]\" ;\n```\n\nAn `array_literal` of rank 2 or more is written as nested literals: each item of the outer literal is the literal of one row.\n\n**Constraints**"
  },
  {
   "id": "spec-04p:array-objects-and-initializers-p1",
   "edition": "SPEC-04P.2",
   "title": "6.12.1 Array objects and initializers (part 2)",
   "clauses": "LS-62 LS-66 LS-67 LS-71 M-24 V-1 V-2",
   "url": "/specifications/spec-04p/2/#array-objects-and-initializers",
   "internal": 0,
   "content": "1. <a id=\"V-1\"></a><a id=\"V-2\"></a><a id=\"M-24\"></a>The element type of an array is an integer type, a fixed-point type (6.3.2), `Bool`, an error set (6.3.7), a struct type or a handle type (6.14). The rank of an array or view type is 1 to 4: an array or view type with more than four extents is diagnosed C9102 at its `[` [V-1, V-2, M-24].\n2. <a id=\"LS-62\"></a>Each extent of a declared array is an `I64` expression whose value is known when the declaration runs: in a function body, an `I64` constant expression, a size parameter of the function (6.9.5), or an expression of constants and size parameters; in a module-level declaration and in a kernel body, a constant expression. Any other extent is diagnosed C6004, and in a kernel body C9102 (6.13.3). A constant extent below 0 is diagnosed C2015 [LS-62].\n3. <a id=\"LS-66\"></a>The extent `_` accepts any extent. It is written only in the type of a parameter or of a view variable (6.12.4); in the type of a declared array, such as `I64[_] a;`, it is diagnosed C9102. `I64[]` is shorthand for `I64[_]` [LS-66].\n4. <a id=\"LS-67\"></a>An array literal that initializes an array shall have exactly as many items as the extent it fills, at every level of nesting (C2011). A trailing comma is permitted. A brace list such as `{1, 2}` is not an array literal and is a syntax error (C1050) [LS-67].\n5. <a id=\"LS-71\"></a>`==`, `!=` and the ordering comparisons are not defined on arrays: comparing two arrays is diagnosed C2013 [LS-71].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:array-objects-and-initializers-p2",
   "edition": "SPEC-04P.2",
   "title": "6.12.1 Array objects and initializers (part 3)",
   "clauses": "LS-62 LS-63 LS-67 LS-68",
   "url": "/specifications/spec-04p/2/#array-objects-and-initializers",
   "internal": 0,
   "content": "6. <a id=\"LS-63\"></a>An array of shape `[n0, ..., nr-1]` holds `n0 * ... * nr-1` elements. They are stored in *row-major order*: the last index varies fastest, so `m[0, 0]`, `m[0, 1]`, `m[0, 2]` are adjacent [LS-63].\n7. An array declared without an initializer has every element 0: `false` for `Bool`, every field 0 for a struct, and the null handle for a handle [LS-67].\n8. An array literal gives the elements in row-major order. An initializer that is an array or a view copies its elements into the new array (6.12.5) [LS-67].\n9. <a id=\"LS-68\"></a>An extent may be 0. `I64[0] none;` declares an array with no elements, and every index into it faults [LS-68].\n10. When a declaration runs, its extents are evaluated from left to right before any storage is taken [LS-62]. A local array takes its storage from the frame arena when its declaration runs and returns it when its block exits (5.2.6).\n\n**Faults**\n\n11. The fault `E_SHAPE` is raised by a declaration whose extent evaluates below 0. The fault record holds the operation identifier `decl.shape`; two operands, the dimension as an `I64` counted from 0 and the requested extent as an `I64`; no exact result; and the limit `I64 0`. Its position is the declared name. The check runs after every extent of the declaration is evaluated, and the first negative extent from the left is reported [LS-62].\n\n**Examples**\n\n12. Declarations without and with initializers, and nested literals. The loop prints the elements in storage order:\n\n```cint array_basics.ci\nvoid main() {\n    I64[4] zeros;\n    I32[2, 3] m = [[1, 2, 3], [4, 5, 6]];\n    Bool[2] flags = [true, false];\n    \"{zeros[3]} {m[1, 0]} {flags[1]}\\n\";\n    for i in 0..2 {\n        for j in 0..3 {\n            \"{m[i, j]} \";\n        }\n    }\n    \"\\n\";\n}\n```\n\n```text\n0 4 false\n1 2 3 4 5 6 \n```"
  },
  {
   "id": "spec-04p:array-objects-and-initializers-p3",
   "edition": "SPEC-04P.2",
   "title": "6.12.1 Array objects and initializers (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#array-objects-and-initializers",
   "internal": 0,
   "content": "13. This example shows an extent computed from a size parameter. `n` is bound to the extent of the argument (6.9.5), and `tmp` has one more element:\n\n```cint array_size_param.ci\nI64 prefix_total[n](in I64[n] xs) {\n    I64[n + 1] tmp;\n    for i in 0..n {\n        tmp[i + 1] = tmp[i] + xs[i];\n    }\n    return tmp[n];\n}\n\nvoid main() {\n    I64[4] a = [1, 2, 3, 4];\n    \"{prefix_total(a)}\\n\";\n}\n```\n\n```text\n10\n```\n\n14. This example shows the same form with an extent that comes out negative. The size parameter `n` is 2, so `n - 3` is -1:\n\n```cint array_negative_extent.ci\nI64 g[n](in I64[n] xs) {\n    I64[n - 3] tmp;\n    return n;\n}\n\nvoid main() {\n    I64[2] a;\n    \"{g(a)}\\n\";\n}\n```\n\n```text\nfault[E_SHAPE]: shapes do not match\n  --> array_negative_extent.ci:2:16\n   |\n 2 |     I64[n - 3] tmp;\n   |                ^ decl.shape\n   |\n   = operation: decl.shape\n   = operand-count: 2\n   = operand: I64 0\n   = operand: I64 -1\n   = exact:   none\n   = limit:   I64 0\n   ...\n```\n\n15. This example shows a literal with too few items:\n\n```cint array_literal_count.ci\nvoid main() {\n    I64[3] a = [1, 2];\n    \"{a[0]}\\n\";\n}\n```\n\n```text\nerror[C2011]: array rule\n  --> array_literal_count.ci:2:16\n   |\n 2 |     I64[3] a = [1, 2];\n   |                ^\n```\n\n16. This example shows an array with no elements:\n\n```cint array_empty.ci\nvoid main() {\n    I64[0] none = [];\n    \"{len(none)}\\n\";\n    I64 i = 0;\n    \"{none[i]}\\n\";\n}\n```\n\n```text\n0\nfault[E_BOUNDS]: index out of bounds\n  --> array_empty.ci:5:11\n   |\n 5 |     \"{none[i]}\\n\";\n   |           ^ index.checked.i64\n   |\n   = operation: index.checked.i64\n   = operand-count: 1\n   = operand: I64 0\n   = exact:   none\n   = limit:   I64 0\n   ...\n```\n\n17. Arrays are not compared with `==`:\n\n```cint array_compare.ci\nvoid main() {\n    I64[2] a;\n    I64[2] b;\n    if (a == b) {\n        \"same\\n\";\n    }\n}\n```"
  },
  {
   "id": "spec-04p:array-objects-and-initializers-p4",
   "edition": "SPEC-04P.2",
   "title": "6.12.1 Array objects and initializers (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#array-objects-and-initializers",
   "internal": 0,
   "content": "```text\nerror[C2013]: array rule\n  --> array_compare.ci:4:9\n   |\n 4 |     if (a == b) {\n   |         ^\n```\n\n**Notes**\n\n18. A C array decays to a pointer and carries no extent. A cint array keeps its shape: every index is checked against it, and an array passed to a function arrives as a view that still has its extents (6.12.4)."
  },
  {
   "id": "spec-04p:indexing",
   "edition": "SPEC-04P.2",
   "title": "6.12.2 Indexing",
   "clauses": "LS-64 LS-65 M-27",
   "url": "/specifications/spec-04p/2/#indexing",
   "internal": 0,
   "content": "#### 6.12.2 Indexing\n\nAn index expression names one element: `a[i]` in an array of rank 1, `m[i, j]` in an array of rank 2, and so on. Indices count from 0. Every index is checked against its extent, and an index outside the array stops the program with a fault instead of reaching other storage.\n\n**Syntax**\n\n```ebnf\npostfix_expr = ( call | primary ) { \"[\" index_list \"]\" | \".\" IDENT } ;\nindex_list   = index { \",\" index } ;\n```\n\n`call` is in 6.7.4 and `primary` in 6.7.3. An `index` is an `expr`, or a range, which makes a slice (6.12.3).\n\n**Constraints**\n\n1. <a id=\"LS-64\"></a>Every index has type `I64`. A literal index is typed `I64`. An index of another integer type is diagnosed C2001; `as I64` (6.6) converts it [LS-64].\n2. <a id=\"LS-65\"></a>An index expression gives at most as many indices as the rank of the array or view it indexes. More indices, as in `a[0, 1]` for an array `a` of rank 1, are diagnosed C9102 at the `[` [LS-65].\n3. Indexing the result of a partial index directly, `m[i][j]`, is diagnosed C2010. The element is written `m[i, j]` [LS-65].\n4. <a id=\"M-27\"></a>An element of a view without write permission is not assignable. Assigning to an element of an `in` parameter is diagnosed C2060, and assigning to an element of an `in` view variable is diagnosed C9102 [M-27].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:indexing-p1",
   "edition": "SPEC-04P.2",
   "title": "6.12.2 Indexing (part 2)",
   "clauses": "IM-186 LS-64 LS-65 V-7",
   "url": "/specifications/spec-04p/2/#indexing",
   "internal": 0,
   "content": "5. <a id=\"V-7\"></a>The valid indices of a dimension of extent `n` are 0 to `n - 1` [LS-64, V-7].\n6. <a id=\"IM-186\"></a>Every index expression is evaluated, from left to right, before any index is checked. The dimensions are then checked in order, and the first index outside its extent faults. When the index expression is the place of an assignment, the place is evaluated and checked before the value is evaluated (6.2.4) [IM-186].\n7. A *partial index* gives fewer indices than the rank: indexing an array or view of rank `r` with `k < r` indices gives a view of rank `r - k` of the remaining dimensions, with the permission of the indexed expression. For `I32[2, 8, 8] p`, `p[0]` is the same view as the slice `p[0, .., ..]` [LS-65].\n\n**Faults**\n\n8. The fault `E_BOUNDS` is raised by an index below 0 or at or above its extent. The fault record holds the operation identifier `index.checked.e`, where `e` is the element type in lower case, or `struct` for a struct element. For rank 1 it holds one operand, the index as an `I64` and the extent as the limit, an `I64`. For rank 2 and more, whether every index is given or only the leading ones, it holds two operands, the dimension counted from 0 and the index, both `I64` and that dimension's extent as the limit. There is no exact result. Its position is the `[` of the index expression [IM-186, LS-64].\n\n**Examples**\n\n9. This example shows a rank-2 element and a row passed as a view:\n\n```cint index_rank2.ci\nI64 row_total(in I64[_] row) {\n    I64 t = 0;\n    for j in 0..len(row) {\n        t += row[j];\n    }\n    return t;\n}\n\nvoid main() {\n    I64[3, 4] m;\n    m[1, 0] = 1;\n    m[1, 3] = 4;\n    m[2, 0] = 100;\n    \"{m[1, 3]} {row_total(m[1])}\\n\";\n}\n```\n\n```text\n4 5\n```\n\n10. Of two indices outside their extents, the dimension checked first is reported. Here `i` is 2 in a dimension of extent 2:"
  },
  {
   "id": "spec-04p:indexing-p2",
   "edition": "SPEC-04P.2",
   "title": "6.12.2 Indexing (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#indexing",
   "internal": 0,
   "content": "```cint index_bounds.ci\nvoid main() {\n    I64[2, 3] m;\n    I64 i = 2;\n    I64 j = 3;\n    m[i, j] = 5;\n}\n```\n\n```text\nfault[E_BOUNDS]: index out of bounds\n  --> index_bounds.ci:5:6\n   |\n 5 |     m[i, j] = 5;\n   |      ^ index.checked.i64\n   |\n   = operation: index.checked.i64\n   = operand-count: 2\n   = operand: I64 0\n   = operand: I64 2\n   = exact:   none\n   = limit:   I64 2\n   ...\n```\n\n11. An index of type `I32` is not converted silently:\n\n```cint index_type.ci\nvoid main() {\n    I64[3] a = [1, 2, 3];\n    I32 k = 1;\n    \"{a[k]}\\n\";\n}\n```\n\n```text\nerror[C2001]: type mismatch\n  --> index_type.ci:4:9\n   |\n 4 |     \"{a[k]}\\n\";\n   |         ^\n```\n\n12. `a[k as I64]` is the form that compiles:\n\n```cint index_convert.ci\nvoid main() {\n    I64[3] a = [1, 2, 3];\n    I32 k = 1;\n    \"{a[k as I64]}\\n\";\n}\n```\n\n```text\n2\n```\n\n**Notes**\n\n13. In C, an index outside an array is undefined behavior, and a negative index has undefined behavior, which often reads the storage before the array. In cint both fault, and the fault record names the index and the extent it missed."
  },
  {
   "id": "spec-04p:slicing-and-index-bases",
   "edition": "SPEC-04P.2",
   "title": "6.12.3 Slicing and index bases",
   "clauses": "LS-161 LS-64",
   "url": "/specifications/spec-04p/2/#slicing-and-index-bases",
   "internal": 0,
   "content": "#### 6.12.3 Slicing and index bases\n\nA range in an index position takes a *slice*: a view of part of an array, sharing the array's storage. `a[2..5]` is the three elements `a[2]`, `a[3]` and `a[4]`; writing through a slice writes the array. A step, `by k`, takes every `k`-th element and a negative step runs backward.\n\n**Syntax**\n\n```ebnf\nindex_list = index { \",\" index } ;\nindex      = expr\n           | [ expr ] \"..\" [ expr ] [ \"by\" expr ]\n           | [ expr ] \"..=\" expr [ \"by\" expr ] ;\n```\n\nAn index expression with at least one range in it is a slice.\n\n**Constraints**\n\n1. The bounds of a range have type `I64`, as an index does (C2001) [LS-64].\n2. <a id=\"LS-161\"></a>The step after `by` is an integer constant expression other than 0. A step that is not a constant, or is 0, is diagnosed C2053 [LS-161].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:slicing-and-index-bases-p1",
   "edition": "SPEC-04P.2",
   "title": "6.12.3 Slicing and index bases (part 2)",
   "clauses": "IM-186 LS-161 LS-162 LS-64 V-7",
   "url": "/specifications/spec-04p/2/#slicing-and-index-bases",
   "internal": 0,
   "content": "3. <a id=\"LS-162\"></a>A slice is a view of the storage of the expression it is taken from. Taking a slice copies no element. The slice has the permission of that expression: a slice of an `in` view is read-only [LS-161, LS-162].\n4. In each dimension, an index removes the dimension and a range keeps it. `m[.., j]` is column `j` of a rank-2 array, a rank-1 view whose consecutive elements are a row's length apart; `m[i, 1..3]` is part of row `i` [LS-161].\n5. With a positive step `k` (1 when `by` is absent), `a[lo..hi]` holds the elements at `lo`, `lo + k`, `lo + 2k` and so on, below `hi`. `a[lo..=hi]` is `a[lo..hi + 1]`, with the addition exact. An omitted first bound is 0 and an omitted second bound is the extent, so `a[..]` is the whole dimension [LS-161, IM-186].\n6. With a negative step `k`, the range runs downward from its first bound: `a[f..g by k]` holds the elements at `f`, `f + k` and so on, above `g` and `a[f..=g by k]` includes `g`. An omitted first bound is the last index, `n - 1` for extent `n` and an omitted second bound runs through index 0. `a[.. by -1]` is the whole dimension reversed [LS-161].\n7. For a dimension of extent `n`, a range with a positive step is valid when `0 <= lo <= hi <= n` after omitted bounds are filled in. A range with a negative step is valid when `-1 <= g <= f <= n - 1` for `f..g`, and when `0 <= g <= f + 1 <= n` for `f..=g`. A valid range may be empty: `a[3..3]`, `a[3..=2]`, `a[n..]`, and a reversed range whose bounds meet, are empty slices, not faults [LS-161, LS-162].\n8. Every array and view is indexed from 0 in every dimension. The first element of a slice has index 0, whatever its position in the array it was taken from: in `in I64[_] v = a[2..5];`, `v[0]` is `a[2]` [LS-64, V-7].\n\n**Faults**"
  },
  {
   "id": "spec-04p:slicing-and-index-bases-p2",
   "edition": "SPEC-04P.2",
   "title": "6.12.3 Slicing and index bases (part 3)",
   "clauses": "IM-186 LS-161",
   "url": "/specifications/spec-04p/2/#slicing-and-index-bases",
   "internal": 0,
   "content": "9. The fault `E_BOUNDS` is raised by a range that is not valid under paragraph 7. The fault record holds the operation identifier `slice.checked.e`, with `e` as for an index (6.12.2); as operands, the dimension at rank 2 and more, then the two bounds as written, after omitted bounds are filled in, all `I64`; no exact result; and that dimension's extent as the limit. Its position is the `[` of the slice [IM-186, LS-161].\n\n**Examples**\n\n10. This example shows the forms of a range on one array of ten elements:\n\n```cint slice_forms.ci\nvoid show(in I64[_] v) {\n    for i in 0..len(v) {\n        \"{v[i]} \";\n    }\n    \"(len {len(v)})\\n\";\n}\n\nvoid main() {\n    I64[10] a;\n    for i in 0..10 {\n        a[i] = i;\n    }\n    show(a[2..5]);\n    show(a[2..=5]);\n    show(a[..3]);\n    show(a[7..]);\n    show(a[1..8 by 3]);\n    show(a[8..2 by -2]);\n    show(a[.. by -1]);\n    show(a[3..=2]);\n    show(a[10..]);\n}\n```\n\n```text\n2 3 4 (len 3)\n2 3 4 5 (len 4)\n0 1 2 (len 3)\n7 8 9 (len 3)\n1 4 7 (len 3)\n8 6 4 (len 3)\n9 8 7 6 5 4 3 2 1 0 (len 10)\n(len 0)\n(len 0)\n```\n\n11. This example shows slices of a rank-2 array, and a write through a slice:\n\n```cint slice_rank2.ci\nvoid show(in I64[_] v) {\n    for i in 0..len(v) {\n        \"{v[i]} \";\n    }\n    \"\\n\";\n}\n\nvoid main() {\n    I64[3, 4] m = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];\n    show(m[.., 2]);\n    show(m[1, 1..3]);\n    inout I64[_, _] corner = m[0..2, 2..4];\n    corner[1, 1] = 80;\n    \"{m[1, 3]} {extent(corner, 0)} {extent(corner, 1)}\\n\";\n}\n```\n\n```text\n3 7 11 \n6 7 \n80 2 2\n```\n\n12. This example shows a range whose first bound is above its second:\n\n```cint slice_bounds.ci\nvoid main() {\n    I64[5] a;\n    I64 lo = 4;\n    I64 hi = 2;\n    in I64[_] v = a[lo..hi];\n    \"{len(v)}\\n\";\n}\n```"
  },
  {
   "id": "spec-04p:slicing-and-index-bases-p3",
   "edition": "SPEC-04P.2",
   "title": "6.12.3 Slicing and index bases (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#slicing-and-index-bases",
   "internal": 0,
   "content": "```text\nfault[E_BOUNDS]: index out of bounds\n  --> slice_bounds.ci:5:20\n   |\n 5 |     in I64[_] v = a[lo..hi];\n   |                    ^ slice.checked.i64\n   |\n   = operation: slice.checked.i64\n   = operand-count: 2\n   = operand: I64 4\n   = operand: I64 2\n   = exact:   none\n   = limit:   I64 5\n   ...\n```\n\n13. This example shows a step that is not a constant:\n\n```cint slice_step.ci\nvoid main() {\n    I64[5] a;\n    I64 k = 2;\n    in I64[_] v = a[0..4 by k];\n    \"{len(v)}\\n\";\n}\n```\n\n```text\nerror[C2053]: type rule\n  --> slice_step.ci:4:29\n   |\n 4 |     in I64[_] v = a[0..4 by k];\n   |                             ^\n```\n\n**Notes**\n\n14. A range in an index has the meaning of a range in a `for` loop (6.10.4): `..` excludes its second bound and `..=` includes it."
  },
  {
   "id": "spec-04p:views-as-parameters",
   "edition": "SPEC-04P.2",
   "title": "6.12.4 Views as parameters",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#views-as-parameters",
   "internal": 0,
   "content": "#### 6.12.4 Views as parameters\n\nAn array passed to a function arrives as a view: the function reads, and with `inout` writes, the caller's elements in place, and nothing is copied. A view can also be a local variable, declared with `in` or `inout` (6.9.1). Every view carries its extents, so a function written for `in I64[_]` works on a whole array, a slice, a row or a column, and checks every index against the extent of what it received.\n\n**Semantics**"
  },
  {
   "id": "spec-04p:views-as-parameters-p1",
   "edition": "SPEC-04P.2",
   "title": "6.12.4 Views as parameters (part 2)",
   "clauses": "LS-162 M-21 M-22 M-24 M-24a M-25 M-27 V-1 V-10 V-11 V-16 V-3",
   "url": "/specifications/spec-04p/2/#views-as-parameters",
   "internal": 0,
   "content": "1. <a id=\"V-3\"></a>A view consists of: the storage it refers to; its element type; its rank `r`, from 1 to 4 (6.12.1); for each dimension `k`, an extent `n[k]` and a *stride* `s[k]`, the signed distance in elements between consecutive indices of that dimension; its *origin* `o`, the position in the storage of the element whose indices are all 0; and its *permission*, read or write, where write also permits reading. Strides and the origin are counted in elements, whatever the element type [V-1, V-3, M-24].\n2. <a id=\"V-4\"></a><a id=\"M-24a\"></a>The element of a view at indices `(i[0], ..., i[r-1])` is the element at position `o + i[0] * s[0] + ... + i[r-1] * s[r-1]` of its storage, computed exactly [V-4, M-24a].\n3. <a id=\"V-10\"></a><a id=\"V-16\"></a>A declared array is a view of its own storage with origin 0 and row-major strides: for `I32[3, 4] m`, the strides are 4 and 1. A slice, a partial index, `transpose`, `reverse` and `reshape` (7.4) each give a new view of the same storage, with other extents, strides and origin and copy no element. A stride may be negative, as in a reversed view [V-10, V-16].\n4. <a id=\"V-11\"></a>`reshape` gives a view only when the new shape addresses the same elements in the same row-major order as the view it is applied to; otherwise an implementation refuses the program (3.16, 7.4) [V-11].\n5. <a id=\"V-5\"></a><a id=\"V-6\"></a><a id=\"M-25\"></a>A view is formed only if every element it can address lies within its storage, and every access through a formed view checks each index against its extent (6.12.2, 6.12.3). No view reaches storage outside the array it was taken from [V-5, V-6, M-25].\n6. Two views of the same storage see the same elements: a write through one is read through every other at once [V-10].\n7. A view has at most the permission of the expression it is taken from. An `in` parameter or view variable has read permission and an `inou"
  },
  {
   "id": "spec-04p:views-as-parameters-p2",
   "edition": "SPEC-04P.2",
   "title": "6.12.4 Views as parameters (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#views-as-parameters",
   "internal": 0,
   "content": "**Examples**\n\n10. This example shows one function, five kinds of argument. Every call passes a view; none copies:\n\n```cint view_args.ci\nI64 total(in I64[_] xs) {\n    I64 s = 0;\n    for i in 0..len(xs) {\n        s += xs[i];\n    }\n    return s;\n}\n\nvoid main() {\n    I64[2, 3] m = [[1, 2, 3], [4, 5, 6]];\n    I64[4] a = [10, 20, 30, 40];\n    \"{total(a)} {total(a[1..3])} {total(m[1])} {total(m[.., 2])} {total(a[.. by -1])}\\n\";\n}\n```\n\n```text\n100 50 15 9 100\n```\n\n11. Writes through an `inout` view reach the caller's array, and a transposed view reads the same storage with its strides exchanged:\n\n```cint view_inout.ci\nvoid bump(inout I64[_] row) {\n    for j in 0..len(row) {\n        row[j] += 1;\n    }\n}\n\nvoid main() {\n    I64[2, 3] m;\n    bump(m[1]);\n    bump(m[.., 0]);\n    in I64[_, _] t = transpose(m);\n    \"{m[0, 0]} {m[1, 0]} {m[1, 2]} {t[2, 1]} {extent(t, 0)}\\n\";\n}\n```\n\n```text\n1 2 1 1 3\n```\n\n12. A slice of an `in` parameter is read-only and is not passed for an `inout` parameter:\n\n```cint view_permission.ci\nvoid clear(inout I64[_] v) {\n    v[0] = 0;\n}\n\nvoid first_two(in I64[_] xs) {\n    clear(xs[0..2]);\n}\n\nvoid main() {\n    I64[3] a = [1, 2, 3];\n    first_two(a);\n}\n```\n\n```text\nerror[C2067]: parameter or argument rule\n  --> view_permission.ci:6:11\n   |\n 6 |     clear(xs[0..2]);\n   |           ^\n```\n\n**Notes**\n\n13. A C function that takes a pointer and a length trusts the length it is given. A cint view carries its extents and strides with it, and the callee indexes it with the same checks as the array it came from."
  },
  {
   "id": "spec-04p:aliasing-and-copies",
   "edition": "SPEC-04P.2",
   "title": "6.12.5 Aliasing and copies",
   "clauses": "LS-70",
   "url": "/specifications/spec-04p/2/#aliasing-and-copies",
   "internal": 0,
   "content": "#### 6.12.5 Aliasing and copies\n\nElements move between arrays only by an explicit copy: an array declared with an initializer, an array assignment or `copy`. A copy requires equal shapes, and its source and destination must not overlap unless they are the same view. When they might overlap, the program copies through storage it declares; no implementation inserts a hidden temporary.\n\n**Constraints**\n\n1. <a id=\"LS-70\"></a>The source and destination of an array assignment, an array initializer and `copy(dst, src)` shall have the same shape. A difference known at translation is diagnosed C2012 [LS-70].\n2. When the source and destination of an array assignment or a `copy` provably overlap at translation, and are not the same view, the program is diagnosed C5010 [LS-70].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:aliasing-and-copies-p1",
   "edition": "SPEC-04P.2",
   "title": "6.12.5 Aliasing and copies (part 2)",
   "clauses": "IM-187 LS-69 LS-70",
   "url": "/specifications/spec-04p/2/#aliasing-and-copies",
   "internal": 0,
   "content": "3. <a id=\"LS-69\"></a>A declaration with a type and no permission keyword declares a new array. If its initializer is an array or a view, the elements are copied into the new array, and a write to the new array after the declaration does not reach the source: `I32[8, 8] left = m[.., 0..8];` is a copy. A declaration with `in` or `inout` declares a view, which shares the storage of its initializer: `inout I32[_, _] left = m[.., 0..8];` writes `m` [LS-69].\n4. Array assignment `b = a`, where `b` is an array, a view with write permission or a slice of one, and `copy(dst, src)` copy every element of the source to the destination in row-major order [LS-70].\n5. <a id=\"IM-187\"></a>The run-time checks of a copy follow the evaluation of the destination place and the source in their order (6.2.4). The shape check comes first, then the overlap check, and only then is any element written. A copy that faults writes no element [IM-187, LS-70].\n6. The source and destination of a copy shall be shown disjoint, or be exactly the same view. They are shown disjoint when either has no elements, when the lowest and highest positions each addresses do not overlap, or when both are views of one storage whose strides share a common factor `g` of at least 2 and whose origins differ modulo `g`. SPEC-02P.1 gives the procedure in full. A copy of a view onto exactly the same view has no effect. Any other pair faults `E_ALIAS` [LS-70].\n7. To move data within one array between places that may overlap, a program copies through an array it declares. No implementation stages a copy through hidden storage [LS-70].\n8. Arguments bound to `inout` parameters of a function call follow the overlap rule of 6.9.5.\n\n**Faults**"
  },
  {
   "id": "spec-04p:aliasing-and-copies-p2",
   "edition": "SPEC-04P.2",
   "title": "6.12.5 Aliasing and copies (part 3)",
   "clauses": "IM-187 LS-70",
   "url": "/specifications/spec-04p/2/#aliasing-and-copies",
   "internal": 0,
   "content": "9. The fault `E_SHAPE` is raised by a copy whose source and destination differ in shape at run time. The fault record holds the operation identifier `copy.shape`; two operands, the lowest dimension in which the extents differ, counted from 0, and the source's extent in that dimension, both `I64`; no exact result; and the destination's extent in that dimension as the limit, an `I64`. Its position is the `=` of the assignment or declaration, or the name `copy` [IM-187].\n10. The fault `E_ALIAS` is raised by a copy whose source and destination are not shown disjoint at run time and are not the same view. The fault record holds the operation identifier `copy.alias`, no operands, no exact result and no limit. Its position is the `=` or the name `copy` [IM-187, LS-70].\n\n**Examples**\n\n11. This example shows a copy and a view from the same initializer:\n\n```cint copy_or_view.ci\nvoid main() {\n    I64[2, 4] m = [[1, 2, 3, 4], [5, 6, 7, 8]];\n    I64[2, 2] left = m[.., 0..2];\n    inout I64[_, _] right = m[.., 2..4];\n    left[0, 0] = 100;\n    right[0, 0] = 300;\n    \"{m[0, 0]} {m[0, 2]} {left[0, 0]}\\n\";\n}\n```\n\n```text\n1 300 100\n```\n\n12. Copies that are accepted: through a declared array, onto the same view, and between the even and odd elements of one array, which share storage but no element:\n\n```cint copy_accepted.ci\nvoid main() {\n    I64[8] x = [0, 1, 2, 3, 4, 5, 6, 7];\n    I64[4] tmp;\n    tmp = x[2..6];\n    x[0..4] = tmp;\n    x[0..8] = x[0..8];\n    x[0..8 by 2] = x[1..8 by 2];\n    for i in 0..8 {\n        \"{x[i]} \";\n    }\n    \"\\n\";\n}\n```\n\n```text\n3 3 5 5 5 5 7 7 \n```\n\n13. This example shows overlap known at translation. `x[0..8 by 2]` addresses positions 0, 2, 4 and 6 and `x[0..4]` positions 0 to 3:\n\n```cint copy_overlap.ci\nvoid main() {\n    I64[16] x;\n    x[0..8 by 2] = x[0..4];\n}\n```"
  },
  {
   "id": "spec-04p:aliasing-and-copies-p3",
   "edition": "SPEC-04P.2",
   "title": "6.12.5 Aliasing and copies (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#aliasing-and-copies",
   "internal": 0,
   "content": "```text\nerror[C5010]: parameter mode, alias, or ABI rule\n  --> copy_overlap.ci:3:20\n   |\n 3 |     x[0..8 by 2] = x[0..4];\n   |                    ^\n```\n\n14. This example shows overlap known only at run time. With `j` equal to 2, the source `x[2..6]` and the destination `x[0..4]` share two elements:\n\n```cint copy_alias.ci\nvoid shift(inout I64[_] x, I64 j) {\n    copy(x[0..4], x[j..j + 4]);\n}\n\nvoid main() {\n    I64[8] x = [0, 1, 2, 3, 4, 5, 6, 7];\n    shift(x, 2);\n}\n```\n\n```text\nfault[E_ALIAS]: views overlap\n  --> copy_alias.ci:2:5\n   |\n 2 |     copy(x[0..4], x[j..j + 4]);\n   |     ^ copy.alias\n   |\n   = operation: copy.alias\n   = operand-count: 0\n   = exact:   none\n   = limit:   none\n   ...\n```\n\n15. This example shows shapes that differ at run time:\n\n```cint copy_shape.ci\nvoid put(inout I64[_] dst, in I64[_] src) {\n    dst = src;\n}\n\nvoid main() {\n    I64[2] dst;\n    I64[3] src = [1, 2, 3];\n    put(dst, src);\n}\n```\n\n```text\nfault[E_SHAPE]: shapes do not match\n  --> copy_shape.ci:2:9\n   |\n 2 |     dst = src;\n   |         ^ copy.shape\n   |\n   = operation: copy.shape\n   = operand-count: 2\n   = operand: I64 0\n   = operand: I64 3\n   = exact:   none\n   = limit:   I64 2\n   ...\n```\n\n**Notes**\n\n16. C's `memcpy` has undefined behavior on overlapping arguments, and `memmove` behaves as if it copied through a temporary. A cint copy does neither: an overlap that the tests cannot exclude is a diagnostic or a fault, and the program states where the elements go in between."
  },
  {
   "id": "spec-04p:module-level-arrays",
   "edition": "SPEC-04P.2",
   "title": "6.12.6 Module-level arrays",
   "clauses": "LS-67",
   "url": "/specifications/spec-04p/2/#module-level-arrays",
   "internal": 0,
   "content": "#### 6.12.6 Module-level arrays\n\nAn array declared at module level lives as long as the program's context, instead of the call that declares it. Every function of the module reads and writes it, and it can be passed as a view argument like any other array. The declaration rules for module-level variables, arrays and handles are in 6.9.3; this subclause states what differs for arrays.\n\n**Constraints**\n\n1. The extents of a module-level array are constant expressions, as 6.12.1 states.\n\n**Semantics**\n\n2. A module-level array has every element 0 unless its declaration has a constant initializer (6.9.3), and it keeps its elements between calls and between entries. It is not storage of the frame arena (5.2.6) [LS-67].\n3. In a script, a variable declared among the top-level statements is a local of the script's implicit entry (5.1.2), so an array declared there is a local array, not a module-level array. A module-level array belongs to a module without top-level statements, such as one that defines `void main()`.\n\n**Examples**\n\n4. This example shows a module-level counter array, written by one function and read by another:\n\n```cint module_array.ci\nI64[4] counts;\nI64[2, 2] grid = [[1, 2], [3, 4]];\n\nvoid tally(I64 k) {\n    counts[k] += 1;\n}\n\nI64 total(in I64[_] v) {\n    I64 s = 0;\n    for i in 0..len(v) {\n        s += v[i];\n    }\n    return s;\n}\n\nvoid main() {\n    tally(1);\n    tally(1);\n    tally(3);\n    grid[1, 0] += counts[1];\n    \"{counts[0]} {counts[1]} {counts[3]} {total(counts)} {grid[1, 0]}\\n\";\n}\n```\n\n```text\n0 2 1 3 5\n```\n\n5. An array declared among the top-level statements of a script is a local of the script's entry:\n\n```cint script_array.ci\nI64[3] a = [1, 2, 3];\na[0] += 40;\n\"{a[0]}\\n\";\n```\n\n```text\n41\n```\n\n6. This example shows a module-level extent that is not a constant:\n\n```cint module_array_extent.ci\nI64 n = 3;\nI64[n] a;\n\nvoid main() {\n    \"{len(a)}\\n\";\n}\n```"
  },
  {
   "id": "spec-04p:module-level-arrays-p1",
   "edition": "SPEC-04P.2",
   "title": "6.12.6 Module-level arrays (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#module-level-arrays",
   "internal": 0,
   "content": "```text\nerror[C6004]: constant expression required\n  --> module_array_extent.ci:2:5\n   |\n 2 | I64[n] a;\n   |     ^\n```"
  },
  {
   "id": "spec-04p:kernels",
   "edition": "SPEC-04P.2",
   "title": "6.13 Kernels",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#kernels",
   "internal": 0,
   "content": "### 6.13 Kernels\n\nA kernel is a function written for one point of an iteration space. A *dispatch* runs it once for every point, each run a *work-item*, over arrays passed as arguments. Every work-item reads the values its arguments held before the dispatch and writes only its own part of the outputs, so no work-item can see another, and the outputs are the same whatever order the work-items run in. If every work-item succeeds, all outputs appear at once; if any faults, none does.\n\nThis section states the meaning of a kernel and of a dispatch: declarations (6.13.1), parameters (6.13.2), the body (6.13.3), the dispatch statement (6.13.4), reductions (6.13.5) and the reference meaning that every executor reproduces (6.13.6). The executors of cint 0.2.0 that run kernels, and what each of them shall do to give that meaning, are in SPEC-02P.1."
  },
  {
   "id": "spec-04p:kernel-declarations",
   "edition": "SPEC-04P.2",
   "title": "6.13.1 Kernel declarations",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#kernel-declarations",
   "internal": 0,
   "content": "#### 6.13.1 Kernel declarations\n\nA kernel declaration names the kernel, its size parameters (3.34), its parameters with a mode for each, and usually an *over clause* that gives the iteration space. The body is written once, for one work-item, using the over clause's variables as that work-item's indices.\n\n**Syntax**\n\n```ebnf\nkernel_decl  = \"kernel\" IDENT size_params \"(\" [ kparam { \",\" kparam } [ \",\" ] ] \")\"\n               [ over_clause ] [ where_clause ] block ;\nkparam       = ( \"in\" | \"out\" | \"inout\" ) type IDENT ;\nover_clause  = \"over\" \"[\" IDENT \":\" shape_expr { \",\" IDENT \":\" shape_expr } \"]\" ;\nwhere_clause = \"where\" constraint { \",\" constraint } ;\nconstraint   = shape_expr ( \"==\" | \"<\" | \"<=\" | \">\" | \">=\" ) shape_expr ;\nshape_expr   = IDENT | INT_LIT | IDENT ( \"+\" | \"-\" ) INT_LIT ;\n```\n\nEach extent in the type of an array parameter is a `shape_expr`, and `INT_LIT` is an integer literal (6.4.5). `size_params` is as for a function (6.9.4), and `export` comes before a kernel as before any `declaration` (6.15.1).\n\n**Constraints**"
  },
  {
   "id": "spec-04p:kernel-declarations-p1",
   "edition": "SPEC-04P.2",
   "title": "6.13.1 Kernel declarations (part 2)",
   "clauses": "K-1 K-2 K-3 K-5 K-8 LS-244 LS-246",
   "url": "/specifications/spec-04p/2/#kernel-declarations",
   "internal": 0,
   "content": "1. <a id=\"LS-244\"></a>Every parameter has a mode, `in`, `out` or `inout`; a parameter without one is a syntax error (C1050). A kernel has no result type: a type before the kernel's name is diagnosed C1010 [LS-244].\n2. <a id=\"K-5\"></a>Each size parameter appears alone as an extent of at least one array parameter. A size parameter that appears in no such extent is diagnosed C2065 [K-5].\n3. <a id=\"K-3\"></a>A kernel has at least one parameter of mode `out` or `inout`. A kernel without one is diagnosed C9102 at its name [K-3].\n4. <a id=\"LS-246\"></a>An array parameter has an integer or fixed-point element type, and a scalar parameter an integer or fixed-point type. A parameter of any other type, such as `Bool` or a struct, is diagnosed C5028 [LS-246].\n5. A scalar parameter has mode `in` or `out`. A scalar `inout` parameter is diagnosed C2064 [K-2].\n6. <a id=\"K-8\"></a>With an over clause of `d` variables, every array parameter of mode `out` or `inout` has rank `d` or more, and its first `d` extents are the over clause's extents, written the same way and in the same order. A parameter of lower rank or with other leading extents is diagnosed C9102 at its name [K-8].\n7. Each extent of an array parameter, each over extent and each side of a `where` constraint is a shape expression: a size parameter, a decimal literal or a size parameter plus or minus a decimal literal. A `where` constraint compares two of them with `==`, `<`, `<=`, `>` or `>=`. Any other extent or comparison, such as `I64[n * 2]` or `where n != 0`, is diagnosed C9102 [K-1].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:kernel-declarations-p2",
   "edition": "SPEC-04P.2",
   "title": "6.13.1 Kernel declarations (part 3)",
   "clauses": "K-6 K-8 K-9 LS-243 LS-244 LS-247",
   "url": "/specifications/spec-04p/2/#kernel-declarations",
   "internal": 0,
   "content": "8. <a id=\"LS-243\"></a>A kernel body is written for one work-item [LS-243].\n9. Size parameters are `I64` values, bound when a dispatch begins from the extents of the arguments (6.13.2). A `where` clause states requirements on them, checked at the same time [LS-244, K-6].\n10. <a id=\"LS-247\"></a>The over clause `over [v1: E1, ..., vd: Ed]` gives the *iteration space*: one work-item for each index tuple `(v1, ..., vd)` with `0 <= vk < Ek`. Each over variable is an `I64` that holds its work-item's index in that dimension. If any `Ek` is 0, the dispatch has no work-items [K-8, LS-247].\n11. <a id=\"K-9\"></a>The *work-item index* is the position of a work-item's tuple in row-major order, counted from 0: for `over [y: h, x: w]`, the work-item `(y, x)` has index `y * w + x` [K-9].\n12. For an array parameter of mode `out` or `inout` and rank `r`, the dimensions after the first `d` form the *owned block*: work-item `(v1, ..., vd)` owns the elements whose first `d` indices are `v1, ..., vd`. With `over [i: n]` and `out I64[n, k] q`, work-item `i` owns the row `q[i, ..]`; with `out I64[n] g`, it owns the one element `g[i]` [K-8].\n13. When a kernel's only outputs are scalar `out` parameters, its over extents may be any shape expressions [K-8].\n14. A kernel without an over clause is in element form (6.13.3) [LS-247].\n\n**Examples**\n\n15. This example shows a kernel over a rank-2 iteration space. Each work-item computes one element of `b`:\n\n```cint kernel_scale.ci\nkernel scale[h, w](in I32[h, w] a, in I32 k, out I64[h, w] b) over [y: h, x: w] {\n    b[y, x] = (a[y, x] as I64) * (k as I64);\n}\n\nvoid main() {\n    I32[2, 3] a = [[1, 2, 3], [4, 5, 6]];\n    I64[2, 3] b;\n    scale(a, 7, b);\n    \"{b[0, 1]} {b[1, 2]}\\n\";\n}\n```\n\n```text\n14 42\n```\n\n16. This example shows an over extent that is a shape expression, and a work-item for each adjacent pair:"
  },
  {
   "id": "spec-04p:kernel-declarations-p3",
   "edition": "SPEC-04P.2",
   "title": "6.13.1 Kernel declarations (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#kernel-declarations",
   "internal": 0,
   "content": "```cint kernel_diffs.ci\nkernel diffs[n](in I64[n] x, out I64[n - 1] d) over [i: n - 1] {\n    d[i] = x[i + 1] - x[i];\n}\n\nvoid main() {\n    I64[4] x = [1, 4, 9, 16];\n    I64[3] d;\n    diffs(x, d);\n    \"{d[0]} {d[1]} {d[2]}\\n\";\n}\n```\n\n```text\n3 5 7\n```\n\n17. `Bool` is not a kernel parameter type:\n\n```cint kernel_bool.ci\nkernel pick[n](in Bool[n] keep, out I64[n] b) over [i: n] {\n    b[i] = 0;\n}\n\nvoid main() {\n    \"unreached\\n\";\n}\n```\n\n```text\nerror[C5028]: parameter mode, alias, or ABI rule\n  --> kernel_bool.ci:1:16\n   |\n 1 | kernel pick[n](in Bool[n] keep, out I64[n] b) over [i: n] {\n   |                ^\n```"
  },
  {
   "id": "spec-04p:parameter-modes-and-shapes",
   "edition": "SPEC-04P.2",
   "title": "6.13.2 Parameter modes and shapes",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#parameter-modes-and-shapes",
   "internal": 0,
   "content": "#### 6.13.2 Parameter modes and shapes\n\nThe mode of a kernel parameter says what the body may do with it. An `in` array is read, an `out` array is written, and an `inout` array is both read and written; a scalar `in` is a value shared by every work-item, and a scalar `out` receives the result of a reduction (6.13.5). When a dispatch begins, the size parameters are bound from the arguments, every extent is checked, and the arguments are checked for overlap, before any work-item runs.\n\n| Mode | Kind | The body may | The body may not | Argument |\n|---|---|---|---|---|\n| `in` | array | read any element | write | a view, with read or write permission |\n| `in` | scalar | read the value, which is the same for every work-item | assign it | a value of exactly the parameter's type |\n| `out` | array | write the elements of its owned block | read | a view with write permission |\n| `out` | scalar | be the target of one `reduce` statement | read or assign it | a variable of exactly the parameter's type |\n| `inout` | array | read any element; write the elements of its owned block | write other elements | a view with write permission |\n\n**Constraints**"
  },
  {
   "id": "spec-04p:parameter-modes-and-shapes-p1",
   "edition": "SPEC-04P.2",
   "title": "6.13.2 Parameter modes and shapes (part 2)",
   "clauses": "K-2 K-4 K-7 LS-245",
   "url": "/specifications/spec-04p/2/#parameter-modes-and-shapes",
   "internal": 0,
   "content": "1. <a id=\"K-2\"></a>An `in` parameter is not assigned: a write to an element of an `in` array or to a scalar `in` is diagnosed C2060 [K-2].\n2. The body does not read an array `out` parameter, and it does not read or assign a scalar `out` parameter except through its `reduce` statement. Such a read or assignment is diagnosed C9102 [K-2].\n3. <a id=\"K-4\"></a><a id=\"K-7\"></a>An array argument has the element type and the rank of its parameter (C2001). An argument for an `out` or `inout` array has write permission (C2067). When the extents of every argument are known at translation, the checks of paragraph 6 run then, and a mismatch is diagnosed C2012 [K-2, K-4, K-7].\n4. An argument for a scalar `in` parameter has exactly the parameter's type (C2001); a literal argument takes the parameter's type. An argument for a scalar `out` parameter is a variable of exactly the parameter's type: another type is diagnosed C2001, and an argument that is not a variable, such as a literal, is diagnosed C2067 [K-2, K-4].\n5. <a id=\"LS-245\"></a>An argument for an `out` or `inout` parameter that provably overlaps another array argument at translation, such as the same array passed twice, is diagnosed C5010 [LS-245].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:parameter-modes-and-shapes-p2",
   "edition": "SPEC-04P.2",
   "title": "6.13.2 Parameter modes and shapes (part 3)",
   "clauses": "A-1 A-2 A-3 A-4 K-1 K-6 M-26",
   "url": "/specifications/spec-04p/2/#parameter-modes-and-shapes",
   "internal": 0,
   "content": "6. <a id=\"K-6\"></a>Size parameters are bound in two passes over the array parameters, in declaration order and, within each, dimension by dimension. The first pass binds each size parameter at its first occurrence alone as an extent, to the argument's extent there. The second pass evaluates every extent with checked `I64` arithmetic and compares it with the argument's extent; the first difference faults. For `kernel k[n](in I64[n + 1] a, out I64[n] b)` with `a` of extent 5 and `b` of extent 3, the first pass binds `n` to 3 from `b`, and the second reports `a`, whose extent should be 4 [K-6].\n7. <a id=\"K-1\"></a>After binding, the constraints of the `where` clause are evaluated in written order, and the first that is false faults [K-1].\n8. <a id=\"A-1\"></a>`in` arguments may overlap each other, and one view may be passed to several `in` parameters [A-1].\n9. <a id=\"A-2\"></a>The elements of every `out` or `inout` argument shall be disjoint from the elements of every other array argument of the same dispatch, whatever its mode [A-2].\n10. <a id=\"A-3\"></a>Overlap is decided by the tests of 6.12.5, paragraph 6, given in full in SPEC-02P.1. A pair those tests show disjoint is accepted; every other pair, whether it overlaps or the tests cannot decide, faults `E_ALIAS`. Some pairs that share no element therefore fault. The same tests apply to every dispatch, whether cint code or a host program issues it, and nothing a program states about its arguments counts as evidence that they are disjoint [A-3].\n11. <a id=\"A-4\"></a><a id=\"M-26\"></a>Every view bound to an `out` or `inout` parameter shall address a distinct element for each index tuple. A view that fails the test of SPEC-02P.1 for this property faults `E_ALIAS` [A-4, M-26].\n12. These checks run when the dispatch begins, before any work-item. A fault here is in the *entry phase* of the dispatch: its address has a dispatch numbe"
  },
  {
   "id": "spec-04p:parameter-modes-and-shapes-p3",
   "edition": "SPEC-04P.2",
   "title": "6.13.2 Parameter modes and shapes (part 4)",
   "clauses": "A-3 K-1 K-6",
   "url": "/specifications/spec-04p/2/#parameter-modes-and-shapes",
   "internal": 0,
   "content": "**Faults**\n\n13. The fault `E_SHAPE` is raised by an argument extent that differs from the extent the second pass computes. The fault record holds the operation identifier `bind.shape`; three operands, the parameter's position counted from 0, the dimension counted from 0 and the argument's extent, all `I64`; no exact result; and the computed extent as the limit, an `I64`. Its position is the kernel name of the dispatch [K-6].\n14. The fault `E_OVERFLOW` is raised when an extent expression `n + c` or `n - c` leaves the range of `I64`, with the operation identifier `add.checked.i64` or `sub.checked.i64`. A computed extent below 0 faults `E_SHAPE` [K-6].\n15. The fault `E_SHAPE` is raised by a false `where` constraint. The fault record holds the operation identifier `bind.where`; three operands, the constraint's position in the clause counted from 0 and the values of its left and right sides, all `I64`; no exact result and no limit [K-1].\n16. The fault `E_ALIAS` is raised by a pair of arguments not shown disjoint. The fault record holds the operation identifier `bind.alias` and two `I64` operands: the position of the `out` or `inout` parameter and the position of the other parameter. It has no exact result and no limit [A-3].\n\n**Examples**\n\n17. This example shows the results of the overlap tests for `kernel inc[n](in I32[n] u, out I32[n] v)`. Each row shows the outcome of the program written in its first column:"
  },
  {
   "id": "spec-04p:parameter-modes-and-shapes-p4",
   "edition": "SPEC-04P.2",
   "title": "6.13.2 Parameter modes and shapes (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#parameter-modes-and-shapes",
   "internal": 0,
   "content": "| Dispatch | Result |\n|---|---|\n| `inc(a, b)` with two arrays | accepted |\n| `inc(a, a)` | C5010 |\n| `inc(p[0], p[1])` with `I32[2, 64] p` | accepted: the rows do not overlap |\n| `inc(m[0..128 by 2], m[1..128 by 2])` with `I32[128] m` | accepted: the even and odd elements share no element |\n| `inc(a[0..4], a[4..8])` with `I32[8] a` | accepted |\n| `inc(q[0..8], q[1..9])` with `I32[9] q` | `E_ALIAS`: the views share seven elements |\n| `inc(a, reverse(a, 0))` | `E_ALIAS`: the views are the same elements in another order |\n\n18. This example shows the same array for an `in` and an `out` parameter:\n\n```cint kernel_same_array.ci\nkernel inc[n](in I32[n] u, out I32[n] v) over [i: n] {\n    v[i] = u[i] + 1;\n}\n\nvoid main() {\n    I32[16] a;\n    inc(a, a);\n}\n```\n\n```text\nerror[C5010]: parameter mode, alias, or ABI rule\n  --> kernel_same_array.ci:7:12\n   |\n 7 |     inc(a, a);\n   |            ^\n```\n\n19. The two passes of paragraph 6, with extents that the compiler does not see because they arrive through views:\n\n```cint kernel_shape.ci\nkernel pair_sums[n](in I64[n + 1] a, out I64[n] b) over [i: n] {\n    b[i] = a[i] + a[i + 1];\n}\n\nvoid sums(in I64[_] a, inout I64[_] b) {\n    pair_sums(a, b);\n}\n\nvoid main() {\n    I64[5] a;\n    I64[3] b;\n    sums(a, b);\n}\n```\n\n```text\nfault[E_SHAPE]: shapes do not match\n  --> kernel_shape.ci:6:5\n   |\n 6 |     pair_sums(a, b);\n   |     ^ bind.shape\n   |\n   = operation: bind.shape\n   = operand-count: 3\n   = operand: I64 0\n   = operand: I64 0\n   = operand: I64 5\n   = exact:   none\n   = limit:   I64 4\n   ...\n   = address: kernel_shape.pair_sums, dispatch 0, phase 0, work-item none, step none\n   ...\n```\n\nThe operands name parameter 0, `a`, and its dimension 0, whose extent is 5 where `n + 1` is 4. The address line names the kernel, the dispatch number, the entry phase (0) and no work-item or step."
  },
  {
   "id": "spec-04p:parameter-modes-and-shapes-p5",
   "edition": "SPEC-04P.2",
   "title": "6.13.2 Parameter modes and shapes (part 6)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#parameter-modes-and-shapes",
   "internal": 0,
   "content": "20. This example shows a `where` clause, and overlapping slices of one array:\n\n```cint kernel_where.ci\nkernel smooth[n](in I64[n] u, out I64[n] v) over [i: n] where n >= 3 {\n    v[i] = u[i];\n}\n\nvoid main() {\n    I64[2] u;\n    I64[2] v;\n    smooth(u, v);\n}\n```\n\n```text\nfault[E_SHAPE]: shapes do not match\n  --> kernel_where.ci:8:5\n   |\n 8 |     smooth(u, v);\n   |     ^ bind.where\n   |\n   = operation: bind.where\n   = operand-count: 3\n   = operand: I64 0\n   = operand: I64 2\n   = operand: I64 3\n   = exact:   none\n   = limit:   none\n   ...\n```\n\nOverlapping slices of one array:\n\n```cint kernel_alias.ci\nkernel inc[n](in I32[n] u, out I32[n] v) over [i: n] {\n    v[i] = u[i] + 1;\n}\n\nvoid main() {\n    I32[9] q;\n    inc(q[0..8], q[1..9]);\n}\n```\n\n```text\nfault[E_ALIAS]: views overlap\n  --> kernel_alias.ci:7:5\n   |\n 7 |     inc(q[0..8], q[1..9]);\n   |     ^ bind.alias\n   |\n   = operation: bind.alias\n   = operand-count: 2\n   = operand: I64 1\n   = operand: I64 0\n   = exact:   none\n   = limit:   none\n   ...\n```\n\n**Notes**\n\n21. A program whose arguments share no element but fail the overlap tests chooses a layout that the tests accept, or copies one argument first."
  },
  {
   "id": "spec-04p:the-body",
   "edition": "SPEC-04P.2",
   "title": "6.13.3 The body",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#the-body",
   "internal": 0,
   "content": "#### 6.13.3 The body\n\nA kernel body is ordinary sequential code with three kinds of limit: it writes outputs only at its own work-item's indices, it writes every element it owns, and it does nothing whose effect another work-item or the rest of the program could see while the dispatch runs.\n\n**Constraints**"
  },
  {
   "id": "spec-04p:the-body-p1",
   "edition": "SPEC-04P.2",
   "title": "6.13.3 The body (part 2)",
   "clauses": "K-10 K-10a K-11 K-12 K-13 LS-247 LS-248 LS-250",
   "url": "/specifications/spec-04p/2/#the-body",
   "internal": 0,
   "content": "1. An over variable is not assigned (C2052) [LS-247].\n2. <a id=\"LS-248\"></a><a id=\"K-10\"></a>Every write to an array parameter of mode `out` or `inout` has the over variables, in order, as its first indices. Any further indices address the owned block and may be any `I64` expressions. A write of another form is diagnosed C5031 [LS-248, K-10].\n3. <a id=\"K-10a\"></a>Every element of the owned block of every array `out` parameter is written on every path through the body that completes. A kernel satisfies this rule when its writes fit one of two patterns; a kernel whose writes fit neither is diagnosed C5031 [LS-248, K-10a]:\n   - a write whose indices are exactly the over variables, executed unconditionally, in both branches of an `if` with an `else`, or in every case of a `switch` with a `default`;\n   - a nest of `for` loops, one for each dimension of the owned block, each over that dimension's full range `0..E` with a bound that is the same for every work-item, whose innermost body writes the element with the loop variables in dimension order, unconditionally and before any `break` or `continue`; the nest itself runs under the conditions of the first pattern.\n4. <a id=\"LS-250\"></a><a id=\"K-11\"></a>A kernel body does not contain a print statement (C5020), a `defer` statement (C5021), `try` or a value of an error union type (C5022), a dispatch (C5023) or a use of a module-level variable (C5025). Named constants and the built-in operations of clause 7 may be used [LS-250, K-11].\n5. <a id=\"K-13\"></a>A local array in a kernel body, a *private array*, has constant extents and its number of elements times the width of its element type, counting a `Bool` element as 8 bits, is at most 32,768 bits: at most 512 `I64` elements, or 4,096 `U8` elements. A private array with an extent that is not constant is diagnosed C9102 at that extent, and a private array above this size is diagnos"
  },
  {
   "id": "spec-04p:the-body-p2",
   "edition": "SPEC-04P.2",
   "title": "6.13.3 The body (part 3)",
   "clauses": "K-10 K-10a K-12 LS-247 LS-256",
   "url": "/specifications/spec-04p/2/#the-body",
   "internal": 0,
   "content": "**Semantics**\n\n7. <a id=\"X-7\"></a>Each work-item runs the body as a sequential program, in the evaluation order of 6.2.4, and every checked operator is checked where it occurs. An executor may reorder or combine work only when the outputs, and which fault occurs first with its operands, are unchanged [X-7].\n8. <a id=\"LS-256\"></a>Size parameters, over variables and the arithmetic on indices are `I64` [LS-256].\n9. A work-item may write an element of its owned block more than once, under `if` and in loops. The value published for the element is the last one written in the work-item's evaluation order. An element of an `inout` owned block that the work-item does not write keeps the value it had before the dispatch [K-10, K-10a].\n10. A body in element form means the same as the indexed form with one over variable for each dimension: `next = old + step;` over parameters of shape `[n]` is `next[i] = old[i] + step[i];` with `over [i: n]`. A scalar `in` parameter in the expression is the same value for every element [K-12, LS-247].\n\n11. A kernel body that calls a user function is outside this edition (6.16), and an implementation refuses a program that has one (3.16).\n\n**Examples**\n\n12. This example shows element form, with a scalar parameter:\n\n```cint kernel_element_form.ci\nkernel scale_add[n](in I64[n] a, in I64 k, out I64[n] b) {\n    b = a * k + 1;\n}\n\nvoid main() {\n    I64[3] a = [1, 2, 3];\n    I64[3] b;\n    scale_add(a, 10, b);\n    \"{b[0]} {b[1]} {b[2]}\\n\";\n}\n```\n\n```text\n11 21 31\n```\n\n13. Writes that cover the owned block: in both branches of an `if`, and in a loop over the block. Each work-item of `row_sums` owns one element of `s` and one row of `c`:\n\n```cint kernel_coverage.ci\nkernel clamp_negative[n](in I64[n] a, out I64[n] b) over [i: n] {\n    if (a[i] < 0) {\n        b[i] = 0;\n    } else {\n        b[i] = a[i];\n    }\n}"
  },
  {
   "id": "spec-04p:the-body-p3",
   "edition": "SPEC-04P.2",
   "title": "6.13.3 The body (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#the-body",
   "internal": 0,
   "content": "kernel row_sums[n, k](in I64[n, k] a, out I64[n] s, out I64[n, k] c) over [i: n] {\n    I64 t = 0;\n    for j in 0..k {\n        t += a[i, j];\n        c[i, j] = t;\n    }\n    s[i] = t;\n}\n\nvoid main() {\n    I64[3] a = [-1, 2, -3];\n    I64[3] b;\n    clamp_negative(a, b);\n    I64[2, 3] m = [[1, 2, 3], [4, 5, 6]];\n    I64[2] s;\n    I64[2, 3] c;\n    row_sums(m, s, c);\n    \"{b[0]} {b[1]} {b[2]}\\n\";\n    \"{s[0]} {s[1]} {c[1, 0]} {c[1, 1]} {c[1, 2]}\\n\";\n}\n```\n\n```text\n0 2 0\n6 15 4 9 15\n```\n\n14. The last write is the one published:\n\n```cint kernel_last_write.ci\nkernel flag_positive[n](in I64[n] a, out I64[n] b) over [i: n] {\n    b[i] = 1;\n    if (a[i] > 0) {\n        b[i] = 2;\n    }\n}\n\nvoid main() {\n    I64[2] a = [0, 5];\n    I64[2] b;\n    flag_positive(a, b);\n    \"{b[0]} {b[1]}\\n\";\n}\n```\n\n```text\n1 2\n```\n\n15. This example shows a write outside the owned block:\n\n```cint kernel_write_rule.ci\nkernel spill[n](in I64[n] a, out I64[n] b) over [i: n] {\n    b[i + 1] = a[i];\n}\n\nvoid main() {\n    \"unreached\\n\";\n}\n```\n\n```text\nerror[C5031]: parameter mode, alias, or ABI rule\n  --> kernel_write_rule.ci:2:5\n   |\n 2 |     b[i + 1] = a[i];\n   |     ^\n```\n\n16. A write that some work-items skip leaves part of the output unwritten:\n\n```cint kernel_coverage_missing.ci\nkernel partial[n](in I64[n] a, out I64[n] b) over [i: n] {\n    if (i > 0) {\n        b[i] = a[i];\n    }\n}\n\nvoid main() {\n    \"unreached\\n\";\n}\n```\n\n```text\nerror[C5031]: parameter mode, alias, or ABI rule\n  --> kernel_coverage_missing.ci:3:9\n   |\n 3 |         b[i] = a[i];\n   |         ^\n```\n\n17. A kernel body does not print:\n\n```cint kernel_print.ci\nkernel noisy[n](in I64[n] a, out I64[n] b) over [i: n] {\n    \"i={i}\\n\";\n    b[i] = a[i];\n}\n\nvoid main() {\n    \"unreached\\n\";\n}\n```\n\n```text\nerror[C5020]: parameter mode, alias, or ABI rule\n  --> kernel_print.ci:2:5\n   |\n 2 |     \"i={i}\\n\";\n   |     ^\n```"
  },
  {
   "id": "spec-04p:the-body-p4",
   "edition": "SPEC-04P.2",
   "title": "6.13.3 The body (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#the-body",
   "internal": 0,
   "content": "18. An index in the owned block is checked against the block's extent. Here work-item 0 reads `a[0, 3]` in a dimension of extent 3:\n\n```cint kernel_block_bounds.ci\nkernel shift_rows[n, k](in I64[n, k] a, out I64[n, k] b) over [i: n] {\n    for j in 0..k {\n        b[i, j] = a[i, j + 1];\n    }\n}\n\nvoid main() {\n    I64[2, 3] a;\n    I64[2, 3] b;\n    shift_rows(a, b);\n}\n```\n\n```text\nfault[E_BOUNDS]: index out of bounds\n  --> kernel_block_bounds.ci:3:20\n   |\n 3 |         b[i, j] = a[i, j + 1];\n   |                    ^ index.checked.i64\n   |\n   = operation: index.checked.i64\n   = operand-count: 2\n   = operand: I64 1\n   = operand: I64 3\n   = exact:   none\n   = limit:   I64 3\n   ...\n   = address: kernel_block_bounds.shift_rows, dispatch 0, phase 1, work-item 0, step 8\n   ...\n```"
  },
  {
   "id": "spec-04p:dispatch",
   "edition": "SPEC-04P.2",
   "title": "6.13.4 Dispatch",
   "clauses": "LS-251",
   "url": "/specifications/spec-04p/2/#dispatch",
   "internal": 0,
   "content": "#### 6.13.4 Dispatch\n\nA dispatch is written like a call statement: the kernel's name and its arguments. It runs every work-item, then publishes the outputs, before the next statement runs.\n\n**Syntax**\n\n```ebnf\ncall = IDENT [ \".\" IDENT ] \"(\" [ args ] \")\" ;\n```\n\nA dispatch is a `call` whose callee names a kernel, standing as a statement (6.10.1). `args` is as for any call (6.7.4).\n\n**Constraints**\n\n1. <a id=\"LS-251\"></a>A dispatch is a statement and has no value. A dispatch used as an expression is diagnosed C2001, and `try` before a dispatch is diagnosed C2043 [LS-251].\n2. A dispatch is written in sequential code. A dispatch inside a kernel body is diagnosed C5023 (6.13.3).\n\n**Semantics**"
  },
  {
   "id": "spec-04p:dispatch-p1",
   "edition": "SPEC-04P.2",
   "title": "6.13.4 Dispatch (part 2)",
   "clauses": "K-14 K-15 LS-251 LS-288",
   "url": "/specifications/spec-04p/2/#dispatch",
   "internal": 0,
   "content": "3. <a id=\"K-14\"></a>A dispatch runs its kernel's work-items as 6.13.6 defines. It is synchronous: when it completes, the statement after it runs and observes the published outputs [K-14, LS-251].\n4. <a id=\"P-1\"></a>Every dispatch is *staged*. The work-items write into storage of their own, which the program cannot observe. If the dispatch completes without a fault, every `out` and `inout` array argument and every scalar `out` variable is *published*: given its new elements at once. If the dispatch faults, nothing is published, and every argument and every variable bound to a scalar `out` holds exactly what it held before the dispatch [P-1, LS-251].\n5. <a id=\"P-2\"></a>No statement after a dispatch can observe some of its outputs updated and others not [P-2].\n6. <a id=\"P-4\"></a>In a dispatch, an `inout` parameter has copy-in, copy-out meaning. Every read of it, at any index and at any time during the dispatch, gives the element's value from before the dispatch, including a work-item's read of an element it has already written. Elements that no work-item writes keep their values [P-4, LS-251].\n7. A fault in a dispatch ends the entry, as any fault does (5.2.3): no statement of the entry after it runs [K-14].\n8. <a id=\"P-3\"></a><a id=\"LS-288\"></a>Every dispatch takes the next *dispatch number* of the entry, from 0 in program order, whether it completes or faults [P-3, LS-288].\n9. <a id=\"K-15\"></a>A dispatch issued through the host interface makes the same checks in the same order and has the same outcome as the same dispatch written in cint source. SPEC-03P.1 describes that interface [K-15].\n\n**Examples**\n\n10. This example shows copy-in and copy-out. Each work-item but the last copies its right neighbor, and every read sees the value from before the dispatch:"
  },
  {
   "id": "spec-04p:dispatch-p2",
   "edition": "SPEC-04P.2",
   "title": "6.13.4 Dispatch (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#dispatch",
   "internal": 0,
   "content": "```cint dispatch_inout.ci\nkernel shift_left[n](inout I64[n] t) over [i: n] {\n    if (i + 1 < n) {\n        t[i] = t[i + 1];\n    }\n}\n\nvoid main() {\n    I64[4] t = [1, 2, 3, 4];\n    shift_left(t);\n    \"{t[0]} {t[1]} {t[2]} {t[3]}\\n\";\n}\n```\n\n```text\n2 3 4 4\n```\n\n11. A step that needs the whole previous state alternates between two arrays, one dispatch per step. Each dispatch reads one array and publishes the other:\n\n```cint dispatch_double_buffer.ci\nkernel smooth[n](in I64[n] u, out I64[n] v) over [i: n] where n >= 3 {\n    I64 r = u[i];\n    if (i > 0 && i < n - 1) {\n        r = (u[i - 1] + 2 * u[i] + u[i + 1]) / 4;\n    }\n    v[i] = r;\n}\n\nvoid main() {\n    I64[5] a = [0, 0, 64, 0, 0];\n    I64[5] b;\n    for step in 0..2 {\n        smooth(a, b);\n        smooth(b, a);\n    }\n    for i in 0..5 {\n        \"{a[i]} \";\n    }\n    \"\\n\";\n}\n```\n\n```text\n0 12 17 12 0 \n```\n\n12. A dispatch has no value:\n\n```cint dispatch_try.ci\nkernel copy1[n](in I64[n] a, out I64[n] b) over [i: n] {\n    b[i] = a[i];\n}\n\nvoid main() {\n    I64[3] a;\n    I64[3] b;\n    try copy1(a, b);\n}\n```\n\n```text\nerror[C2043]: type rule\n  --> dispatch_try.ci:8:5\n   |\n 8 |     try copy1(a, b);\n   |     ^\n```\n\n**Notes**\n\n13. A view of an output formed before a dispatch reads the published elements after it, as every view of the same storage does (6.12.4):\n\n```cint dispatch_view.ci\nkernel inc[n](in I64[n] a, out I64[n] b) over [i: n] {\n    b[i] = a[i] + 1;\n}\n\nvoid main() {\n    I64[3] a = [10, 20, 30];\n    I64[3] b;\n    in I64[_] head = b[0..2];\n    inc(a, b);\n    \"{head[0]} {head[1]}\\n\";\n}\n```\n\n```text\n11 21\n```"
  },
  {
   "id": "spec-04p:reductions-in-kernels",
   "edition": "SPEC-04P.2",
   "title": "6.13.5 Reductions in kernels",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#reductions-in-kernels",
   "internal": 0,
   "content": "#### 6.13.5 Reductions in kernels\n\nA reduction combines one value from each work-item into one scalar result: a sum, a count, a minimum or a maximum. It is written as a `reduce` statement whose target is a scalar `out` parameter. Contributions are combined in ascending work-item index, so a reduction whose result depends on order, such as a checked fold, has one result whatever order the work-items ran in.\n\n**Syntax**\n\n```ebnf\nreduce_stmt = \"reduce\" IDENT \"=\" reduction \";\" ;\nreduction   = ( \"sum\" | \"sum_wrap\" | \"sum_sat\" | \"min\" | \"max\" | \"count\" ) \"(\" expr \")\"\n            | \"fold_checked\" \"(\" \"add\" \",\" expr \",\" expr \")\" ;\n```\n\n**Constraints**"
  },
  {
   "id": "spec-04p:reductions-in-kernels-p1",
   "edition": "SPEC-04P.2",
   "title": "6.13.5 Reductions in kernels (part 2)",
   "clauses": "LS-249 R-1",
   "url": "/specifications/spec-04p/2/#reductions-in-kernels",
   "internal": 0,
   "content": "1. <a id=\"R-1\"></a>A `reduce` statement appears only in a kernel body, and its target is a scalar `out` parameter. A `reduce` statement outside a kernel body, or with another target, such as a local variable, is diagnosed C9102 [R-1].\n2. <a id=\"LS-249\"></a>Each scalar `out` parameter is the target of exactly one `reduce` statement. A `reduce` statement is not inside a loop; it may be inside an `if`. A scalar `out` parameter that is the target of no `reduce` statement, a second `reduce` statement to one target, and a `reduce` statement inside a loop are diagnosed C9102 [R-1, LS-249].\n3. The contribution of `sum(e)` has an integer type, and the target has an integer type. In `fold_checked(add, init, e)`, `e` and `init` have exactly the target's type, and `init` is the same for every work-item. The contribution of `sum_wrap`, `sum_sat`, `min` and `max` has exactly the target's type. The contribution of `count(c)` is a `Bool`, and the target is an `I64`. Another type is diagnosed C2001; a conversion of the contribution, as in `fold_checked(add, 0, x[i] as I64)`, gives it the target's type [LS-249].\n4. For fixed-point contributions, the target of `sum` has the type of the contributions, as 7.3 states for `sum(R, xs)`. A target of another type is diagnosed C9102.\n\n**Semantics**"
  },
  {
   "id": "spec-04p:reductions-in-kernels-p2",
   "edition": "SPEC-04P.2",
   "title": "6.13.5 Reductions in kernels (part 3)",
   "clauses": "LS-249 R-1 R-2 R-3",
   "url": "/specifications/spec-04p/2/#reductions-in-kernels",
   "internal": 0,
   "content": "5. A work-item that executes the `reduce` statement contributes the value of its expression; a work-item that does not execute it contributes nothing. Each work-item contributes at most once to each target [R-1].\n6. <a id=\"R-2\"></a>The *logical order* of contributions is ascending work-item index [R-2].\n7. Each form is the operation of 7.3 applied to the contributions in logical order, with the target's type as the result type [LS-249]:\n   - `sum(e)`: the exact sum, checked once against the target's range after the last contribution;\n   - `fold_checked(add, init, e)`: `init`, then each contribution added in logical order with a checked `+` in the target's type;\n   - `sum_wrap(e)`: the exact sum reduced modulo 2^`w` into the target's range, which is the same as adding with `+%` in any order;\n   - `sum_sat(e)`: `init` 0, then each contribution added in logical order with `+|`;\n   - `min(e)`, `max(e)`: the least or greatest contribution;\n   - `count(c)`: the number of contributions that are `true`.\n8. <a id=\"R-3\"></a>With no contributions, `sum`, `sum_wrap`, `sum_sat` and `count` give 0 and `fold_checked` gives `init`; `min` and `max` fault [R-3, LS-249].\n9. The target receives its result when the dispatch publishes its outputs (6.13.4), and not if the dispatch faults.\n10. On fixed-point contributions, each form acts on the storage integers and nothing rounds, as 7.3 states.\n\n**Faults**"
  },
  {
   "id": "spec-04p:reductions-in-kernels-p3",
   "edition": "SPEC-04P.2",
   "title": "6.13.5 Reductions in kernels (part 4)",
   "clauses": "LS-249 R-6 R-7",
   "url": "/specifications/spec-04p/2/#reductions-in-kernels",
   "internal": 0,
   "content": "11. <a id=\"R-6\"></a>The fault `E_OVERFLOW` is raised by `fold_checked` at the first contribution `k` in logical order whose partial result leaves the target's range. The fault is attributed to work-item `k`, at the step of its `reduce` statement. The fault record holds the operation identifier `fold_checked.add.t`, where `t` is the target type in lower case; three operands, the index `k` as an `I64`, the accumulator before `k` and the contribution; the exact result; and the bound it crossed as the limit [R-6, LS-249].\n12. <a id=\"R-7\"></a>The fault `E_OVERFLOW` is raised by `sum` when the exact sum is outside the target's range. The fault is in the *epilogue* of the dispatch, after every work-item. The record holds the operation identifier `sum.checked.e.r`, where `e` is the contribution type and `r` the target type; one operand, the number of contributions as an `I64`; the exact sum; and the bound it crossed as the limit [LS-249, R-7].\n13. The fault `E_SHAPE` is raised in the epilogue by `min` or `max` with no contributions. The record holds the operation identifier `reduce_min.checked.t` or `reduce_max.checked.t` and one operand, `I64 0` [LS-249, R-7].\n14. Epilogue faults occur only when no work-item faulted. Among themselves they are ordered by the declaration order of their targets [R-7].\n\n**Examples**\n\n15. This example shows six reductions over one input:\n\n```cint reduce_forms.ci\nkernel stats[n](in I32[n] x, out I64 total, out I32 lo, out I32 hi, out I64 negatives,\n                out I32 wrapped, out I8 clamped) over [i: n] {\n    reduce total = sum(x[i]);\n    reduce lo = min(x[i]);\n    reduce hi = max(x[i]);\n    reduce negatives = count(x[i] < 0);\n    reduce wrapped = sum_wrap(x[i]);\n    reduce clamped = sum_sat((x[i] / 1000000000) as I8);\n}"
  },
  {
   "id": "spec-04p:reductions-in-kernels-p4",
   "edition": "SPEC-04P.2",
   "title": "6.13.5 Reductions in kernels (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#reductions-in-kernels",
   "internal": 0,
   "content": "void main() {\n    I32[4] x = [2147483647, 5, -7, 2147483647];\n    I64 total = 0;\n    I32 lo = 0;\n    I32 hi = 0;\n    I64 negatives = 0;\n    I32 wrapped = 0;\n    I8 clamped = 0;\n    stats(x, total, lo, hi, negatives, wrapped, clamped);\n    \"{total} {lo} {hi} {negatives} {wrapped} {clamped}\\n\";\n}\n```\n\n```text\n4294967292 -7 2147483647 1 -4 3\n```\n\n`total` holds the exact sum in an `I64`; `wrapped` holds the same sum reduced into `I32`. `clamped` adds the quotients 2, 0, -1 and 2, since integer `/` is floor division (6.7.7).\n\n16. `sum_sat` depends on the order of its contributions, which is the work-item order. The two inputs hold the same values in different orders:\n\n```cint reduce_sat_order.ci\nkernel total_sat[n](in I8[n] x, out I8 s) over [i: n] {\n    reduce s = sum_sat(x[i]);\n}\n\nvoid main() {\n    I8[3] p = [120, 120, -120];\n    I8[3] q = [120, -120, 120];\n    I8 s1 = 0;\n    I8 s2 = 0;\n    total_sat(p, s1);\n    total_sat(q, s2);\n    \"{s1} {s2}\\n\";\n}\n```\n\n```text\n7 120\n```\n\nIn the first order, 120 + 120 saturates to 127, and 127 - 120 is 7.\n\n17. This example shows a contribution under `if`, and reductions with no contributions:\n\n```cint reduce_empty.ci\nkernel positive_sum[n](in I64[n] x, out I64 s) over [i: n] {\n    if (x[i] > 0) {\n        reduce s = sum(x[i]);\n    }\n}\n\nkernel summary[n](in I64[n] x, out I64 s, out I64 c, out I64 f) over [i: n] {\n    reduce s = sum(x[i]);\n    reduce c = count(x[i] > 0);\n    reduce f = fold_checked(add, 7, x[i]);\n}\n\nvoid main() {\n    I64[4] x = [3, -1, 4, -1];\n    I64 p = 0;\n    positive_sum(x, p);\n    I64[0] none;\n    I64 s = 5;\n    I64 c = 5;\n    I64 f = 5;\n    summary(none, s, c, f);\n    \"{p} {s} {c} {f}\\n\";\n}\n```\n\n```text\n7 0 0 7\n```\n\n18. A fixed-point sum adds the stored integers, with no rounding:\n\n```cint reduce_fixed.ci\nkernel total_q[n](in Q16.16[n] a, out Q16.16 t) over [i: n] {\n    reduce t = sum(a[i]);\n}"
  },
  {
   "id": "spec-04p:reductions-in-kernels-p5",
   "edition": "SPEC-04P.2",
   "title": "6.13.5 Reductions in kernels (part 6)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#reductions-in-kernels",
   "internal": 0,
   "content": "void main() {\n    Q16.16[3] a = [1.5, 3.0, 0.25];\n    Q16.16 t = 0.0;\n    total_q(a, t);\n    \"{t}\\n\";\n}\n```\n\n```text\n4.75\n```\n\n19. This example shows a checked fold. The partial sum after work-item 0 is `I64.max`, and work-item 1 adds 1:\n\n```cint kernel_fold.ci\nkernel total_checked[n](in I64[n] x, out I64 s) over [i: n] {\n    reduce s = fold_checked(add, 0, x[i]);\n}\n\nvoid main() {\n    I64[3] x = [9223372036854775807, 1, -1];\n    I64 s = 0;\n    total_checked(x, s);\n    \"{s}\\n\";\n}\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> kernel_fold.ci:2:16\n   |\n 2 |     reduce s = fold_checked(add, 0, x[i]);\n   |                ^ fold_checked.add.i64\n   |\n   = operation: fold_checked.add.i64\n   = operand-count: 3\n   = operand: I64 1\n   = operand: I64 9223372036854775807\n   = operand: I64 1\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n   ...\n   = address: kernel_fold.total_checked, dispatch 0, phase 1, work-item 1, step 1\n   ...\n```\n\n`sum` over the same input gives `I64.max`: the exact sum is in range, so the overflow of the partial sum does not matter.\n\n20. This example shows a sum checked in the epilogue. The first dispatch's exact sum, 2147483647, fits `I32`; the second's, 2147483648, does not:\n\n```cint kernel_epilogue.ci\nkernel total[n](in I32[n] x, out I32 s) over [i: n] {\n    reduce s = sum(x[i]);\n}\n\nvoid main() {\n    I32[3] x = [2147483647, 1, -1];\n    I32[2] y = [2147483647, 1];\n    I32 s = 0;\n    total(x, s);\n    \"{s}\\n\";\n    total(y, s);\n    \"{s}\\n\";\n}\n```"
  },
  {
   "id": "spec-04p:reductions-in-kernels-p6",
   "edition": "SPEC-04P.2",
   "title": "6.13.5 Reductions in kernels (part 7)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#reductions-in-kernels",
   "internal": 0,
   "content": "```text\n2147483647\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> kernel_epilogue.ci:2:16\n   |\n 2 |     reduce s = sum(x[i]);\n   |                ^ sum.checked.i32.i32\n   |\n   = operation: sum.checked.i32.i32\n   = operand-count: 1\n   = operand: I64 2\n   = exact:   2147483648\n   = limit:   I32 2147483647\n   ...\n   = address: kernel_epilogue.total, dispatch 1, phase 2, work-item none, step none\n   ...\n```\n\nThe address names dispatch 1, the second dispatch of the entry and phase 2, the epilogue.\n\n**Notes**\n\n21. The accumulator that `sum` uses, and the bound that makes its exact sum always representable, are in 7.3."
  },
  {
   "id": "spec-04p:meaning-of-a-dispatch",
   "edition": "SPEC-04P.2",
   "title": "6.13.6 Meaning of a dispatch",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#meaning-of-a-dispatch",
   "internal": 0,
   "content": "#### 6.13.6 Meaning of a dispatch\n\nThe meaning of a dispatch is defined by a sequential procedure: check the arguments, run the work-items one at a time in ascending index, combine the reductions, publish. Every executor gives the outcome of this procedure, including on a GPU, where many work-items run at once and several may fault: the fault reported is always the one the procedure reaches first.\n\n**Semantics**"
  },
  {
   "id": "spec-04p:meaning-of-a-dispatch-p1",
   "edition": "SPEC-04P.2",
   "title": "6.13.6 Meaning of a dispatch (part 2)",
   "clauses": "LS-287 LS-288 R-8",
   "url": "/specifications/spec-04p/2/#meaning-of-a-dispatch",
   "internal": 0,
   "content": "1. <a id=\"X-1\"></a>A dispatch of `N` work-items means the following procedure [X-1]:\n   1. Run the entry checks of 6.13.2, then charge the dispatch's fuel (paragraph 7). If one fails, that fault is the dispatch's fault; stop.\n   2. For each work-item index `i` from 0 to `N - 1`, run the body as an independent sequential program, with the over variables set to the index tuple of `i`, fresh local variables, fuel charged to the entry, every read of an `in` or `inout` argument giving its value from before the dispatch, every write to an `out` or `inout` argument going to work-item `i`'s owned block in staging, and each `reduce` statement contributing to its reduction. If a work-item faults, that fault is the dispatch's fault; stop.\n   3. Complete the reductions and check their results (6.13.5). If one faults, that fault is the dispatch's fault; stop.\n   4. Publish the outputs (6.13.4).\n2. <a id=\"X-2\"></a>A work-item reads only values from before the dispatch and its own local state, and writes only its own owned blocks in staging. Contributions to reductions and charges of fuel are combined only by the rules of 6.13.5 and paragraph 7. Every order of running the work-items, including running them at the same time, therefore gives the same outputs and the same fault [X-2].\n3. <a id=\"LS-287\"></a>A dispatch has three *phases*: entry (0), work-items (1) and epilogue (2). When more than one fault could occur, the fault of the dispatch is the least by phase, then by work-item index, then by step ordinal. It is the fault the procedure of paragraph 1 reaches first, whichever fault an executor's hardware met first in time [LS-287].\n4. <a id=\"R-8\"></a>If the fault of a dispatch is at work-item `k`, every work-item with a lower index completed without a fault [R-8].\n5. The record of a fault in a dispatch holds, beyond the fields of every fault record (8.1), the *address* of the fault"
  },
  {
   "id": "spec-04p:meaning-of-a-dispatch-p2",
   "edition": "SPEC-04P.2",
   "title": "6.13.6 Meaning of a dispatch (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#meaning-of-a-dispatch",
   "internal": 0,
   "content": "**Examples**\n\n8. Two work-items overflow, at indices 2 and 4. The fault reported is at work-item 2, whichever an executor reached first:\n\n```cint kernel_lowest.ci\nkernel square[n](in I32[n] x, out I32[n] y) over [i: n] {\n    y[i] = x[i] * x[i];\n}\n\nvoid main() {\n    I32[6] x = [1, 2, 50000, 3, 46341, 4];\n    I32[6] y;\n    square(x, y);\n    \"{y[0]}\\n\";\n}\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> kernel_lowest.ci:2:17\n   |\n 2 |     y[i] = x[i] * x[i];\n   |                 ^ mul.checked.i32\n   |\n   = operation: mul.checked.i32\n   = operand-count: 2\n   = operand: I32 50000\n   = operand: I32 50000\n   = exact:   2500000000\n   = limit:   I32 2147483647\n   ...\n   = address: kernel_lowest.square, dispatch 0, phase 1, work-item 2, step 3\n   = stack-depth: 1\n   = called from: kernel_lowest.ci:8:5\n   = fuel-consumed: 7 (not part of the fault record)\n   ...\n```\n\nThe step ordinal counts the place `y[i]` as step 0, the two reads of `x[i]` as steps 1 and 2, and the product as step 3. The fuel consumed is 1 for the call of `main` and 6 for the dispatch of six work-items; the body has no loop or call.\n\n**Notes**\n\n9. No output of the faulted dispatch in this example is published: `y` holds what it held before. A host program that runs the entry, or a checkpoint taken after it, observes `y` unchanged (SPEC-03P.1, 8.4)."
  },
  {
   "id": "spec-04p:arenas-pools-and-handles",
   "edition": "SPEC-04P.2",
   "title": "6.14 Arenas, pools and handles",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#arenas-pools-and-handles",
   "internal": 0,
   "content": "### 6.14 Arenas, pools and handles\n\nAn arena and a pool are storage that a program declares once, at module level, with a fixed capacity, and then reuses. An arena hands out runs of elements one after another and takes them all back at once with `reset`. A pool holds single elements in slots, taken with `insert` and given back one at a time with `remove`. The program refers to what it was given through a *handle*. Every use of a handle is checked: a handle whose storage was given back, or that belongs to another arena or pool, faults with `E_STALE_HANDLE` instead of reading other data. Storage is returned only by `remove` and `reset`, never by a free of an address, and no handle is a raw address.\n\nThe type forms are in 6.3.8. This section states the declarations (6.14.1), arenas (6.14.2), pools (6.14.3), handles and the stale-handle fault (6.14.4), views of arena storage (6.14.5) and how the frame arena that holds local arrays relates to them (6.14.6)."
  },
  {
   "id": "spec-04p:memory-declarations",
   "edition": "SPEC-04P.2",
   "title": "6.14.1 Declarations",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#memory-declarations",
   "internal": 0,
   "content": "#### 6.14.1 Declarations\n\nAn arena or a pool is declared at the top level of a module with its element type and its capacity. Functions reach it by its name, or through a parameter of type `Arena(T)` or `Pool(T)`. Handles are ordinary values that can be copied and stored.\n\n**Syntax**\n\n```ebnf\nmemory_decl = ( \"Arena\" | \"Pool\" ) \"(\" memory_elem \",\" expr \")\" IDENT \";\" ;\nmemory_type = ( \"Arena\" | \"Pool\" ) \"(\" memory_elem \")\"\n            | \"Handle\" \"(\" memory_elem [ \"[\" [ \"_\" ] \"]\" ] \")\" ;\nmemory_elem = INT_TYPE | \"Bool\" | qualified ;         (* an integer, Bool or struct type *)\n```\n\n`memory_decl` is a top-level declaration (6.9.3). `memory_type` is a type (6.3.8).\n\n**Constraints**"
  },
  {
   "id": "spec-04p:memory-declarations-p1",
   "edition": "SPEC-04P.2",
   "title": "6.14.1 Declarations (part 2)",
   "clauses": "M-19 M-20 M-20a M-20b",
   "url": "/specifications/spec-04p/2/#memory-declarations",
   "internal": 0,
   "content": "1. <a id=\"M-20\"></a>A memory declaration appears at the top level of a module. Inside a function, a test or a block it is diagnosed C4012 at its first token [M-20].\n2. The capacity is a constant expression of type `I64` (6.9.3) whose value is at least 0. A negative capacity is diagnosed C6006 at the capacity [M-20].\n3. The element type `T` of an arena or a pool is an integer type, `Bool` or a struct type [M-19].\n4. <a id=\"M-20b\"></a>A value of type `Arena(T)` or `Pool(T)` is a parameter, or a local variable with an initializer; such a local without an initializer is diagnosed C9102 at its name. It is not stored in a module-level variable, a struct field, an array, an arena or a pool, and it is not returned: each of these is diagnosed C2051 at its type. It is not assigned after its declaration: C2058 at the target of the assignment [M-20b].\n5. The operations that change an arena or a pool, `alloc`, `alloc_result`, `child`, `reset`, `insert`, `insert_result` and `remove`, are applied to a module-level name, a local or an `inout` parameter. Applied to an `in` parameter they are diagnosed C2067 at the receiver, and an assignment through a dereference of an `in` parameter, such as `a[h][0] = 0`, is diagnosed C2060 at its target [M-20b].\n6. <a id=\"M-20a\"></a>A handle has the type that the operation creating it gives: `alloc` gives `Handle(T[])` and `insert` gives `Handle(T)`, where `T` is the element type. A handle of another type where one is required, such as a `Handle(I64[])` given to a pool's `remove`, is diagnosed C2001 at it [M-20a].\n7. Handles, arenas and pools are not compared: `==` and the other comparisons on them are diagnosed C2103 at the left operand [M-20a].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:memory-declarations-p2",
   "edition": "SPEC-04P.2",
   "title": "6.14.1 Declarations (part 3)",
   "clauses": "M-13 M-19 M-20 M-20a M-20b",
   "url": "/specifications/spec-04p/2/#memory-declarations",
   "internal": 0,
   "content": "8. Every arena and pool of a program is created, empty, with the module-level variables (6.9.3), with the element type and the capacity its declaration gives. No arena or pool grows: its storage is fixed by the declarations [M-20, M-19].\n9. In a script, a memory declaration among the top-level statements is still a module-level declaration. The arena or pool exists before the first statement runs and is visible throughout the module, above its declaration as well as below. It is not a local of the script's entry [M-20].\n10. <a id=\"M-13\"></a>Arenas are numbered from 1, and pools are numbered from 1, by separate counters. Module-level arenas and pools are numbered in the order the modules are loaded, the root module first and then the modules it imports, breadth first in import order and within a module in declaration order. A child arena (6.14.2) takes the next arena number when `child` runs. A number is not reused. The number is the *container* recorded in each handle the arena or pool gives [M-13].\n11. A copy of an `Arena(T)` or `Pool(T)` value names the same arena or pool. An `inout Arena(T)` parameter to which a module-level arena is passed allocates from that arena [M-20b].\n12. A handle is an ordinary value. It is copied by assignment, passed in any mode, returned and stored in variables, struct fields and arrays. A `Handle` variable declared without an initializer, and a `Handle` module-level variable or struct field that is given no value, is the *null handle* [M-20a].\n13. The operations of 6.14.2 and 6.14.3 and the checks of handles charge no fuel (5.2.4) [M-20a].\n\n**Examples**\n\n14. This example shows a script whose arena is declared after the statements that use it:\n\n```cint script_arena.ci\nHandle(I64[]) h = scratch.alloc(4);\nfor i in 0..4 {\n    scratch[h][i] = i * i;\n}\n\"{sum(scratch[h])}\\n\";\n\nArena(I64, 8) scratch;\n```\n\n```text\n14\n```"
  },
  {
   "id": "spec-04p:memory-declarations-p3",
   "edition": "SPEC-04P.2",
   "title": "6.14.1 Declarations (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#memory-declarations",
   "internal": 0,
   "content": "15. This example shows an arena declared inside a function:\n\n```cint arena_in_function.ci\nvoid main() {\n    Arena(I64, 8) scratch;\n}\n```\n\n```text\nerror[C4012]: statement form not permitted\n  --> arena_in_function.ci:2:5\n   |\n 2 |     Arena(I64, 8) scratch;\n   |     ^\n```\n\n16. This example shows a reset through an `in` parameter:\n\n```cint arena_in_param.ci\nArena(I64, 16) scratch;\n\nvoid clear(in Arena(I64) a) {\n    a.reset();\n}\n\nvoid main() {\n    clear(scratch);\n}\n```\n\n```text\nerror[C2067]: parameter or argument rule\n  --> arena_in_param.ci:4:5\n   |\n 4 |     a.reset();\n   |     ^\n```\n\n17. Handles kept in a module-level variable and in struct fields. The struct is declared in a program with `void main()` (6.9.6):\n\n```cint handle_fields.ci\nstruct Body {\n    I64 mass;\n    I64 vel;\n}\n\nstruct Link {\n    Handle(Body) from;\n    Handle(Body) to;\n}\n\nconst I64 BODIES = 4;\n\nPool(Body, BODIES) bodies;\nHandle(Body) sun;\n\nvoid main() {\n    sun = bodies.insert(Body(mass = 100, vel = 0));\n    Link l;\n    l.from = sun;\n    l.to = bodies.insert(Body(mass = 3, vel = 2));\n    bodies[l.to].vel += 1;\n    \"{bodies[l.from].mass} {bodies[l.to].vel}\\n\";\n}\n```\n\n```text\n100 3\n```\n\n18. This example shows an array of handles:\n\n```cint handle_array.ci\nPool(I64, 4) counts;\n\nvoid main() {\n    Handle(I64)[3] hs;\n    hs[0] = counts.insert(5);\n    \"{counts[hs[0]]}\\n\";\n}\n```\n\n```text\n5\n```\n\n19. An arena of an unsigned wide type, and a local that names a module-level arena and a pool:\n\n```cint arena_u128.ci\nArena(U128, 2) ids;\n\nvoid main() {\n    Handle(U128[]) k = ids.alloc(1);\n    \"{ids[k][0]}\\n\";\n}\n```\n\n```text\n0\n```\n\n```cint arena_local_name.ci\nArena(I64, 8) scratch;\nPool(I64, 2) counts;\n\nvoid main() {\n    Arena(I64) s = scratch;\n    Pool(I64) p = counts;\n    Handle(I64[]) h = s.alloc(2);\n    scratch[h][1] = 4;\n    Handle(I64) k = p.insert(3);\n    \"{s[h][1]} {counts[k]}\\n\";\n}\n```\n\n```text\n4 3\n```"
  },
  {
   "id": "spec-04p:memory-declarations-p4",
   "edition": "SPEC-04P.2",
   "title": "6.14.1 Declarations (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#memory-declarations",
   "internal": 0,
   "content": "**Notes**\n\n20. An arena holds one element type. Data of several types that is allocated together goes in a struct element, as in 6.14.2, or in several arenas."
  },
  {
   "id": "spec-04p:arenas",
   "edition": "SPEC-04P.2",
   "title": "6.14.2 Arenas",
   "clauses": "M-19",
   "url": "/specifications/spec-04p/2/#arenas",
   "internal": 0,
   "content": "#### 6.14.2 Arenas\n\nAn arena hands out runs of consecutive elements, each run after the last, and takes them all back at once with `reset`. A run is reached through its handle, as a view of rank 1. A *child* arena is carved out of a parent for allocations that end sooner than the parent's.\n\n**Syntax**\n\n```ebnf\ncall = IDENT [ \".\" IDENT ] \"(\" [ args ] \")\" ;\n```\n\nAn arena operation is a `call` `a.alloc(n)`, `a.alloc_result(n)`, `a.child(n)` or `a.reset()`, where the name `a` denotes an arena (6.7.4). The dereference `a[h]` is an index expression (6.12.2) whose index is a handle.\n\n**Constraints**\n\n1. <a id=\"M-19\"></a>The argument of `alloc`, `alloc_result` and `child` has type `I64`; another type is diagnosed C2001 [M-19].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:arenas-p1",
   "edition": "SPEC-04P.2",
   "title": "6.14.2 Arenas (part 2)",
   "clauses": "M-13 M-14 M-14a M-19 M-20 M-20a",
   "url": "/specifications/spec-04p/2/#arenas",
   "internal": 0,
   "content": "2. <a id=\"M-14\"></a>An arena of capacity `c` has a *used extent* `u` and a *generation* `g`, both 0 when it is created. Its storage is `c` elements, numbered from 0 [M-14, M-19].\n3. `a.alloc(n)`, for `0 <= n` and `u + n <= c`, gives the run of elements `u` to `u + n - 1`, sets each of them to 0 (every field to 0 for a struct element), and increases `u` by `n`. It returns a handle with slot `u` (the used extent before the allocation), length `n`, generation `g`, the arena's number and kind 1 (6.14.4). `alloc(0)` gives a handle of length 0. An allocation does not move an earlier one [M-14, M-19].\n4. `a.alloc_result(n)` is the result form (3.8) of `alloc`, of type `AllocError!Handle(T[])`. Where `u + n` exceeds `c` for a count `n` of at least 0, it changes nothing and returns `AllocError.full`, the one value of the built-in error set `AllocError` (6.3.7), whose tag is `U16 1`. A negative count faults as for `alloc` [M-19].\n5. <a id=\"M-14a\"></a>`a[h]`, for a handle `h` that is valid in `a` (6.14.4), is the run of `h` as a view of rank 1 whose extent is the handle's length. It has write permission, except where `a` is an `in` parameter, where it has read permission. `a[h][i]` is an element of the run: its index is checked against the run's extent (6.12.2), so no index reaches a neighboring run [M-14a, M-20a].\n6. `a.reset()` increases `g` by 1 and sets `u` to 0. Every handle given before the reset is stale from then on (6.14.4), and the next allocation starts at element 0 [M-14].\n7. `a.child(c)` charges `c` elements to `a` as `a.alloc(c)` does, and faults as it does. It returns a new arena of type `Arena(T)`: its elements are the charged elements of `a`, its element type is that of `a`, its capacity is `c`, its used extent and its generation are 0, and it takes the next arena number (6.14.1). `child` has no result form [M-20, M-13].\n8. Resetting a child does not change its "
  },
  {
   "id": "spec-04p:arenas-p2",
   "edition": "SPEC-04P.2",
   "title": "6.14.2 Arenas (part 3)",
   "clauses": "M-17a M-19 M-20",
   "url": "/specifications/spec-04p/2/#arenas",
   "internal": 0,
   "content": "**Faults**\n\n9. The fault `E_BOUNDS` is raised by `alloc`, `alloc_result` or `child` with a count below 0, and by `alloc` or `child` with a count `n` for which `u + n` exceeds `c`. The record holds the operation identifier `arena.alloc`; three `I64` operands, the count requested, the used extent `u` and the capacity `c`; and no exact result and no limit. Its position is the member name, `alloc` or `child` [M-19, M-17a].\n10. The fault `E_STALE_HANDLE` is raised by `alloc`, `alloc_result` or `child` on a retired arena, with the operation identifier `arena.alloc`, and by `reset` on a retired arena, with the operation identifier `arena.reset`. The record is that of 6.14.4, paragraph 7, with the reason `retired`, and its handle operands are the arena's own fields: slot 0, the capacity as the length, the arena's generation, its number and kind 1. Its position is the member name [M-17a, M-20].\n\n**Examples**\n\n11. This example shows runs of 3, 2 and 0 elements. Elements not assigned are 0:\n\n```cint arena_alloc.ci\nArena(I64, 16) scratch;\n\nvoid main() {\n    Handle(I64[]) a = scratch.alloc(3);\n    Handle(I64[]) b = scratch.alloc(2);\n    Handle(I64[]) e = scratch.alloc(0);\n    scratch[a][0] = 4;\n    scratch[a][2] = 6;\n    scratch[b][1] = 9;\n    \"{len(scratch[a])} {len(scratch[e])} {sum(scratch[a])} {scratch[a][1]} {scratch[b][0]} {scratch[b][1]}\\n\";\n}\n```\n\n```text\n3 0 10 0 0 9\n```\n\n12. Each call takes the whole arena and resets it before it returns, so the arena does not fill:\n\n```cint arena_reset.ci\nArena(I64, 4) scratch;\n\nI64 step(I64 k) {\n    Handle(I64[]) h = scratch.alloc(4);\n    for i in 0..4 {\n        scratch[h][i] = k + i;\n    }\n    I64 t = sum(scratch[h]);\n    scratch.reset();\n    return t;\n}\n\nvoid main() {\n    I64 a = step(0);\n    I64 b = step(10);\n    I64 c = step(100);\n    \"{a} {b} {c}\\n\";\n}\n```\n\n```text\n6 46 406\n```"
  },
  {
   "id": "spec-04p:arenas-p3",
   "edition": "SPEC-04P.2",
   "title": "6.14.2 Arenas (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#arenas",
   "internal": 0,
   "content": "13. The result form reports a full arena as an error, which the caller handles with `catch` (6.11). The second call needs 4 elements where 2 are left:\n\n```cint arena_alloc_result.ci\nArena(I64, 6) scratch;\n\nAllocError!I64 ones(I64 n) {\n    Handle(I64[]) h = try scratch.alloc_result(n);\n    for i in 0..n {\n        scratch[h][i] = 1;\n    }\n    return sum(scratch[h]);\n}\n\nvoid main() {\n    I64 a = ones(4) catch -1;\n    I64 b = ones(4) catch -1;\n    I64 c = ones(2) catch -1;\n    \"{a} {b} {c}\\n\";\n}\n```\n\n```text\n4 -1 2\n```\n\n14. The faulting form stops the program, and the record gives the numbers:\n\n```cint arena_full.ci\nArena(I64, 8) scratch;\n\nvoid main() {\n    Handle(I64[]) a = scratch.alloc(5);\n    Handle(I64[]) b = scratch.alloc(4);\n}\n```\n\n```text\nfault[E_BOUNDS]: index out of bounds\n  --> arena_full.ci:5:31\n   |\n 5 |     Handle(I64[]) b = scratch.alloc(4);\n   |                               ^ arena.alloc\n   |\n   = operation: arena.alloc\n   = operand-count: 3\n   = operand: I64 4\n   = operand: I64 5\n   = operand: I64 8\n   = exact:   none\n   = limit:   none\n   ...\n```\n\n15. A child arena of 3 elements is charged to its parent between `a` and `b`. Resetting the child gives its elements back to the child, not to the parent, so the parent is full after `c`:\n\n```cint arena_child.ci\nArena(I64, 8) scratch;\n\nvoid main() {\n    Handle(I64[]) a = scratch.alloc(2);\n    Arena(I64) part = scratch.child(3);\n    Handle(I64[]) b = scratch.alloc(1);\n    Handle(I64[]) x = part.alloc(3);\n    part[x][2] = 9;\n    part.reset();\n    Handle(I64[]) y = part.alloc(2);\n    \"{part[y][0]} {len(part[y])}\\n\";\n    Handle(I64[]) c = scratch.alloc(2);\n    \"{len(scratch[c])}\\n\";\n    Handle(I64[]) d = scratch.alloc(1);\n}\n```"
  },
  {
   "id": "spec-04p:arenas-p4",
   "edition": "SPEC-04P.2",
   "title": "6.14.2 Arenas (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#arenas",
   "internal": 0,
   "content": "```text\n0 2\n2\nfault[E_BOUNDS]: index out of bounds\n  --> arena_child.ci:14:31\n   |\n14 |     Handle(I64[]) d = scratch.alloc(1);\n   |                               ^ arena.alloc\n   |\n   = operation: arena.alloc\n   = operand-count: 3\n   = operand: I64 1\n   = operand: I64 8\n   = operand: I64 8\n   ...\n```\n\n16. This example shows an arena of struct elements. Its capacity and its used extent count elements, not bytes:\n\n```cint arena_struct.ci\nstruct Body {\n    I64 mass;\n    I64 vel;\n}\n\nArena(Body, 3) scratch;\n\nvoid main() {\n    Handle(Body[]) two = scratch.alloc(2);\n    Handle(Body[]) one = scratch.alloc(1);\n    scratch[two][1].mass = 11;\n    scratch[one][0] = Body(mass = 2, vel = 4);\n    \"{scratch[two][1].mass} {scratch[one][0].vel} {scratch[two][0].mass}\\n\";\n}\n```\n\n```text\n11 4 0\n```\n\n17. This example shows an allocation from a retired arena. The handle operands are the child's own fields: slot 0, its capacity 4, generation 0, arena number 2 and kind 1; the reason is 2, `retired`:\n\n```cint arena_retired.ci\nArena(I64, 8) scratch;\n\nvoid main() {\n    Arena(I64) part = scratch.child(4);\n    scratch.reset();\n    Handle(I64[]) u = part.alloc(1);\n}\n```\n\n```text\nfault[E_STALE_HANDLE]: stale handle\n  --> arena_retired.ci:6:28\n   |\n 6 |     Handle(I64[]) u = part.alloc(1);\n   |                            ^ arena.alloc\n   |\n   = operation: arena.alloc\n   = operand-count: 7\n   = operand: U64 0\n   = operand: I64 4\n   = operand: U64 0\n   = operand: U32 2\n   = operand: U8 1\n   = operand: U64 0\n   = operand: U8 2\n   ...\n```\n\n**Notes**\n\n18. An arena has no partial reset. Allocations that end sooner than the rest are taken from a child arena, and the child is reset.\n19. At one reset every microsecond, the generation of paragraph 6 reaches 2^64 - 1 after about 584,500 years."
  },
  {
   "id": "spec-04p:pools",
   "edition": "SPEC-04P.2",
   "title": "6.14.3 Pools",
   "clauses": "M-20a",
   "url": "/specifications/spec-04p/2/#pools",
   "internal": 0,
   "content": "#### 6.14.3 Pools\n\nA pool holds up to its capacity of single elements, each in a *slot*. `insert` stores a value in a free slot and returns a handle to it; `remove` frees the slot. A freed slot is used again, and from then on the handle to its old contents is stale.\n\n**Syntax**\n\n```ebnf\ncall = IDENT [ \".\" IDENT ] \"(\" [ args ] \")\" ;\n```\n\nA pool operation is a `call` `p.insert(v)`, `p.insert_result(v)` or `p.remove(h)`, where the name `p` denotes a pool (6.7.4). The dereference `p[h]` is an index expression (6.12.2) whose index is a handle.\n\n**Constraints**\n\n1. The argument of `insert` and `insert_result` has the element type `T` of the pool, and that of `remove` has type `Handle(T)`. Another type is diagnosed C2001 [M-20a].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:pools-p1",
   "edition": "SPEC-04P.2",
   "title": "6.14.3 Pools (part 2)",
   "clauses": "M-12 M-15 M-16 M-17a M-18 M-19 M-20a",
   "url": "/specifications/spec-04p/2/#pools",
   "internal": 0,
   "content": "2. <a id=\"M-15\"></a>A pool of capacity `c` has the slots 0 to `c - 1`. Each slot is *vacant*, *occupied* or *retired*, and has a generation, a `U64` that starts at 0. In a new pool every slot is vacant [M-15].\n3. <a id=\"M-18\"></a>`p.insert(v)` stores `v` in a vacant slot, marks the slot occupied and returns a handle with the slot's index, length 1, the slot's generation, the pool's number and kind 2 (6.14.4). The slot is the one most recently vacated by `remove` and not taken since; when there is none, it is the vacant slot of lowest index. The handles a program obtains are therefore fixed by its sequence of operations [M-18, M-12].\n4. `p.insert_result(v)` is the result form (3.8) of `insert`, of type `AllocError!Handle(T)`. When the pool is full it changes nothing and returns `AllocError.full` (6.14.2) [M-19].\n5. A pool is *full* when every slot is occupied or retired [M-19].\n6. `p[h]`, for a handle `h` that is valid in `p` (6.14.4), is the slot's element as a place. It can be read, assigned whole, or have a field read or assigned, as in `bodies[h].mass += 5` [M-20a].\n7. <a id=\"M-17a\"></a>`p.remove(h)` checks `h` as `p[h]` does. It then marks the slot vacant and increases its generation by 1, so `h` and every copy of it are stale from then on [M-15, M-17a].\n8. <a id=\"M-16\"></a>A generation does not wrap. A `remove` that would set a slot's generation to 2^64 - 1 marks the slot retired instead, and no `insert` takes a retired slot [M-16].\n\n**Faults**"
  },
  {
   "id": "spec-04p:pools-p2",
   "edition": "SPEC-04P.2",
   "title": "6.14.3 Pools (part 3)",
   "clauses": "M-17a M-19",
   "url": "/specifications/spec-04p/2/#pools",
   "internal": 0,
   "content": "9. The fault `E_BOUNDS` is raised by `insert` into a full pool. The record holds the operation identifier `pool.insert`; three `I64` operands, the number of occupied slots, the number of retired slots and the capacity; and no exact result and no limit. Its position is the member name `insert` [M-19, M-17a].\n10. The fault `E_STALE_HANDLE` is raised by `p[h]` and by `remove` with a handle that is not valid in `p`, with the operation identifier `pool.deref` (6.14.4) [M-17a].\n\n**Examples**\n\n11. This example shows two bodies in a pool. A slot is assigned whole, a field is updated in place, and a copy of an element outlives the slot it came from:\n\n```cint pool_basics.ci\nstruct Body {\n    I64 mass;\n    I64 vel;\n}\n\nPool(Body, 4) bodies;\n\nvoid main() {\n    Handle(Body) a = bodies.insert(Body(mass = 7, vel = 1));\n    Handle(Body) b = bodies.insert(Body(mass = 5, vel = 2));\n    bodies[a].vel += bodies[b].vel;\n    bodies[b] = Body(mass = 6, vel = 0);\n    Body saved = bodies[a];\n    bodies.remove(a);\n    \"{saved.mass} {saved.vel} {bodies[b].mass}\\n\";\n}\n```\n\n```text\n7 3 6\n```\n\n12. The most recently freed slot is used first. `x` takes slot 2, freed last, and `y` takes slot 0. After `x` is removed, the record shows its slot 2 at generation 1, where the slot is now at generation 2:\n\n```cint pool_order.ci\nPool(I64, 3) counts;\n\nvoid main() {\n    Handle(I64) a = counts.insert(1);\n    Handle(I64) b = counts.insert(2);\n    Handle(I64) c = counts.insert(3);\n    counts.remove(a);\n    counts.remove(c);\n    Handle(I64) x = counts.insert(4);\n    Handle(I64) y = counts.insert(5);\n    \"{counts[b]} {counts[x]} {counts[y]}\\n\";\n    counts.remove(x);\n    \"{counts[x]}\\n\";\n}\n```"
  },
  {
   "id": "spec-04p:pools-p3",
   "edition": "SPEC-04P.2",
   "title": "6.14.3 Pools (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#pools",
   "internal": 0,
   "content": "```text\n2 4 5\nfault[E_STALE_HANDLE]: stale handle\n  --> pool_order.ci:13:13\n   |\n13 |     \"{counts[x]}\\n\";\n   |             ^ pool.deref\n   |\n   = operation: pool.deref\n   = operand-count: 7\n   = operand: U64 2\n   = operand: I64 1\n   = operand: U64 1\n   = operand: U32 1\n   = operand: U8 2\n   = operand: U64 2\n   = operand: U8 3\n   ...\n```\n\n13. This example shows a full pool. The slot freed by `remove` is used again, and the fourth `insert` finds 2 occupied slots, none retired, in a capacity of 2:\n\n```cint pool_full.ci\nPool(I64, 2) counts;\n\nvoid main() {\n    Handle(I64) a = counts.insert(10);\n    Handle(I64) b = counts.insert(20);\n    counts.remove(a);\n    Handle(I64) c = counts.insert(30);\n    Handle(I64) d = counts.insert(40);\n}\n```\n\n```text\nfault[E_BOUNDS]: index out of bounds\n  --> pool_full.ci:8:28\n   |\n 8 |     Handle(I64) d = counts.insert(40);\n   |                            ^ pool.insert\n   |\n   = operation: pool.insert\n   = operand-count: 3\n   = operand: I64 2\n   = operand: I64 0\n   = operand: I64 2\n   ...\n```\n\n14. This example shows the result form:\n\n```cint pool_insert_result.ci\nPool(I64, 2) counts;\n\nAllocError!I64 keep(I64 v) {\n    Handle(I64) h = try counts.insert_result(v);\n    return counts[h];\n}\n\nvoid main() {\n    I64 a = keep(10) catch -1;\n    I64 b = keep(20) catch -1;\n    I64 c = keep(30) catch -1;\n    \"{a} {b} {c}\\n\";\n}\n```\n\n```text\n10 20 -1\n```\n\n**Notes**\n\n15. A pool of capacity 0 is valid and is always full."
  },
  {
   "id": "spec-04p:handles-and-stale-handles",
   "edition": "SPEC-04P.2",
   "title": "6.14.4 Handles and stale handles",
   "clauses": "M-12",
   "url": "/specifications/spec-04p/2/#handles-and-stale-handles",
   "internal": 0,
   "content": "#### 6.14.4 Handles and stale handles\n\nA handle records where its element or run is, and the generation under which it was given. Each use compares it with the arena or pool it is used in. A handle that no longer matches faults with `E_STALE_HANDLE`, and the record says which check failed.\n\n**Semantics**\n\n1. <a id=\"M-12\"></a>A handle has five fields. Its canonical form is 32 bytes, little-endian, with the fields at these offsets [M-12]:\n\n| Offset | Field | Type | Arena handle | Pool handle |\n| --- | --- | --- | --- | --- |\n| 0 | slot | `U64` | the first element of the run | the slot index |\n| 8 | length | `I64` | the number of elements of the run | 1 |\n| 16 | generation | `U64` | the arena's generation at the allocation | the slot's generation at the insertion |\n| 24 | container | `U32` | the arena's number | the pool's number |\n| 28 | kind | `U8` | 1 | 2 |\n| 29 | reserved | 3 bytes | 0 | 0 |"
  },
  {
   "id": "spec-04p:handles-and-stale-handles-p1",
   "edition": "SPEC-04P.2",
   "title": "6.14.4 Handles and stale handles (part 2)",
   "clauses": "M-12 M-14 M-15 M-17",
   "url": "/specifications/spec-04p/2/#handles-and-stale-handles",
   "internal": 0,
   "content": "2. The *null handle* has every field 0, and it is the only handle of kind 0. A decoder of the canonical form rejects 32 bytes whose reserved bytes are not 0 or whose kind is not 0, 1 or 2 [M-12].\n3. A handle `h` is *valid* in an arena `a` when all of these hold: `a`, and every arena that `a` was carved from, is not retired; `h` has `a`'s number as its container and kind 1; `h`'s generation equals `a`'s generation; `h`'s length is at least 0; and `h`'s slot plus its length, computed without overflow, is at most `a`'s used extent [M-14].\n4. <a id=\"M-17\"></a>A handle `h` is valid in a pool `p` when `h` has `p`'s number as its container and kind 2, its slot is below `p`'s capacity, that slot is occupied, and the slot's generation equals `h`'s generation [M-15, M-17].\n5. Each dereference, `a[h]` or `p[h]` and each `remove`, checks its handle before anything else, and a handle that is not valid faults. Copying, storing, passing and returning a handle does not check it [M-17].\n6. When a handle is not valid for more than one reason, the first reason in this order is reported [M-17]:\n\n| Order | Reason | Code | Condition |\n| --- | --- | --- | --- |\n| 1 | `null` | 1 | the handle is the null handle |\n| 2 | `container` | 6 | the handle's container or kind is not that of the arena or pool it is used in |\n| 3 | `retired` | 2 | the arena, an arena it was carved from, or the pool slot is retired |\n| 4 | `generation` | 3 | the handle's generation differs from the current generation |\n| 5 | `extent` | 4 | in an arena, slot plus length exceeds the used extent; in a pool, the slot is at or above the capacity |\n| 6 | `vacant` | 5 | in a pool, the slot is not occupied |\n\n**Faults**"
  },
  {
   "id": "spec-04p:handles-and-stale-handles-p2",
   "edition": "SPEC-04P.2",
   "title": "6.14.4 Handles and stale handles (part 3)",
   "clauses": "M-17a",
   "url": "/specifications/spec-04p/2/#handles-and-stale-handles",
   "internal": 0,
   "content": "7. The fault `E_STALE_HANDLE` is raised by a dereference or a `remove` whose handle is not valid. The record holds the operation identifier `handle.check` for an arena and `pool.deref` for a pool. It has seven operands: the handle's slot (`U64`), length (`I64`), generation (`U64`), container (`U32`) and kind (`U8`); the current generation as a `U64`, which is the arena's generation, or the generation of the pool's slot when the handle's slot is below the capacity and 0 otherwise; and the reason's code as a `U8`. It has no exact result and no limit. Its position is the `[` of the dereference, or the member name `remove` [M-17a].\n\n**Examples**\n\n8. This example shows a handle used after its slot was freed and filled again. The new element is at slot 0 with generation 1; the old handle has generation 0, so the reason is 3, `generation`:\n\n```cint stale_pool.ci\nstruct Body {\n    I64 mass;\n    I64 vel;\n}\n\nPool(Body, 4) bodies;\n\nvoid main() {\n    Handle(Body) h = bodies.insert(Body(mass = 7, vel = 1));\n    bodies.remove(h);\n    Handle(Body) k = bodies.insert(Body(mass = 9, vel = 0));\n    \"{bodies[k].mass}\\n\";\n    \"{bodies[h].mass}\\n\";\n}\n```\n\n```text\n9\nfault[E_STALE_HANDLE]: stale handle\n  --> stale_pool.ci:13:13\n   |\n13 |     \"{bodies[h].mass}\\n\";\n   |             ^ pool.deref\n   |\n   = operation: pool.deref\n   = operand-count: 7\n   = operand: U64 0\n   = operand: I64 1\n   = operand: U64 0\n   = operand: U32 1\n   = operand: U8 2\n   = operand: U64 1\n   = operand: U8 3\n   ...\n```\n\n9. A handle declared without an initializer is the null handle, reason 1:\n\n```cint stale_null.ci\nPool(I64, 2) counts;\n\nvoid main() {\n    Handle(I64) h;\n    \"{counts[h]}\\n\";\n}\n```"
  },
  {
   "id": "spec-04p:handles-and-stale-handles-p3",
   "edition": "SPEC-04P.2",
   "title": "6.14.4 Handles and stale handles (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#handles-and-stale-handles",
   "internal": 0,
   "content": "```text\nfault[E_STALE_HANDLE]: stale handle\n  --> stale_null.ci:5:13\n   |\n 5 |     \"{counts[h]}\\n\";\n   |             ^ pool.deref\n   |\n   = operation: pool.deref\n   = operand-count: 7\n   = operand: U64 0\n   = operand: I64 0\n   = operand: U64 0\n   = operand: U32 0\n   = operand: U8 0\n   = operand: U64 0\n   = operand: U8 1\n   ...\n```\n\n10. This example shows a handle from pool 2 used in pool 1. Its slot and generation match a live slot of `red`, and the dereference still reads nothing: the reason is 6, `container`:\n\n```cint stale_container.ci\nPool(I64, 2) red;\nPool(I64, 2) blue;\n\nvoid main() {\n    Handle(I64) r = red.insert(1);\n    Handle(I64) b = blue.insert(2);\n    \"{red[b]}\\n\";\n}\n```\n\n```text\nfault[E_STALE_HANDLE]: stale handle\n  --> stale_container.ci:7:10\n   |\n 7 |     \"{red[b]}\\n\";\n   |          ^ pool.deref\n   |\n   = operation: pool.deref\n   = operand-count: 7\n   = operand: U64 0\n   = operand: I64 1\n   = operand: U64 0\n   = operand: U32 2\n   = operand: U8 2\n   = operand: U64 0\n   = operand: U8 6\n   ...\n```\n\n11. This example shows a handle into an arena after a reset. The new run starts at element 0 again and reads 0; the old handle has generation 0 where the arena has generation 1:\n\n```cint stale_arena.ci\nArena(I64, 8) scratch;\n\nvoid main() {\n    Handle(I64[]) tmp = scratch.alloc(4);\n    scratch[tmp][0] = 3;\n    scratch.reset();\n    Handle(I64[]) fresh = scratch.alloc(4);\n    \"{scratch[fresh][0]}\\n\";\n    \"{scratch[tmp][0]}\\n\";\n}\n```\n\n```text\n0\nfault[E_STALE_HANDLE]: stale handle\n  --> stale_arena.ci:9:14\n   |\n 9 |     \"{scratch[tmp][0]}\\n\";\n   |              ^ handle.check\n   |\n   = operation: handle.check\n   = operand-count: 7\n   = operand: U64 0\n   = operand: I64 4\n   = operand: U64 0\n   = operand: U32 1\n   = operand: U8 1\n   = operand: U64 1\n   = operand: U8 3\n   ...\n```"
  },
  {
   "id": "spec-04p:handles-and-stale-handles-p4",
   "edition": "SPEC-04P.2",
   "title": "6.14.4 Handles and stale handles (part 5)",
   "clauses": "M-20b",
   "url": "/specifications/spec-04p/2/#handles-and-stale-handles",
   "internal": 0,
   "content": "12. This example shows a handle into a child arena after the parent's reset. `first` and `scratch` are arenas 1 and 2, so the child is arena 3; the reason is 2, `retired`:\n\n```cint stale_retired.ci\nArena(I64, 8) first;\nArena(I64, 8) scratch;\n\nvoid main() {\n    Arena(I64) part = scratch.child(4);\n    Handle(I64[]) t = part.alloc(2);\n    part[t][0] = 5;\n    scratch.reset();\n    \"{part[t][0]}\\n\";\n}\n```\n\n```text\nfault[E_STALE_HANDLE]: stale handle\n  --> stale_retired.ci:9:11\n   |\n 9 |     \"{part[t][0]}\\n\";\n   |           ^ handle.check\n   |\n   = operation: handle.check\n   = operand-count: 7\n   = operand: U64 0\n   = operand: I64 2\n   = operand: U64 0\n   = operand: U32 3\n   = operand: U8 1\n   = operand: U64 0\n   = operand: U8 2\n   ...\n```\n\n**Notes**\n\n13. A child arena belongs to the block that declares the local naming it. A handle into the child that is kept after the block can be used only through another arena's name, and that use faults with the reason `container` [M-20b]."
  },
  {
   "id": "spec-04p:views-of-arena-storage",
   "edition": "SPEC-04P.2",
   "title": "6.14.5 Views of arena storage",
   "clauses": "M-14a M-17a M-23",
   "url": "/specifications/spec-04p/2/#views-of-arena-storage",
   "internal": 0,
   "content": "#### 6.14.5 Views of arena storage\n\n`a[h]` is a view (6.12.4) of rank 1 over the run of `h`. Such a view remembers the handle it came from, and every access through it checks that handle again, so a reset between the view's creation and its use is caught at the use.\n\n**Semantics**\n\n1. <a id=\"M-23\"></a>A view obtained from `a[h]` records the handle `h`. Each element access through it checks `h` as a dereference does (6.14.4), then checks the index (6.12.2) [M-23].\n2. The check is made whatever runs between the view's creation and its use: a reset in a called function, through a module-level name or through two parameters that name the same arena [M-23].\n3. A view obtained from `a[h]` can initialize a view variable (6.9.1), be indexed, be measured with `len`, be reduced with `sum`, be sliced and be passed as a view argument. A slice of it records the same handle [M-23, M-14a].\n\n**Faults**\n\n4. The fault `E_STALE_HANDLE` is raised by an element access through a view whose handle is not valid. The record is that of 6.14.4, paragraph 7, with the operation identifier `handle.check` and the operands of the handle the view was obtained from. Its position is the `[` of the element access [M-23, M-17a].\n\n**Examples**\n\n5. This example shows a view variable over a run:\n\n```cint arena_view.ci\nArena(I64, 16) scratch;\n\nvoid main() {\n    Handle(I64[]) h = scratch.alloc(3);\n    scratch[h][2] = 5;\n    in I64[_] v = scratch[h];\n    \"{sum(v)} {len(v)} {v[2]}\\n\";\n}\n```\n\n```text\n5 3 5\n```\n\n6. This example shows a reset in a called function, between the view's creation and its use:\n\n```cint arena_view_stale.ci\nArena(I64, 64) scratch;\n\nvoid clear() {\n    scratch.reset();\n}\n\nI64 total_first(Handle(I64[]) h) {\n    inout I64[_] v = scratch[h];\n    I64 t = sum(v);\n    clear();\n    I64 x = v[0];\n    return t + x;\n}"
  },
  {
   "id": "spec-04p:views-of-arena-storage-p1",
   "edition": "SPEC-04P.2",
   "title": "6.14.5 Views of arena storage (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#views-of-arena-storage",
   "internal": 0,
   "content": "void main() {\n    Handle(I64[]) h = scratch.alloc(3);\n    scratch[h][0] = 2;\n    \"{total_first(h)}\\n\";\n}\n```\n\n```text\nfault[E_STALE_HANDLE]: stale handle\n  --> arena_view_stale.ci:11:14\n   |\n11 |     I64 x = v[0];\n   |              ^ handle.check\n   |\n   = operation: handle.check\n   = operand-count: 7\n   = operand: U64 0\n   = operand: I64 3\n   = operand: U64 0\n   = operand: U32 1\n   = operand: U8 1\n   = operand: U64 1\n   = operand: U8 3\n   ...\n```\n\n7. This example shows a run passed to a function's view parameter, and a slice of a run:\n\n```cint arena_view_arg.ci\nArena(I64, 16) scratch;\n\nI64 total(in I64[_] v) {\n    return sum(v);\n}\n\nvoid main() {\n    Handle(I64[]) h = scratch.alloc(3);\n    scratch[h][2] = 5;\n    \"{total(scratch[h])}\\n\";\n}\n```\n\n```text\n5\n```\n\n```cint arena_view_slice.ci\nArena(I64, 16) scratch;\n\nvoid main() {\n    Handle(I64[]) h = scratch.alloc(4);\n    scratch[h][3] = 7;\n    in I64[_] tail = scratch[h][2..4];\n    \"{len(tail)} {tail[1]}\\n\";\n}\n```\n\n```text\n2 7\n```\n\n**Notes**\n\n8. A pool element is reached as the place `p[h]` (6.14.3), not through a view."
  },
  {
   "id": "spec-04p:frame-arena-and-arenas",
   "edition": "SPEC-04P.2",
   "title": "6.14.6 The frame arena and arenas",
   "clauses": "M-22",
   "url": "/specifications/spec-04p/2/#frame-arena-and-arenas",
   "internal": 0,
   "content": "#### 6.14.6 The frame arena and arenas\n\nLocal arrays and arenas are two kinds of storage for runs of elements. A local array lives in the frame arena (5.2.6) and ends with its block. A run taken from an arena lives until the arena is reset, and is reached through a handle that can be returned and stored.\n\n**Semantics**\n\n1. The frame arena holds the local arrays of the running entry (5.2.6). No handle refers to its storage and no arena operation names it: a local array is released when its block exits, and not by `reset`.\n2. When the frame arena is exhausted, the fault is `E_BOUNDS` with the operation identifier `arena.alloc` and the three operands of 6.14.2, paragraph 9, at the declared name of the array (5.2.6).\n3. Storage that is referenced after the call that fills it returns, or across entries, is taken from an arena or a pool, and the program keeps a handle to it. A view of it is formed where it is used [M-22].\n\n**Examples**\n\n4. A function that fills a run and returns its handle, and a function that reads the run through an `in` parameter:\n\n```cint arena_return.ci\nArena(I64, 16) scratch;\n\nHandle(I64[]) count_up(inout Arena(I64) a, I64 n) {\n    Handle(I64[]) h = a.alloc(n);\n    for i in 0..n {\n        a[h][i] = i + 1;\n    }\n    return h;\n}\n\nI64 last(in Arena(I64) a, Handle(I64[]) h) {\n    return a[h][len(a[h]) - 1];\n}\n\nvoid main() {\n    Handle(I64[]) h = count_up(scratch, 4);\n    \"{sum(scratch[h])} {last(scratch, h)}\\n\";\n}\n```\n\n```text\n10 4\n```"
  },
  {
   "id": "spec-04p:modules-programs-and-tests",
   "edition": "SPEC-04P.2",
   "title": "6.15 Modules, programs and tests",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#modules-programs-and-tests",
   "internal": 0,
   "content": "### 6.15 Modules, programs and tests\n\nA program is made of modules. This clause gives how one module uses another, what a module makes visible to the modules that import it, and how a module states tests that `cint test` runs. Scripts, programs with `main` and importable modules are defined in 5.1.2."
  },
  {
   "id": "spec-04p:modules-and-imports",
   "edition": "SPEC-04P.2",
   "title": "6.15.1 Modules and imports",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#modules-and-imports",
   "internal": 0,
   "content": "#### 6.15.1 Modules and imports\n\nEach source file is one module (5.1.1), and its path names it. A module uses another by importing it, and then reaches the other module's exported names through a qualifier. A module is translated from its own source and the exported declarations of the modules it imports: there are no header files, prototypes or include guards.\n\n**Syntax**\n\n```ebnf\nimport_decl = \"import\" module_path\n              [ \"as\" IDENT | \".\" \"{\" IDENT { \",\" IDENT } [ \",\" ] \"}\" ] \";\" ;\nmodule_path = IDENT { \".\" IDENT } ;\ntop_item    = [ \"export\" ] declaration\n            | test_decl\n            | static_assert\n            | statement ;\ndeclaration = const_decl | var_decl | func_decl | kernel_decl\n            | struct_decl | error_decl | memory_decl ;\n```\n\n`module` is in 5.1.1, the declarations in 6.9, 6.13.1 and 6.14.1 and `test_decl` in 6.15.3. A `statement` among the top-level items makes the module a script (5.1.2).\n\n**Constraints**"
  },
  {
   "id": "spec-04p:modules-and-imports-p1",
   "edition": "SPEC-04P.2",
   "title": "6.15.1 Modules and imports (part 2)",
   "clauses": "LS-225 LS-226 LS-227 LS-228 LS-230",
   "url": "/specifications/spec-04p/2/#modules-and-imports",
   "internal": 0,
   "content": "1. <a id=\"LS-225\"></a>A module's path relative to the source root (paragraph 11) names it: each `/` becomes `.` and the final `.ci` is removed, so the file `geo/vec.ci` is the module `geo.vec`. Each segment of the path, the last without `.ci`, shall be an identifier (6.4.4) and shall not be one of the device names `con`, `prn`, `aux`, `nul`, `com1` to `com9` and `lpt1` to `lpt9`, in any mix of upper and lower case. Two module paths of one program shall not be equal when ASCII letters are compared without regard to case. A path that breaks one of these rules is diagnosed C3030 at the start of that file, position `<path>:1:1` [LS-225].\n2. <a id=\"LS-226\"></a>Every `import` declaration shall come before every other item of the module except a profile declaration (5.1.1). An import after another item is diagnosed C3012 at its `import` [LS-226].\n3. The file of each imported module shall be readable under the source root. An import whose module file cannot be read is diagnosed C3009 at its module path [LS-225].\n4. <a id=\"LS-230\"></a>A module shall not import itself, directly or through other modules. The import that closes a cycle is diagnosed C3003 at its module path [LS-230].\n5. <a id=\"LS-228\"></a>Each name in a module is declared once, whatever it names: a type, a function, a constant, a variable, an error set, a kernel, an arena, a pool or an import. A second declaration of a name is diagnosed C3001 at the second declared name. There is no overloading: two functions with the same name and different parameters are two declarations of one name [LS-228].\n6. An import declares one name in the importing module: the last segment of the module path, or the identifier after `as`. A second import that declares the same name, or another declaration of it, is diagnosed C3001, as paragraph 5 states [LS-228].\n7. A selected import, `import a.b.{X, y};`, declares each listed name in th"
  },
  {
   "id": "spec-04p:modules-and-imports-p2",
   "edition": "SPEC-04P.2",
   "title": "6.15.1 Modules and imports (part 3)",
   "clauses": "LS-225 LS-227 LS-228 LS-229",
   "url": "/specifications/spec-04p/2/#modules-and-imports",
   "internal": 0,
   "content": "**Semantics**\n\n11. The *source root* is the directory that module paths are relative to. For `cint run FILE` and `cint test FILE` it is the directory of `FILE`, unless the command names another with `--root` (SPEC-06P.1) [LS-225].\n12. `import a.b;` makes each exported name `n` of the module `a.b` available as `b.n`. `import a.b as v;` makes it available as `v.n`, and `b` then names nothing. `import a.b.{X, y};` makes the listed names available unqualified, and only those names [LS-228].\n13. <a id=\"LS-229\"></a>A module is translated from its own source and the exported declarations of the modules it imports [LS-229].\n14. Each module-level variable is one object of the context (6.9.3), however many modules import its module. An importer reads an exported variable as `m.name` and may assign it, and every module that names the variable reaches the same object [LS-227].\n\n**Examples**\n\n15. This example shows a module and a program that imports it. The program's directory is the source root, and the module `geo.vec` is the file `geo/vec.ci` below it. It exports a struct, a constant and two functions and keeps `helper` private:\n\n```cint geo/vec.ci\nexport struct V2 { I64 x; I64 y; }\n\nexport const I64 UNIT = 1000;\n\nexport I64 dot2(V2 a, V2 b) {\n    return a.x * b.x + a.y * b.y;\n}\n\nexport V2 scaled(V2 a, I64 k) {\n    return V2(a.x * k, a.y * k);\n}\n\nI64 helper() {\n    return 0;\n}\n```\n\nThe program `main.ci` imports it and reaches each exported name through the qualifier `vec`, the last segment of the module path:\n\n```cint main.ci\nimport geo.vec;\n\nvoid main() {\n    vec.V2 a = vec.V2(3, 4);\n    vec.V2 b = vec.scaled(a, 2);\n    \"{vec.dot2(a, b)} {b.x} {vec.UNIT}\\n\";\n}\n```\n\n```console\n$ cint run main.ci\n50 6 1000\n```\n\n16. `as` gives the qualifier another name, and the struct's fields can be named in its constructor:\n\n```cint short.ci\nimport geo.vec as v;"
  },
  {
   "id": "spec-04p:modules-and-imports-p3",
   "edition": "SPEC-04P.2",
   "title": "6.15.1 Modules and imports (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#modules-and-imports",
   "internal": 0,
   "content": "void main() {\n    v.V2 a = v.V2(x = 1, y = 2);\n    \"{v.dot2(a, a)}\\n\";\n}\n```\n\n```console\n$ cint run short.ci\n5\n```\n\n17. A selected import names the listed declarations without a qualifier:\n\n```cint pick.ci\nimport geo.vec.{V2, dot2};\n\nvoid main() {\n    V2 a = V2(3, 4);\n    \"{dot2(a, a)}\\n\";\n}\n```\n\n```text\n25\n```\n\n18. A private name is not visible to an importer:\n\n```cint private.ci\nimport geo.vec;\n\nvoid main() {\n    \"{vec.helper()}\\n\";\n}\n```\n\n```console\n$ cint run private.ci\nerror[C3008]: undefined or unusable name\n  --> private.ci:4:11\n   |\n 4 |     \"{vec.helper()}\\n\";\n   |           ^\n```\n\n19. Imports are not transitive. The module `geo.shape` imports `geo.vec`, and a program that imports only `geo.shape` cannot name `vec`:\n\n```cint geo/shape.ci\nimport geo.vec;\n\nexport I64 square_area(I64 side) {\n    return side * side * vec.UNIT;\n}\n```\n\n```cint reach.ci\nimport geo.shape;\n\nvoid main() {\n    \"{shape.square_area(3)} {vec.UNIT}\\n\";\n}\n```\n\n```console\n$ cint run reach.ci\nerror[C3005]: undefined or unusable name\n  --> reach.ci:4:30\n   |\n 4 |     \"{shape.square_area(3)} {vec.UNIT}\\n\";\n   |                              ^\n```\n\n20. Module state is shared. The module `util.tally` counts calls in an exported variable; the program reads the count, assigns it and calls again:\n\n```cint util/tally.ci\nexport I64 calls = 0;\n\nexport I64 tick() {\n    calls += 1;\n    return calls;\n}\n```\n\n```cint counter.ci\nimport util.tally;\n\nvoid main() {\n    _ = tally.tick();\n    _ = tally.tick();\n    \"{tally.calls}\\n\";\n    tally.calls = 10;\n    \"{tally.tick()}\\n\";\n}\n```\n\n```console\n$ cint run counter.ci\n2\n11\n```\n\n21. Each name is declared once, so a function cannot be overloaded:\n\n```cint overload.ci\nI64 area(I64 side) {\n    return side * side;\n}\n\nI64 area(I64 w, I64 h) {\n    return w * h;\n}\n\nvoid main() {\n    \"{area(3)}\\n\";\n}\n```"
  },
  {
   "id": "spec-04p:modules-and-imports-p4",
   "edition": "SPEC-04P.2",
   "title": "6.15.1 Modules and imports (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#modules-and-imports",
   "internal": 0,
   "content": "```text\nerror[C3001]: duplicate name\n  --> overload.ci:5:5\n   |\n 5 | I64 area(I64 w, I64 h) {\n   |     ^\n```\n\n22. Imports come first:\n\n```cint import_late.ci\nI64 one() {\n    return 1;\n}\n\nimport util.text;\n\nvoid main() {\n    \"{one()}\\n\";\n}\n```\n\n```text\nerror[C3012]: `import` after other items\n  --> import_late.ci:5:1\n   |\n 5 | import util.text;\n   | ^\n```\n\n23. A module that imports itself is the shortest cycle:\n\n```cint cycle.ci\nimport cycle;\n\nexport I64 one() {\n    return 1;\n}\n\nvoid main() {\n    \"{one()}\\n\";\n}\n```\n\n```text\nerror[C3003]: name or module rule\n  --> cycle.ci:1:8\n   |\n 1 | import cycle;\n   |        ^\n```\n\n**Notes**\n\n24. The rules of paragraph 1 make one module path name the same file on every file system, including one that ignores the case of letters or reserves device names.\n25. SPEC-06P.1 describes the options of `cint run`, `cint test` and `cint build`, including programs with several source roots."
  },
  {
   "id": "spec-04p:exports",
   "edition": "SPEC-04P.2",
   "title": "6.15.2 Exports",
   "clauses": "LS-227",
   "url": "/specifications/spec-04p/2/#exports",
   "internal": 0,
   "content": "#### 6.15.2 Exports\n\n`export` before a top-level declaration makes it visible to the modules that import its module. Every other declaration is private to its module. The exported declarations of a module are its interface, and an importer is translated against that interface alone (6.15.1).\n\n**Constraints**\n\n1. <a id=\"LS-227\"></a>`export` is written before a declaration at the top level of a module (6.15.1). Before a test, a statement or a `static_assert` or inside a block, it is a syntax error, C1050 [LS-227].\n\n**Semantics**\n\n2. An exported declaration is visible to every module that imports its module, through the qualifier or the selection of the import (6.15.1). A declaration without `export` is private: it is visible throughout its own module, its tests included (6.15.3) and nowhere else [LS-227].\n3. Exporting a struct exports all its fields. An importer constructs the struct, reads and assigns its fields and passes it as it does a struct of its own [LS-227].\n4. Exporting an error set exports its values. An importer names the set as `m.E`, uses it in a result type such as `m.E!I64`, and writes its values as `.name` where the type is known (6.3.7) [LS-227].\n\n**Examples**\n\n5. The module `util.parse` exports an error set and a function that returns it:\n\n```cint util/parse.ci\nexport error ParseError { empty, bad_digit }\n\nexport ParseError!I64 digit(I64 c) {\n    if (c < 48 || c > 57) {\n        return .bad_digit;\n    }\n    return c - 48;\n}\n```\n\n6. A test is not exported:\n\n```cint export_test.ci\nexport test \"always\" {\n    assert(true);\n}\n\nvoid main() {\n    \"ok\\n\";\n}\n```\n\n```text\nerror[C1050]: syntax error\n  --> export_test.ci:1:8\n   |\n 1 | export test \"always\" {\n   |        ^\n```\n\n**Notes**"
  },
  {
   "id": "spec-04p:exports-p1",
   "edition": "SPEC-04P.2",
   "title": "6.15.2 Exports (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#exports",
   "internal": 0,
   "content": "7. `export` gives no access from a program written in another language. A host program calls the exported functions of a cint library through the host interface, which SPEC-03P.1 defines with the signatures it accepts."
  },
  {
   "id": "spec-04p:tests",
   "edition": "SPEC-04P.2",
   "title": "6.15.3 Tests",
   "clauses": "LS-232 LS-233 LS-236 LS-237",
   "url": "/specifications/spec-04p/2/#tests",
   "internal": 0,
   "content": "#### 6.15.3 Tests\n\nA test is a named block at the top level of a module that checks what the module's code does. `cint test` runs the tests of a program, each in a fresh context, and reports which passed. A test either expects its body to complete or expects one fault, which its header names. 8.3 shows how tests serve as golden outputs.\n\n**Syntax**\n\n```ebnf\ntest_decl = \"test\" STRING [ \"expect_fault\" IDENT [ \"at\" DEC_INT ] ] block ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-232\"></a>A test appears at the top level of a module of any kind: a script, a program with `main` or an importable module. A test inside a function or a block is a syntax error, C1050 [LS-232].\n2. <a id=\"LS-233\"></a>The name of a test is a string literal without holes. A hole in it is diagnosed C1033 [LS-233].\n3. Two tests of one module shall not have the same name. The second is diagnosed C3020 at its `test` [LS-233].\n4. <a id=\"LS-237\"></a>`expect_fault` appears only in a test header. Anywhere else it is diagnosed C3021 at `expect_fault` [LS-237].\n5. <a id=\"LS-236\"></a>The name after `expect_fault` is a fault code of 5.2.3. A name that begins `E_` and is not one is diagnosed C1011 (6.4.4) [LS-236].\n6. A test may name every declaration of its module, private ones included and the exported names of the modules its module imports. It shall not name a top-level variable of a script: C3004 (5.1.2) [LS-232].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:tests-p1",
   "edition": "SPEC-04P.2",
   "title": "6.15.3 Tests (part 2)",
   "clauses": "LS-232 LS-234 LS-235 LS-236 LS-238 LS-239 LS-240 LS-315",
   "url": "/specifications/spec-04p/2/#tests",
   "internal": 0,
   "content": "7. <a id=\"LS-239\"></a>Every translation checks the tests of each module, so `cint run` reports a diagnostic in a test as `cint test` does. Only `cint test` runs tests. It runs no entry of the program: the top-level statements of a script and the function `main` do not run during `cint test`, unless a test calls `main` [LS-232, LS-239].\n8. <a id=\"LS-234\"></a>Each test runs as one entry (3.20) in a fresh context: every module-level variable starts at its initial value and every arena and pool is empty. No test can observe the effects of another [LS-234].\n9. `cint test FILE` runs the tests of every module of the program whose root is `FILE`. It takes the modules in the byte order of their paths relative to the source root, and the tests of each module in source order, so the report is the same on every run [LS-234].\n10. <a id=\"LS-235\"></a>A test without `expect_fault` passes when its body completes, by reaching its end or by `return;`. It fails when an `assert` fails, when any other fault occurs, or when an error leaves it [LS-235].\n11. In a test body, `try` admits an error of any set, and an error that leaves the test through `try` fails it, as 6.11.3 states. The report names the error as `cint run` names an error result of `main` (6.11.7). A test that expects an error binds it with `catch` and checks it with `assert` [LS-315].\n12. A test with `expect_fault E_NAME` passes when its body faults and the fault's code is `E_NAME`. It fails when the body completes, when an error leaves it, or when it faults with another code. The fault ends the test as a fault ends any entry (5.2.3): nothing after it runs, deferred statements do not run, and the test's context is discarded. A fault is not caught or resumed, so a test checks one fault, and several faults take several tests [LS-236].\n13. A failed `assert` is the fault `E_ASSERT` (6.10.9), so `expect_fault E_ASSERT` expects an a"
  },
  {
   "id": "spec-04p:tests-p2",
   "edition": "SPEC-04P.2",
   "title": "6.15.3 Tests (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#tests",
   "internal": 0,
   "content": "**Examples**\n\n16. This example shows four tests of one function. The third expects a fault; the fourth states a wrong value, so its `assert` fails and the report shows both compared values:\n\n```cint arith.ci\nI64 mean(I64 total, I64 n) {\n    return total / n;\n}\n\ntest \"floor division of negatives\" {\n    assert(-7 / 2 == -4);\n    assert(-7 % 2 == 1);\n}\n\ntest \"mean of three\" {\n    assert(mean(9, 3) == 3);\n}\n\ntest \"a zero count faults\" expect_fault E_DIV_ZERO {\n    I64 m = mean(10, 0);\n}\n\ntest \"a wrong expectation fails\" {\n    assert(mean(10, 4) == 3);\n}\n```\n\n```console\n$ cint test arith.ci\ntest arith.ci:5 \"floor division of negatives\" ... ok\ntest arith.ci:10 \"mean of three\" ... ok\ntest arith.ci:14 \"a zero count faults\" ... ok\ntest arith.ci:18 \"a wrong expectation fails\" ... FAILED\nfault[E_ASSERT]: assertion failed\n  --> arith.ci:19:12\n   |\n19 |     assert(mean(10, 4) == 3);\n   |            ^ assert.checked.bool\n   |\n   = operation: assert.checked.bool\n   = operand-count: 2\n   = operand: I64 2\n   = operand: I64 3\n   = exact:   none\n   = limit:   none\n...\n3 of 4 tests passed\n$ echo $?\n3\n```\n\n17. This example shows errors in tests. The first test expects an error and checks which one; the second passes errors on with `try`; in the third an error leaves the test, which fails it:\n\n```cint parse.ci\nerror ParseError { empty, bad_digit }\n\nParseError!I64 digit(I64 c) {\n    if (c < 48 || c > 57) {\n        return .bad_digit;\n    }\n    return c - 48;\n}\n\ntest \"a letter is a bad digit\" {\n    I64 v = digit(65) catch (e) {\n        assert(e == .bad_digit);\n        return;\n    };\n    assert(false);\n}\n\ntest \"two digits parse\" {\n    I64 a = try digit(52);\n    I64 b = try digit(50);\n    assert(a * 10 + b == 42);\n}\n\ntest \"an error fails the test\" {\n    I64 a = try digit(120);\n    assert(a == 0);\n}\n```"
  },
  {
   "id": "spec-04p:tests-p3",
   "edition": "SPEC-04P.2",
   "title": "6.15.3 Tests (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#tests",
   "internal": 0,
   "content": "```console\n$ cint test parse.ci\ntest parse.ci:10 \"a letter is a bad digit\" ... ok\ntest parse.ci:18 \"two digits parse\" ... ok\ntest parse.ci:24 \"an error fails the test\" ... FAILED\nerror: parse.ParseError.bad_digit (tag 2)\n2 of 3 tests passed\n```\n\n18. Each test starts from fresh module state, so both tests pass:\n\n```cint state.ci\nI64 counter = 0;\n\nvoid bump() {\n    counter += 1;\n}\n\ntest \"the first test sees fresh state\" {\n    bump();\n    assert(counter == 1);\n}\n\ntest \"the second test sees fresh state too\" {\n    bump();\n    bump();\n    assert(counter == 2);\n}\n```\n\n```console\n$ cint test state.ci\ntest state.ci:7 \"the first test sees fresh state\" ... ok\ntest state.ci:12 \"the second test sees fresh state too\" ... ok\n2 of 2 tests passed\n```\n\n19. `at` names the line of the faulting operation. Here it is the addition on line 2, inside the function the tests call, so the second test fails:\n\n```cint lines.ci\nI8 inc(I8 a) {\n    return a + 1;\n}\n\ntest \"the fault is at line 2\" expect_fault E_OVERFLOW at 2 {\n    I8 top = inc(127);\n}\n\ntest \"the fault is not at line 6\" expect_fault E_OVERFLOW at 6 {\n    I8 top = inc(127);\n}\n```\n\n```console\n$ cint test lines.ci\ntest lines.ci:5 \"the fault is at line 2\" ... ok\ntest lines.ci:9 \"the fault is not at line 6\" ... FAILED\n  expected fault E_OVERFLOW at line 6\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> lines.ci:2:14\n   |\n 2 |     return a + 1;\n   |              ^ add.checked.i8\n...\n1 of 2 tests passed\n```\n\n20. The top-level statements of a script do not run during `cint test`. This script faults when it runs, and its test passes:\n\n```cint notebook.ci\nI8 level = 127;\nlevel += 1;\n\"not reached\\n\";\n\nI8 half(I8 v) {\n    return v / 2;\n}\n\ntest \"half rounds down\" {\n    assert(half(-7) == -4);\n}\n```"
  },
  {
   "id": "spec-04p:tests-p4",
   "edition": "SPEC-04P.2",
   "title": "6.15.3 Tests (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#tests",
   "internal": 0,
   "content": "```console\n$ cint test notebook.ci\ntest notebook.ci:9 \"half rounds down\" ... ok\n1 of 1 tests passed\n$ cint run notebook.ci\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> notebook.ci:2:7\n   |\n 2 | level += 1;\n   |       ^ add.checked.i8\n...\n```\n\n21. Test names are unique within a module:\n\n```cint test_dup.ci\n\"{twice(5)}\\n\";\n\nI64 twice(I64 x) {\n    return 2 * x;\n}\n\ntest \"twice\" {\n    assert(twice(2) == 4);\n}\n\ntest \"twice\" {\n    assert(twice(-2) == -4);\n}\n```\n\n```text\nerror[C3020]: name or module rule\n  --> test_dup.ci:11:1\n   |\n11 | test \"twice\" {\n   | ^\n```\n\n22. `expect_fault` is not a statement:\n\n```cint test_header.ci\nvoid main() {\n    I8 a = 127;\n    expect_fault E_OVERFLOW;\n    a += 1;\n}\n```\n\n```text\nerror[C3021]: name or module rule\n  --> test_header.ci:3:5\n   |\n 3 |     expect_fault E_OVERFLOW;\n   |     ^\n```\n\n**Notes**\n\n23. `cint test` reports verdicts; it does not show the output a test writes. A test states what it expects with `assert`, which records both compared values when it fails (6.10.9).\n24. 8.3 uses tests as golden outputs, and SPEC-06P.1 gives the options of `cint test`."
  },
  {
   "id": "spec-04p:future-directions",
   "edition": "SPEC-04P.2",
   "title": "6.16 Future directions",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#future-directions",
   "internal": 0,
   "content": "### 6.16 Future directions\n\nThis subclause lists constructs that are not part of this edition. Annex A has no production for them, and an implementation rejects or refuses a program that uses one (A.1, paragraph 4). Listing a construct here does not commit any edition to define it, or to use the spelling shown. Each entry says what a program writes instead in this edition."
  },
  {
   "id": "spec-04p:future-types-and-values",
   "edition": "SPEC-04P.2",
   "title": "6.16.1 Types and values",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#future-types-and-values",
   "internal": 0,
   "content": "#### 6.16.1 Types and values\n\n1. This edition has no string type, whose values a program could store, compare and pass. A string literal is print text or a read-only argument (6.4.8).\n2. This edition has no byte-string literals such as `b\"...\"`, no raw string literals, in which backslashes are not escapes, and no string literals of several lines. A string literal is UTF-8 text on one line, with the escapes of 6.4.8.\n3. This edition has no enumerations. `const` declarations (6.9.2) name the values.\n4. This edition has no tagged unions and no optional values. An error union (6.3.7) carries either a value or an error.\n5. A rounding mode is not a value in this edition, so a program cannot store, pass or compare one. A mode is written as a bare name in a `round` clause or a mode argument (6.7.15).\n6. This edition has no unsigned fixed point, and no fixed-point format whose integer and fraction bits total more than 64 (6.3.2).\n7. This edition has no `U1024`. The widest unsigned type is `U512` (6.3.1).\n8. This edition has no type properties such as `T.bits`, `T.frac_bits`, `T.bytes` and `offset`, no packed structs and no bit fields. The width of each type is fixed by its name (6.3), and the layout of a struct is not observable from a program.\n9. This edition has no error sets with a signed underlying type, no error-set variables at module level and no conversion of an error value to its integer tag (6.3.7, 6.9.7).\n10. A constant has a scalar type in this edition (6.9.2), so a constant array such as `const I32[4] PRIMES = [2, 3, 5, 7];` cannot be declared.\n11. A program cannot declare a function or a type with a type parameter. The operations of clause 7 accept several types, and `Arena(T)`, `Pool(T)` and `Handle(T[])` (6.3.8) are the only types with a parameter."
  },
  {
   "id": "spec-04p:future-declarations-and-statements",
   "edition": "SPEC-04P.2",
   "title": "6.16.2 Declarations and statements",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#future-declarations-and-statements",
   "internal": 0,
   "content": "#### 6.16.2 Declarations and statements\n\n12. This edition has no `var` declarations, which take a local's type from its initializer. An initializer made only of literals has no type of its own (6.5), so a declaration names its type.\n13. A parameter has no default value. A call names every argument, positionally or by name (6.9.5).\n14. A function has no `where` clause on its size parameters. A kernel may have one (6.13.1).\n15. This edition has no tuples, so a function cannot return several values to be unpacked, as in `(q, r) = divmod(7, 2);`. A function returns one value and writes others through `inout` parameters (6.9.5).\n16. This edition has no `do` loops, which test the condition after the body. A `while` loop with a `break` (6.10.3, 6.10.6) does the same.\n17. A loop does not run over the elements of an array or a view, as in `for i, x in a { }`. A `for` statement runs over a range of indices (6.10.4).\n18. An array or a view has no declared lower bound, such as `I64[1..=m]`. Every array and view is indexed from 0 in every dimension (6.12.3).\n19. A function cannot return an array or a view, and a view cannot be stored at module level. A function writes its array results into a view parameter (6.12.4).\n20. A constant expression cannot call a user function, and no operation makes the contents of a file a constant array. A constant expression holds literals, constants, operators and the named operations of 7.2 (6.8).\n21. This edition has no attributes, such as an annotation on an export that sets how a function is called from C, Python or Fortran. The host interface of every export is the one SPEC-03P.1 defines (6.15.2)."
  },
  {
   "id": "spec-04p:future-operations",
   "edition": "SPEC-04P.2",
   "title": "6.16.3 Operations",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#future-operations",
   "internal": 0,
   "content": "#### 6.16.3 Operations\n\n22. The result forms (6.7.12) take integer operands only, so `add_result`, `sub_result`, `mul_result`, `div_result` and `sqrt_result` on fixed-point operands are not in this edition. A fixed-point operation that cannot give its result faults.\n23. This edition has no saturating conversion `x as| T`. For an integer `x`, `clamp(x, lo, hi) as T`, with `lo` and `hi` the bounds of `T`, gives the value clamped to the range of `T` (7.2.1).\n24. `++` and `--` do not apply to a fixed-point place. `x += 1.0;` adds one to a fixed-point `x` (6.7.14).\n25. This edition has no wrapping or saturating division (`div_wrap`, `div_sat`), no wrapping or saturating square root (`sqrt_wrap`, `sqrt_sat`), and no `divmod`, which needs tuples (paragraph 15). 7.2.2 gives the division functions.\n26. `clamp` does not take fixed-point operands (7.2.1).\n27. An integer literal has no exponent notation, such as `1e9`. Digit separators keep long literals readable: `1_000_000_000` (6.4.5).\n28. A fraction literal is not the source of a conversion, as in `2.5 as I32`. A fraction literal takes a fixed-point type from its context (6.5), and that value converts (6.6).\n29. A reduction does not run along one axis of an array of rank 2 or more, `fold_checked` takes no user function and does not apply `mul` to fixed-point elements, and `dot` does not take arrays of rank 2 (7.3).\n30. This edition has no `equal(a, b)` or `swap(a, b)` on arrays, no operators such as `a + b` on whole arrays, no `reshape` that copies, no `transpose` of a rank other than 2, and no `extent` or `reverse` with a dimension computed at run time (7.4).\n31. A kernel body calls no user function (6.13.3).\n32. A program cannot format into an array, as in `format(buf, ...)`, and structs, error values, handles and arrays of rank 2 or more have no default rendering (7.5.2)."
  },
  {
   "id": "spec-04p:future-memory",
   "edition": "SPEC-04P.2",
   "title": "6.16.4 Memory",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#future-memory",
   "internal": 0,
   "content": "#### 6.16.4 Memory\n\n33. An arena or a pool cannot hold fixed-point elements, and a kernel body cannot declare one (6.14)."
  },
  {
   "id": "spec-04p:library",
   "edition": "SPEC-04P.2",
   "title": "7 Library",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#library",
   "internal": 0,
   "content": "## 7 Library\n\nThe library is the set of operations a program calls by name without declaring or importing them: integer and fixed-point arithmetic that needs a wider intermediate or a named rounding, reductions over arrays, functions that measure, fill, copy and re-view arrays and the formatting that print statements apply to values. A library operation follows the rules of the operators. A checked operation gives an exact result, or a result rounded once by a mode the program names, and checks that result against its type; when the result does not fit, it faults with a record that names the operation, its operands and the bound it crossed. The wrapping and saturating operations (`sum_wrap`, `sum_sat`, `mul_wrap`, `mul_sat`) never fault on overflow.\n\nThe result forms `add_result` to `shl_result` are in 6.7.12. The members of arenas and pools, such as `alloc` and `insert`, are in 6.14."
  },
  {
   "id": "spec-04p:reserved-names-and-arguments",
   "edition": "SPEC-04P.2",
   "title": "7.1 Reserved names and arguments",
   "clauses": "LS-145",
   "url": "/specifications/spec-04p/2/#reserved-names-and-arguments",
   "internal": 0,
   "content": "### 7.1 Reserved names and arguments\n\nLibrary names are reserved in every module, so `sum` or `min` means the same thing in every program. A call of a library operation is written like a function call, but some of its arguments are not values: a type that names the result, a rounding mode or an operation, each written as a bare name.\n\n**Constraints**\n\n1. The names in this table are the built-in functions. They are visible in every module without an import. A declaration of one of them, of any kind and in any scope, is diagnosed C3001 [LS-145].\n\n| Names | Subclause |\n|---|---|\n| `abs`, `uabs` | 6.7.5 |\n| `div_round`; `mul`, `div`, `mul_wrap`, `mul_sat` | 6.7.7 |\n| `rotl`, `rotr` | 6.7.8 |\n| `min`, `max`, `clamp` | 7.2.1 |\n| `div_trunc`, `rem_trunc`, `div_euclid`, `rem_euclid` | 7.2.2 |\n| `mul_full`, `muldiv`, `isqrt`, `isqrt_round` | 7.2.3 |\n| `sqrt`, `qmul`, `mul_int` | 7.2.4 |\n| `add_result`, `sub_result`, `mul_result`, `div_result`, `rem_result`, `shl_result` | 6.7.12 |\n| `sum`, `fold_checked`, `sum_wrap`, `sum_sat`, `count`, `dot`; `min` and `max` over an array | 7.3 |\n| `len`, `extent`, `size`, `copy`, `fill`, `transpose`, `reverse`, `reshape` | 7.4 |"
  },
  {
   "id": "spec-04p:reserved-names-and-arguments-p1",
   "edition": "SPEC-04P.2",
   "title": "7.1 Reserved names and arguments (part 2)",
   "clauses": "LS-145 LS-146 LS-307",
   "url": "/specifications/spec-04p/2/#reserved-names-and-arguments",
   "internal": 0,
   "content": "2. The names `divmod`, `equal`, `swap`, `lower`, `wrap_bits`, `random`, `format`, `utf8`, `embed`, `to_device`, `to_host`, `rescale3`, `rescale3_rem`, `shl3`, `sign` and `tdot` are reserved for built-in operations: a declaration of one of them is diagnosed C3001, as for the names of paragraph 1, and this edition gives them no meaning [LS-145].\n3. <a id=\"LS-146\"></a><a id=\"LS-307\"></a>Three kinds of argument are names, not values [LS-146, LS-307]:\n   - A *type argument* is a type name written as the first argument of `muldiv`, `sum`, `dot` or `qmul`. It names the result type. Only these built-ins take a type argument; a type name as an argument of a user function is diagnosed C3007.\n   - A *mode argument* is the name of a rounding mode (6.7.15), written bare as the last argument of `div_round`, `muldiv`, `isqrt_round`, `mul`, `div`, `mul_wrap`, `mul_sat`, `sqrt`, `qmul` or `dot`. A mode position is resolved by its position, not by looking the name up, so a variable named `floor` does not change `div_round(a, b, floor)`. Any other name in a mode position is diagnosed C3007.\n   - An *operation argument* is `add` or `mul`, written bare as the first argument of `fold_checked`. Any other name there is diagnosed C3007.\n4. A built-in takes no named arguments (C2063). A call with the wrong number of arguments for the built-in is diagnosed C2022 [LS-145].\n5. Where the description of a built-in gives several value arguments one type `T`, they shall have the same type, and mixing two types is diagnosed C2001. A literal argument takes the type of the typed arguments. When every such argument is a literal, `T` is the type that the context of the call requires, or `I64` when the context requires none (6.5) [LS-145].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:reserved-names-and-arguments-p2",
   "edition": "SPEC-04P.2",
   "title": "7.1 Reserved names and arguments (part 3)",
   "clauses": "IM-51",
   "url": "/specifications/spec-04p/2/#reserved-names-and-arguments",
   "internal": 0,
   "content": "6. Each call of a built-in is one operation. It gives its result or raises one fault, positioned at the name of the built-in in the call, whatever the implementation computes internally [IM-51].\n\n**Examples**\n\n7. A mode position takes the mode's name even when a variable has the same name:\n\n```cint mode_position.ci\nI64 floor = 10;\n\"{div_round(7, 2, floor)} {div_round(7, 2, ceil)} {floor}\\n\";\n```\n\n```text\n3 4 10\n```\n\n8. A library name cannot be declared:\n\n```cint reserved_name.ci\nI64 count = 0;\n\"{count}\\n\";\n```\n\n```text\nerror[C3001]: duplicate name\n  --> reserved_name.ci:1:5\n   |\n 1 | I64 count = 0;\n   |     ^\n```\n\n**Notes**\n\n9. In C, a local variable may hide a library function of the same name. A cint program cannot declare these names at all, so a reader of `sum(xs)` or `min(a, b)` never needs to look for a declaration."
  },
  {
   "id": "spec-04p:integer-and-fixed-point-operations",
   "edition": "SPEC-04P.2",
   "title": "7.2 Integer and fixed-point operations",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#integer-and-fixed-point-operations",
   "internal": 0,
   "content": "### 7.2 Integer and fixed-point operations\n\nThese functions compute what an operator cannot: the lesser or greater of two values, quotients rounded toward zero or by the Euclidean convention, products and quotients that need a wider intermediate, square roots and fixed-point products of two formats or of a fixed-point value and an integer. Each gives an exact or once-rounded result and checks it against its result type, as a checked operator does.\n\n| Call | Arguments | Result | Faults |\n|---|---|---|---|\n| `min(a, b)`, `max(a, b)` | `T` integer or fixed point | `T` | none |\n| `clamp(x, lo, hi)` | `T` integer | `T` | `E_DOMAIN` |\n| `div_trunc(a, b)`, `div_euclid(a, b)` | `T` integer | `T` | `E_DIV_ZERO`, `E_OVERFLOW` |\n| `rem_trunc(a, b)`, `rem_euclid(a, b)` | `T` integer | `T` | `E_DIV_ZERO` |\n| `mul_full(a, b)` | `T` of `I8` to `I512` or `U8` to `U256` | integer type of width 2`w`, same signedness | none |\n| `muldiv(R, a, b, c, mode)` | `T` integer; `R` any integer type | `R` | `E_DIV_ZERO`, `E_OVERFLOW` |\n| `isqrt(x)`, `isqrt_round(x, mode)` | `T` integer | `T` | `E_DOMAIN`, `E_OVERFLOW` |\n| `sqrt(a)`, `sqrt(a, mode)` | `Q<i>.<f>` | the same type | `E_DOMAIN`, `E_OVERFLOW` |\n| `qmul(R, a, b)`, `qmul(R, a, b, mode)` | `a`, `b` fixed point of any formats; `R` fixed point | `R` | `E_OVERFLOW` |\n| `mul_int(a, n)` | `a` fixed point; `n` any integer type | the type of `a` | `E_OVERFLOW` |\n\nThe other built-in operations on single values are stated with the operators they complete: `abs` and `uabs` in 6.7.5; `div_round`, and the fixed-point `mul`, `div`, `mul_wrap` and `mul_sat` with a rounding mode, in 6.7.7; `rotl` and `rotr` in 6.7.8; and the result forms in 6.7.12. The rounding modes are in 6.7.15."
  },
  {
   "id": "spec-04p:min-max-and-clamp",
   "edition": "SPEC-04P.2",
   "title": "7.2.1 min, max and clamp",
   "clauses": "IM-49 LS-145",
   "url": "/specifications/spec-04p/2/#min-max-and-clamp",
   "internal": 0,
   "content": "#### 7.2.1 min, max and clamp\n\n`min` and `max` choose one of two values, and `clamp` limits a value to a range. None of them computes a new value, so none can overflow.\n\n**Constraints**\n\n1. <a id=\"IM-49\"></a>The two arguments of `min(a, b)` and of `max(a, b)` shall have one integer or fixed-point type `T`. The three arguments of `clamp(x, lo, hi)` shall have one integer type `T` [LS-145, IM-49].\n2. When `lo` and `hi` are both constant expressions and `lo > hi`, the call of `clamp` is diagnosed C6006 [IM-49].\n3. A call of `min` or `max` whose last argument is an array or a view is the reduction of 7.3, not this function.\n\n**Semantics**\n\n4. `min(a, b)` gives the lesser and `max(a, b)` the greater of the two values. On fixed point they compare the values, which is the order of the storage integers [IM-49].\n5. When `lo <= hi`, `clamp(x, lo, hi)` gives `lo` if `x < lo`, `hi` if `x > hi` and `x` otherwise. `min` and `max` never fault, and `clamp` faults only as paragraph 6 states [IM-49].\n\n**Faults**\n\n6. The fault `E_DOMAIN` is raised by `clamp` when `lo > hi` at run time, whatever `x` is. The record holds the operation identifier `clamp.checked.t` and the operands `x`, `lo` and `hi`. It has no exact result and no limit [IM-49].\n\n**Examples**\n\n7. This example shows `min`, `max` and `clamp`, including a value that `clamp` raises to its lower bound and one that it lowers to its upper bound:\n\n```cint min_max.ci\nI64 t = -7;\n\"{min(t, 2)} {max(t, 2)} {clamp(t, -5, 5)} {clamp(12, -5, 5)}\\n\";\n```\n\n```text\n-7 2 -5 5\n```\n\n8. Constant bounds in the wrong order are found during translation:\n\n```cint clamp_bounds.ci\nI64 x = 9;\n\"{clamp(x, 5, 1)}\\n\";\n```\n\n```text\nerror[C6006]: compile-time evaluation rule\n  --> clamp_bounds.ci:2:3\n...\n```"
  },
  {
   "id": "spec-04p:division-functions",
   "edition": "SPEC-04P.2",
   "title": "7.2.2 Division functions",
   "clauses": "IM-36 IM-39 IM-40",
   "url": "/specifications/spec-04p/2/#division-functions",
   "internal": 0,
   "content": "#### 7.2.2 Division functions\n\nThe operators `/` and `%` divide with the quotient rounded toward negative infinity (6.7.7). These functions give the two other conventions in common use.\n\n| Function | Quotient `q` | Remainder `r` |\n|---|---|---|\n| `a / b`, `a % b` (6.7.7) | `floor(a / b)` | zero or the sign of `b` |\n| `div_trunc(a, b)`, `rem_trunc(a, b)` | rounded toward zero | zero or the sign of `a` |\n| `div_euclid(a, b)`, `rem_euclid(a, b)` | the `q` for which `0 <= r < \\|b\\|` | never negative |\n\n**Constraints**\n\n1. <a id=\"IM-36\"></a>The two arguments of each function of this subclause shall have one integer type `T`. A fixed-point argument is diagnosed C2103 [IM-36].\n\n**Semantics**\n\n2. For `b != 0`, `div_trunc(a, b)` is the rational `a / b` rounded toward zero, and `rem_trunc(a, b)` is `a - b * div_trunc(a, b)` [IM-36].\n3. For `b != 0`, `div_euclid(a, b)` is the integer `q` for which `r = a - b * q` satisfies `0 <= r < |b|`, and `rem_euclid(a, b)` is that `r` [IM-36].\n4. In each pair, `a == q * b + r` holds exactly. The quotients of `div_trunc` and `div_euclid` are checked against `T`: when the exact quotient is outside the range of `T`, the function faults [IM-36, IM-39].\n5. For signed `T`, `MIN(T)` divided by -1 has the quotient `-MIN(T)`, which is outside the range, so `div_trunc` and `div_euclid` fault. Its remainder is 0, so `rem_trunc(MIN(T), -1)` and `rem_euclid(MIN(T), -1)` give 0 and do not fault. An implementation shall give 0 for these remainders and shall not trap [IM-39, IM-40].\n\n**Faults**"
  },
  {
   "id": "spec-04p:division-functions-p1",
   "edition": "SPEC-04P.2",
   "title": "7.2.2 Division functions (part 2)",
   "clauses": "IM-39",
   "url": "/specifications/spec-04p/2/#division-functions",
   "internal": 0,
   "content": "6. The fault `E_DIV_ZERO` is raised by every function of this subclause when `b == 0`, before any other check. The record holds the operation identifier `<name>.checked.t`, for example `rem_euclid.checked.i64`, and the operands `a` and `b`. It has no exact result and no limit. Its position is the name of the function in the call [IM-39].\n7. The fault `E_OVERFLOW` is raised by `div_trunc` and `div_euclid` when the quotient is outside the range of `T`. The record holds the same operation and operands, the exact quotient, and the bound it crossed [IM-39].\n\n**Examples**\n\n8. The three conventions differ when the operands have opposite signs:\n\n```cint division_forms.ci\nI64 a = -7;\nI64 b = 2;\n\"{a / b} {a % b}\\n\";\n\"{div_trunc(a, b)} {rem_trunc(a, b)}\\n\";\n\"{div_euclid(a, b)} {rem_euclid(a, b)}\\n\";\n\"{div_euclid(7, -2)} {rem_euclid(7, -2)}\\n\";\n```\n\n```text\n-4 1\n-3 -1\n-4 1\n-3 1\n```\n\n9. The remainders of `MIN(T)` by -1 are 0; the quotient does not fit:\n\n```cint trunc_overflow.ci\nI64 m = I64.min;\nI64 d = -1;\n\"{rem_trunc(m, d)} {rem_euclid(m, d)}\\n\";\nI64 q = div_trunc(m, d);\n```\n\n```text\n0 0\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> trunc_overflow.ci:4:9\n   |\n 4 | I64 q = div_trunc(m, d);\n   |         ^ div_trunc.checked.i64\n   |\n   = operation: div_trunc.checked.i64\n   = operand-count: 2\n   = operand: I64 -9223372036854775808\n   = operand: I64 -1\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n   ...\n```\n\n10. This example shows division by zero:\n\n```cint euclid_zero.ci\nI64 a = 5;\nI64 z = 0;\n\"{rem_euclid(a, z)}\\n\";\n```\n\n```text\nfault[E_DIV_ZERO]: division by zero\n  --> euclid_zero.ci:3:3\n   |\n 3 | \"{rem_euclid(a, z)}\\n\";\n   |   ^ rem_euclid.checked.i64\n   |\n   = operation: rem_euclid.checked.i64\n   = operand-count: 2\n   = operand: I64 5\n   = operand: I64 0\n   = exact:   none\n   = limit:   none\n   ...\n```\n\n**Notes**"
  },
  {
   "id": "spec-04p:division-functions-p2",
   "edition": "SPEC-04P.2",
   "title": "7.2.2 Division functions (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#division-functions",
   "internal": 0,
   "content": "11. Fortran's `MOD` truncates, like C's `%` and corresponds to `rem_trunc`; Fortran's `MODULO` corresponds to `%`. A remainder that must lie in `0` to `|b| - 1`, such as an index into a ring buffer, is `rem_euclid` whatever the sign of `b`."
  },
  {
   "id": "spec-04p:wide-intermediates",
   "edition": "SPEC-04P.2",
   "title": "7.2.3 Wide intermediates",
   "clauses": "IM-51 IM-53",
   "url": "/specifications/spec-04p/2/#wide-intermediates",
   "internal": 0,
   "content": "#### 7.2.3 Wide intermediates\n\nAn operator never computes in a wider type than its operands. When a computation needs more bits in the middle than at the end, such as a product that is divided at once, the program asks for it by name. Each of these functions keeps its intermediate exact and rounds at most once.\n\n**Constraints**\n\n1. <a id=\"IM-51\"></a>The arguments of `mul_full(a, b)` shall have one type `T` among `I8` to `I512` and `U8` to `U256`; `I1024` and `U512` are diagnosed C2103 [IM-51].\n2. <a id=\"IM-53\"></a>In `muldiv(R, a, b, c, mode)`, `a`, `b` and `c` shall have one integer type `T`. `R` may be `T` or any other integer type [IM-53].\n3. The argument of `isqrt(x)` and of `isqrt_round(x, mode)` shall have an integer type `T` [IM-51].\n\n**Semantics**\n\n4. `mul_full(a, b)` gives the exact product `a * b` as a value of the integer type of width 2`w` and the same signedness as `T`: `I16` for `I8`, `I128` for `I64`, `I1024` for `I512`, `U128` for `U64`, `U512` for `U256`. Every such product fits, so `mul_full` never faults [IM-51].\n5. `muldiv(R, a, b, c, mode)` forms the exact product `a * b`, divides it by `c` as a rational, rounds the quotient once by `mode` and checks the rounded value against `R`. The product is never narrowed, whatever the widths of `T` and `R` [IM-51, IM-53].\n6. `isqrt(x)` gives `floor(sqrt(x))`: the unique `r >= 0` with `r * r <= x < (r + 1) * (r + 1)` [IM-51].\n7. `isqrt_round(x, mode)` gives the square root of `x` rounded by `mode`. The square root of an integer is never exactly halfway between two integers, so every `half_` mode gives the nearest integer. The rounded value is checked against `T` [IM-51].\n\n**Faults**"
  },
  {
   "id": "spec-04p:wide-intermediates-p1",
   "edition": "SPEC-04P.2",
   "title": "7.2.3 Wide intermediates (part 2)",
   "clauses": "IM-51 IM-52",
   "url": "/specifications/spec-04p/2/#wide-intermediates",
   "internal": 0,
   "content": "8. The fault `E_DIV_ZERO` is raised by `muldiv` when `c == 0`. The record holds the operation identifier `muldiv.checked.t.r.mode`, which names both `T` and `R`, for example `muldiv.checked.i64.i64.floor`, and the operands `a`, `b` and `c`. It has no exact result and no limit [IM-51].\n9. The fault `E_OVERFLOW` is raised by `muldiv` when the rounded quotient is outside the range of `R`. The record holds the same operation and operands, the rounded quotient as the exact result, and the bound of `R` it crossed [IM-51].\n10. <a id=\"IM-52\"></a>The fault `E_DOMAIN` is raised by `isqrt` and `isqrt_round` when `x < 0`. The record holds the operation identifier `isqrt.checked.t` or `isqrt_round.checked.t.mode` and the operand `x`. It has no exact result and no limit [IM-52].\n11. The fault `E_OVERFLOW` is raised by `isqrt_round` when the rounded root is outside the range of `T`, with the rounded root as the exact result [IM-51].\n\n**Examples**\n\n12. This example shows a product that overflows `I64` and a scaled ratio that does not:\n\n```cint wide_ops.ci\nI64 big = I64.max;\nI128 p = mul_full(big, big);\n\"{p}\\n\";\n\"{muldiv(I64, big, big, big, floor)}\\n\";\n\"{muldiv(I64, 7, 5, 2, half_even)} {muldiv(I64, 9, 5, 2, half_even)}\\n\";\nI128 x = 1 << 65;\n\"{isqrt(x)} {isqrt_round(x, half_even)}\\n\";\n```\n\n```text\n85070591730234615847396907784232501249\n9223372036854775807\n18 22\n6074000999 6074001000\n```\n\n13. The exact result in a `muldiv` record is the rounded quotient, before the range check:\n\n```cint muldiv_overflow.ci\nI64 big = I64.max;\nI64 three = 3;\nI64 r = muldiv(I64, big, three, 2, ceil);\n\"{r}\\n\";\n```"
  },
  {
   "id": "spec-04p:wide-intermediates-p2",
   "edition": "SPEC-04P.2",
   "title": "7.2.3 Wide intermediates (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#wide-intermediates",
   "internal": 0,
   "content": "```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> muldiv_overflow.ci:3:9\n   |\n 3 | I64 r = muldiv(I64, big, three, 2, ceil);\n   |         ^ muldiv.checked.i64.i64.ceil\n   |\n   = operation: muldiv.checked.i64.i64.ceil\n   = operand-count: 3\n   = operand: I64 9223372036854775807\n   = operand: I64 3\n   = operand: I64 2\n   = exact:   13835058055282163711\n   = limit:   I64 9223372036854775807\n   ...\n```\n\n14. `mul_full` of `U64` gives `U128`:\n\n```cint mul_full_u64.ci\nU64 a = U64.max;\nU128 p = mul_full(a, a);\n\"{p}\\n\";\n```\n\n```text\n340282366920938463426481119284349108225\n```"
  },
  {
   "id": "spec-04p:fixed-point-operations",
   "edition": "SPEC-04P.2",
   "title": "7.2.4 Fixed-point operations",
   "clauses": "IM-63 IM-64 IM-67",
   "url": "/specifications/spec-04p/2/#fixed-point-operations",
   "internal": 0,
   "content": "#### 7.2.4 Fixed-point operations\n\nA fixed-point value `Q<i>.<f>` is held as a storage integer `A`, its value being `A / 2^f` (6.3.2). The operators combine values of one format. These functions take a square root, multiply values of two different formats and multiply a fixed-point value by an integer. Each rounds at most once, on the exact result, and checks the rounded storage integer against the range of the result's storage type.\n\n**Constraints**\n\n1. <a id=\"IM-67\"></a>The argument of `sqrt(a)` and of `sqrt(a, mode)` shall have a fixed-point type. An integer argument is diagnosed C2103; `isqrt` is the integer square root [IM-67].\n2. <a id=\"IM-63\"></a>In `qmul(R, a, b)` and `qmul(R, a, b, mode)`, `R` shall be a fixed-point type and `a` and `b` values of fixed-point types, of any formats. An integer argument is diagnosed C2103 [IM-63].\n3. <a id=\"IM-64\"></a>In `mul_int(a, n)`, `a` shall have a fixed-point type and `n` an integer type of any width [IM-64].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:fixed-point-operations-p1",
   "edition": "SPEC-04P.2",
   "title": "7.2.4 Fixed-point operations (part 2)",
   "clauses": "IM-63 IM-64 IM-67",
   "url": "/specifications/spec-04p/2/#fixed-point-operations",
   "internal": 0,
   "content": "4. For `a` of `Q<i>.<f>` with storage integer `A >= 0`, `sqrt(a, mode)` gives the value whose storage integer is `isqrt_round(A * 2^f, mode)`, computed in an intermediate of at least 2`w` bits. `sqrt(a)` uses `half_even`. The storage integer is then checked against the range of the storage type. For `i >= 2` the root is always in range; for `Q1.<f>`, the modes that round up can reach `2^(w - 1)`, which is not [IM-67].\n5. For `a` of `Q<ia>.<fa>` with storage integer `A`, `b` of `Q<ib>.<fb>` with storage integer `B`, and `R` of `Q<ir>.<fr>`, `qmul(R, a, b, mode)` forms the exact product `A * B`, whose scale is `2^(fa + fb)`. When `fa + fb > fr` the storage integer of the result is `A * B / 2^(fa + fb - fr)` rounded once by `mode`, and `qmul(R, a, b)` uses `half_even`. Otherwise it is `A * B * 2^(fr - fa - fb)`, exactly and nothing rounds. The storage integer is then checked against the range of `R` [IM-63].\n6. `mul_int(a, n)` gives the value of the type of `a` whose storage integer is `A * n`, exactly, checked against the range of that type. Nothing rounds [IM-64].\n\n**Faults**"
  },
  {
   "id": "spec-04p:fixed-point-operations-p2",
   "edition": "SPEC-04P.2",
   "title": "7.2.4 Fixed-point operations (part 3)",
   "clauses": "IM-52 IM-63 IM-64 IM-67",
   "url": "/specifications/spec-04p/2/#fixed-point-operations",
   "internal": 0,
   "content": "7. The fault `E_DOMAIN` is raised by `sqrt` when `a < 0`. The record holds the operation identifier `sqrt.checked.q.mode`, where `q` spells the type with an underscore for the point (`q16_16` for `Q16.16`) and `mode` is the mode used, written or default; the operand is `a`. It has no exact result and no limit [IM-52, IM-67].\n8. The fault `E_OVERFLOW` is raised by `sqrt` when the rounded storage integer is out of range, for example `sqrt(Q1.15.raw(32767), ceil)`, whose rounded storage integer is 32768. The record holds the operation, the operand, that storage integer as the exact result, and the type's bound as the limit [IM-67].\n9. The fault `E_OVERFLOW` is raised by `qmul` when the storage integer of the result is outside the range of `R`. The operation identifier is `qmul.checked.qa.qb.r`, followed by `.mode` only when the operation rounds; the operands are `a` and `b`, and the exact result is the rounded storage integer [IM-63].\n10. The fault `E_OVERFLOW` is raised by `mul_int` when `A * n` is outside the range of the storage type. The operation identifier is `mul_int.checked.q.n`, for example `mul_int.checked.q16_16.i64`; the operands are `a` and `n`, the exact result is `A * n`, and the limit is the bound of the type of `a` [IM-64].\n\n**Examples**\n\n11. A square root rounded two ways, a product of two formats and a product by an integer. `0.5` in `Q1.15` has the storage integer 16384, and `1.5` in `Q16.16` has 98304; their product has the scale `2^31`, and `qmul` rounds it to `2^16` or widens it to `2^32`:\n\n```cint fixed_ops.ci\nQ16.16 two = 2.0;\n\"{sqrt(two)} {sqrt(two, floor)}\\n\";\nQ16.16 a = 1.5;\nQ1.15 h = 0.5;\n\"{qmul(Q16.16, a, h)} {qmul(Q32.32, a, h)}\\n\";\nI32 k = 3;\n\"{mul_int(a, k)}\\n\";\n```\n\n```text\n1.414215087890625 1.4141998291015625\n0.75 0.75\n4.5\n```"
  },
  {
   "id": "spec-04p:fixed-point-operations-p3",
   "edition": "SPEC-04P.2",
   "title": "7.2.4 Fixed-point operations (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#fixed-point-operations",
   "internal": 0,
   "content": "12. This example shows a square root of a negative value. In a fault record, a fixed-point value is written as its storage integer, `Q16.16 raw -131072` for -2.0:\n\n```cint sqrt_domain.ci\nvoid show(Q16.16 a) {\n    \"{sqrt(a)}\\n\";\n}\nshow(-2.0);\n```\n\n```text\nfault[E_DOMAIN]: operand outside the operation's domain\n  --> sqrt_domain.ci:2:7\n   |\n 2 |     \"{sqrt(a)}\\n\";\n   |       ^ sqrt.checked.q16_16.half_even\n   |\n   = operation: sqrt.checked.q16_16.half_even\n   = operand-count: 1\n   = operand: Q16.16 raw -131072\n   = exact:   none\n   = limit:   none\n   ...\n```\n\n13. A product by an integer that leaves the range of `Q16.16`. The exact result is the storage integer `A * n`:\n\n```cint mulint_over.ci\nvoid show(Q16.16 a, I64 k) {\n    \"{mul_int(a, k)}\\n\";\n}\nshow(20000.5, 2);\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> mulint_over.ci:2:7\n   |\n 2 |     \"{mul_int(a, k)}\\n\";\n   |       ^ mul_int.checked.q16_16.i64\n   |\n   = operation: mul_int.checked.q16_16.i64\n   = operand-count: 2\n   = operand: Q16.16 raw 1310752768\n   = operand: I64 2\n   = exact:   2621505536\n   = limit:   Q16.16 raw 2147483647\n   ...\n```"
  },
  {
   "id": "spec-04p:reductions",
   "edition": "SPEC-04P.2",
   "title": "7.3 Reductions",
   "clauses": "IM-73",
   "url": "/specifications/spec-04p/2/#reductions",
   "internal": 0,
   "content": "### 7.3 Reductions\n\nA reduction combines the elements of an array or a view into one value. Checked and saturating additions do not give the same result in every order: with `M` the maximum of `I64`, `(M + 1) + (-1)` faults while `M + (1 + (-1))` gives `M` and in `I8` saturating `120 + 120 - 120` gives 7 left to right but 120 right to left. So each reduction is a named operation whose result is defined independently of how an implementation schedules the work [IM-73].\n\n| Call | Result | Order | Faults |\n|---|---|---|---|\n| `sum(xs)`, `sum(R, xs)` | the exact sum, checked once against `R` (default: the element type) | any | `E_OVERFLOW` at the final check |\n| `fold_checked(add, init, xs)`, `fold_checked(mul, init, xs)` | `init` combined with each element in turn, each step checked | logical order | `E_OVERFLOW` at the first step out of range |\n| `sum_wrap(xs)` | the exact sum, wrapped to the element type | any | none |\n| `sum_sat(xs)` | `0` combined with each element in turn by `+\\|` | logical order | none |\n| `min(xs)`, `max(xs)` | the least or greatest element | any | `E_SHAPE` when `xs` is empty |\n| `min(init, xs)`, `max(init, xs)` | as above, with `init` included | any | none |\n| `count(mask)` | the number of `true` elements, as an `I64` | any | none |\n| `dot(R, a, b)` | the exact sum of the products `a[k] * b[k]`, checked once against `R` | any | `E_SHAPE`, `E_OVERFLOW` |\n\n**Constraints**"
  },
  {
   "id": "spec-04p:reductions-p1",
   "edition": "SPEC-04P.2",
   "title": "7.3 Reductions (part 2)",
   "clauses": "IM-77 IM-87 R-4",
   "url": "/specifications/spec-04p/2/#reductions",
   "internal": 0,
   "content": "1. <a id=\"IM-77\"></a>The array argument of a reduction, `xs`, `mask`, `a` or `b`, shall be an array or a view; any other argument is diagnosed C2103. Every reduction but `dot` accepts any rank from 1 to 4 [IM-77].\n2. The elements shall have an integer or fixed-point type, diagnosed C2103 otherwise, except for `count`, whose elements shall be `Bool` (C2001) [IM-77].\n3. <a id=\"R-4\"></a>In `sum(R, xs)`, `R` shall be an integer type when the elements are integers; any integer `R` is allowed, wider or narrower than the elements. When the elements are fixed point, `R` is the element type. Any other `R` is diagnosed C9102 [IM-77, R-4].\n4. In `fold_checked(op, init, xs)` and in `min(init, xs)` and `max(init, xs)`, `init` shall have the element type (C2001). The operation `mul` is allowed on integer elements [IM-77].\n5. <a id=\"IM-87\"></a>`dot(R, a, b)` shall have a type as its first argument (C3007). `a` and `b` shall be rank-1 arrays or views of one element type (C2001). `R` is an integer type when the elements are integers and a fixed-point type when they are fixed point, and a mode argument may follow only for fixed point [IM-87].\n6. A reduction across the work-items of a kernel is written with a `reduce` statement (6.13.5).\n\n**Semantics**"
  },
  {
   "id": "spec-04p:reductions-p2",
   "edition": "SPEC-04P.2",
   "title": "7.3 Reductions (part 3)",
   "clauses": "IM-74 IM-77 IM-78 IM-79 IM-80 IM-82 IM-83 IM-84 IM-85 IM-87 R-4",
   "url": "/specifications/spec-04p/2/#reductions",
   "internal": 0,
   "content": "7. <a id=\"IM-74\"></a>The *logical order* of the elements of an array or view is the row-major order of their logical indices, in which the last index varies fastest. It does not depend on the layout of the storage, on strides, or on where the view begins [IM-74].\n8. <a id=\"IM-78\"></a><a id=\"IM-82\"></a>`sum(xs)` and `sum(R, xs)` compute the exact sum of the elements in Z and check it once against `R`, which is the element type when omitted. Partial sums are never checked, so every order of addition gives the same result. The final check is a range check on an exact value, so it raises `E_OVERFLOW`, not the `E_NARROW` of a conversion [IM-77, IM-78, IM-82].\n9. <a id=\"IM-80\"></a>An implementation may compute a sum of `n` signed or unsigned `w`-bit elements in any accumulator of at least `w + ceil(log2(n))` bits, in any association order, because no partial sum can leave that range; or by any other method that gives the exact sum. For `I64` and narrower elements an `I128` accumulator is enough [IM-80].\n10. <a id=\"IM-83\"></a>`fold_checked(add, init, xs)` sets an accumulator of the element type to `init` and then, for each element `x` in logical order, sets it to `acc + x` with a checked addition in the element type; `fold_checked(mul, init, xs)` uses a checked multiplication. The result is the final accumulator. A fault is raised at the least index `j` whose step leaves the range. For `add`, the accumulator after element `j` is `init + x_0 + ... + x_j` exactly, so an implementation may compute exact prefix sums in a wider accumulator and report the least `j` whose prefix is out of range [IM-77, IM-83].\n11. `sum_wrap(xs)` gives `wrap(E, s)`, where `E` is the element type and `s` the exact sum. Wrapped addition is associative and commutative, so every order gives this result [IM-77, IM-82].\n12. <a id=\"IM-84\"></a>`sum_sat(xs)` sets an accumulator to 0 and, for each element `x`"
  },
  {
   "id": "spec-04p:reductions-p3",
   "edition": "SPEC-04P.2",
   "title": "7.3 Reductions (part 4)",
   "clauses": "IM-77 IM-81 IM-83 IM-87",
   "url": "/specifications/spec-04p/2/#reductions",
   "internal": 0,
   "content": "**Faults**\n\n19. Every fault of a reduction is positioned at the name of the built-in in the call [IM-77].\n20. <a id=\"IM-81\"></a>The fault `E_OVERFLOW` is raised by `sum` when the exact sum is outside the range of `R`. The record holds the operation identifier `sum.checked.e.r`, which always names both the element type and `R`, one operand, the count of elements `n` as an `I64`, the exact sum as the exact result, and the bound of `R` it crossed. It does not hold the elements [IM-81].\n21. The fault `E_OVERFLOW` is raised by `fold_checked` at the least index `j` whose step leaves the range. The record holds the operation identifier `fold_checked.add.e` or `fold_checked.mul.e`, the operands `j` as an `I64`, the accumulator before step `j` and the element `x_j`, both in the element type, the out-of-range result as the exact result, and the bound it crossed [IM-83].\n22. The fault `E_SHAPE` is raised by `min(xs)` and `max(xs)` when `xs` is empty. The record holds the operation identifier `reduce_min.checked.e` or `reduce_max.checked.e` and one operand, `I64 0`, the count. It has no exact result and no limit [IM-77].\n23. The fault `E_SHAPE` is raised by `dot` when `a` and `b` have different extents, before any fuel is charged. The record holds the operation identifier `dot.checked.e.r`, the operands `I64 0`, the dimension and the extent of `b` as an `I64`, no exact result and the extent of `a` as the limit [IM-87].\n24. The fault `E_OVERFLOW` is raised by `dot` when the result is outside the range of `R`, with the record of `sum`: the count `n`, the exact sum, rounded for fixed point, and the bound of `R`. For fixed point the operation is `dot.checked.q.r` followed by `.mode` only when the operation rounds [IM-87].\n\n**Examples**\n\n25. This example shows four reductions of the same three values:"
  },
  {
   "id": "spec-04p:reductions-p4",
   "edition": "SPEC-04P.2",
   "title": "7.3 Reductions (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#reductions",
   "internal": 0,
   "content": "```cint reductions.ci\nvoid show() {\n    I8[3] v = [120, 120, -120];\n    I8 a = sum(v);\n    I8 c = sum_sat(v);\n    I8 d = sum_wrap(v);\n    I8[3] u = [127, 127, 127];\n    I16 e = sum(I16, u);\n    \"{a} {c} {d} {e}\\n\";\n    \"{min(v)} {max(v)} {min(-128, v)}\\n\";\n    Bool[4] m = [true, false, true, true];\n    \"{count(m)}\\n\";\n    I32[3] x = [1, 2, 3];\n    I32[3] y = [4, 5, 6];\n    \"{dot(I64, x, y)}\\n\";\n}\nshow();\n```\n\n```text\n120 7 120 381\n-120 120 -128\n3\n32\n```\n\n26. `fold_checked` checks every step; the exact total of `v` fits `I8`, but the second partial sum does not:\n\n```cint fold_fault.ci\nvoid show() {\n    I8[3] v = [120, 120, -120];\n    I8 b = fold_checked(add, 0, v);\n    \"{b}\\n\";\n}\nshow();\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> fold_fault.ci:3:12\n   |\n 3 |     I8 b = fold_checked(add, 0, v);\n   |            ^ fold_checked.add.i8\n   |\n   = operation: fold_checked.add.i8\n   = operand-count: 3\n   = operand: I64 1\n   = operand: I8 120\n   = operand: I8 120\n   = exact:   240\n   = limit:   I8 127\n   ...\n```\n\n27. A `sum` checks only its final result:\n\n```cint sum_fault.ci\nvoid show() {\n    I8[3] u = [127, 127, 127];\n    I8 f = sum(u);\n    \"{f}\\n\";\n}\nshow();\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> sum_fault.ci:3:12\n   |\n 3 |     I8 f = sum(u);\n   |            ^ sum.checked.i8.i8\n   |\n   = operation: sum.checked.i8.i8\n   = operand-count: 1\n   = operand: I64 3\n   = exact:   381\n   = limit:   I8 127\n   ...\n```\n\n28. The order-dependent reductions follow logical order. A Fortran array `A(2, 2)` stored column by column is reduced in its own element order by reducing the transposed view (7.4):\n\n```cint reduce_order.ci\nvoid show() {\n    I8[2, 2] g = [[100, -100], [100, -100]];\n    \"{sum_sat(g)} {fold_checked(add, 0, g)} {sum_sat(transpose(g))}\\n\";\n}\nshow();\n```\n\n```text\n0 0 -73\n```"
  },
  {
   "id": "spec-04p:reductions-p5",
   "edition": "SPEC-04P.2",
   "title": "7.3 Reductions (part 6)",
   "clauses": "IM-75 IM-76",
   "url": "/specifications/spec-04p/2/#reductions",
   "internal": 0,
   "content": "29. This example shows the least element of an empty view:\n\n```cint min_empty.ci\nvoid show() {\n    I64[3] v = [4, 5, 6];\n    \"{min(9, v[0..0])}\\n\";\n    \"{min(v[0..0])}\\n\";\n}\nshow();\n```\n\n```text\n9\nfault[E_SHAPE]: shapes do not match\n  --> min_empty.ci:4:7\n   |\n 4 |     \"{min(v[0..0])}\\n\";\n   |       ^ reduce_min.checked.i64\n   |\n   = operation: reduce_min.checked.i64\n   = operand-count: 1\n   = operand: I64 0\n   = exact:   none\n   = limit:   none\n   ...\n```\n\n30. Fixed-point reductions keep the format; `dot` rounds the exact sum once. Here each product `2^-16 * 0.5` is below the resolution of `Q16.16`, but their exact sum is not:\n\n```cint fixed_reductions.ci\nvoid show() {\n    Q16.16[3] v = [0.5, 0.25, -1.0];\n    \"{sum(v)} {min(v)} {sum_sat(v)}\\n\";\n    Q16.16[2] x = [Q16.16.raw(1), Q16.16.raw(1)];\n    Q16.16[2] y = [0.5, 0.5];\n    \"{dot(Q16.16, x, y)}\\n\";\n}\nshow();\n```\n\n```text\n-0.25 -1.0 -0.25\n0.0000152587890625\n```\n\n**Notes**\n\n31. <a id=\"IM-75\"></a><a id=\"IM-76\"></a>A Fortran array `A(m, n)` presented with the shape `[m, n]` is reduced in the order `A(1,1)`, `A(1,2)`, and so on, while Fortran's array element order is `A(1,1)`, `A(2,1)`, and so on. The order does not change `sum`, `sum_wrap`, `min`, `max` or `count`, but it changes `fold_checked` and `sum_sat`, as example 28 shows. Reducing `transpose(a)`, a view that copies no element, gives Fortran's order [IM-75, IM-76]."
  },
  {
   "id": "spec-04p:array-operations",
   "edition": "SPEC-04P.2",
   "title": "7.4 Array operations",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#array-operations",
   "internal": 0,
   "content": "### 7.4 Array operations\n\nThese functions report the shape of an array or view, fill and copy elements and give new views of the same elements in another order or shape. A view function moves no element; it gives a view with other extents and strides over the same storage (6.12).\n\n| Call | Result |\n|---|---|\n| `len(a)` | the extent of a rank-1 array or view, as an `I64` |\n| `extent(a, d)` | the extent of dimension `d`, counted from 0, as an `I64` |\n| `size(a)` | the number of elements, the product of the extents, as an `I64` |\n| `fill(dst, v)` | sets every element of `dst` to `v` |\n| `copy(dst, src)` | copies the elements of `src` into `dst` |\n| `transpose(a)` | a view of a rank-2 array or view with its two dimensions exchanged |\n| `reverse(a, d)` | a view in which dimension `d` runs backward |\n| `reshape(a, e1, ...)` | a view of the elements of `a`, in logical order, with the extents `e1, ...` |\n\n**Constraints**"
  },
  {
   "id": "spec-04p:array-operations-p1",
   "edition": "SPEC-04P.2",
   "title": "7.4 Array operations (part 2)",
   "clauses": "LS-145",
   "url": "/specifications/spec-04p/2/#array-operations",
   "internal": 0,
   "content": "1. <a id=\"LS-145\"></a>The first argument of each function shall be an array or a view, diagnosed C2103 otherwise [LS-145].\n2. The argument of `len` shall have rank 1; `len` of an array of higher rank is diagnosed C2014; `extent` and `size` measure such an array [LS-145].\n3. The dimension `d` of `extent(a, d)` and of `reverse(a, d)` is an `I64` constant expression whose value is a dimension of `a`, from 0 to its rank minus 1 [LS-145].\n4. The destination of `fill` and of `copy` shall be a writable array or view, a place the function may write (C2067). The value of `fill` shall have the element type. The source of `copy` shall have the element type and rank of the destination (C2001), and where both extents of a dimension are known during translation they shall be equal (C2012) [LS-145].\n5. When the storage that the two arguments of `copy` name is known during translation to overlap without being the same view, the call is diagnosed C5010 (6.12.5) [LS-145].\n6. The argument of `transpose` shall have rank 2. The extents `e1, ...` of `reshape` are `I64` values (C2001), from one to four of them [LS-145].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:array-operations-p2",
   "edition": "SPEC-04P.2",
   "title": "7.4 Array operations (part 3)",
   "clauses": "LS-145",
   "url": "/specifications/spec-04p/2/#array-operations",
   "internal": 0,
   "content": "7. `len`, `extent` and `size` read the shape and never fault [LS-145].\n8. `fill(dst, v)` stores `v` in every element of `dst`. `copy(dst, src)` stores each element of `src` in the element of `dst` at the same logical index. A `copy` whose two arguments are the same view stores nothing [LS-145].\n9. `transpose(a)` gives the view whose element `[i, j]` is the element `[j, i]` of `a`. `reverse(a, d)` gives the view whose index `k` in dimension `d` names the element at index `extent(a, d) - 1 - k` of `a`. `reshape(a, e1, ...)` gives the view with extents `e1, ...` whose elements, in logical order, are the elements of `a` in logical order; this edition defines it when the product of `e1, ...` equals `size(a)` and the elements of `a` are stored contiguously in row-major order. Outside that condition `reshape` has no result in this edition, and an implementation refuses the program (3.16). Each view function gives a view of the same storage, which is writable when `a` is; no element is copied [LS-145].\n\n**Faults**\n\n10. The fault `E_SHAPE` is raised by `copy` when the extents of `src` and `dst` differ in a dimension, before any element is stored. The fault record is that of a copy, as 6.12.5, paragraph 9, states, and its position is the name `copy`.\n11. The fault `E_ALIAS` is raised by `copy` when `src` and `dst` are not shown disjoint (6.12.5) and are not the same view, after the shape check and before any element is stored. The fault record is that of a copy, as 6.12.5, paragraph 10, states.\n\n**Examples**\n\n12. This example shows shapes, and three views of one array:"
  },
  {
   "id": "spec-04p:array-operations-p3",
   "edition": "SPEC-04P.2",
   "title": "7.4 Array operations (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#array-operations",
   "internal": 0,
   "content": "```cint array_ops.ci\nvoid show(in I32[_, _] m) {\n    for i in 0..extent(m, 0) {\n        for j in 0..extent(m, 1) {\n            \"{m[i, j]} \";\n        }\n        \"| \";\n    }\n    \"\\n\";\n}\nvoid demo() {\n    I32[2, 3] m = [[1, 2, 3], [4, 5, 6]];\n    \"{extent(m, 0)} {extent(m, 1)} {size(m)}\\n\";\n    show(m);\n    show(transpose(m));\n    show(reverse(m, 1));\n    show(reshape(m, 3, 2));\n    I32[6] flat;\n    fill(flat, 7);\n    I32[3] row;\n    copy(row, m[1]);\n    \"{len(flat)} {flat[0]} {row[0]} {row[2]}\\n\";\n}\ndemo();\n```\n\n```text\n2 3 6\n1 2 3 | 4 5 6 | \n1 4 | 2 5 | 3 6 | \n3 2 1 | 6 5 4 | \n1 2 | 3 4 | 5 6 | \n6 7 4 6\n```\n\n13. A view is writable when its array is, so `fill` through a reversed view writes the array:\n\n```cint fill_view.ci\nvoid demo() {\n    I32[2, 3] m = [[1, 2, 3], [4, 5, 6]];\n    fill(reverse(m, 0)[0], 9);\n    \"{m[0, 0]} {m[1, 0]}\\n\";\n}\ndemo();\n```\n\n```text\n1 9\n```\n\n14. This example shows extents that differ only at run time:\n\n```cint copy_shape.ci\nvoid demo() {\n    I32[4] a = [1, 2, 3, 4];\n    I64 k = 2;\n    I32[3] b;\n    copy(b, a[0..k]);\n    \"{b[0]}\\n\";\n}\ndemo();\n```\n\n```text\nfault[E_SHAPE]: shapes do not match\n  --> copy_shape.ci:5:5\n   |\n 5 |     copy(b, a[0..k]);\n   |     ^ copy.shape\n   |\n   = operation: copy.shape\n   = operand-count: 2\n   = operand: I64 0\n   = operand: I64 2\n   = exact:   none\n   = limit:   I64 3\n   ...\n```\n\n15. This example shows overlapping storage, known only at run time:\n\n```cint copy_alias.ci\nvoid demo() {\n    I32[4] a = [1, 2, 3, 4];\n    I64 k = 1;\n    copy(a[0..3], a[k..k + 3]);\n    \"{a[0]}\\n\";\n}\ndemo();\n```\n\n```text\nfault[E_ALIAS]: views overlap\n  --> copy_alias.ci:4:5\n   |\n 4 |     copy(a[0..3], a[k..k + 3]);\n   |     ^ copy.alias\n   |\n   = operation: copy.alias\n   = operand-count: 0\n   = exact:   none\n   = limit:   none\n   ...\n```"
  },
  {
   "id": "spec-04p:formatting",
   "edition": "SPEC-04P.2",
   "title": "7.5 Formatting",
   "clauses": "IM-90 IM-91 LS-210",
   "url": "/specifications/spec-04p/2/#formatting",
   "internal": 0,
   "content": "### 7.5 Formatting\n\nA print statement (6.10.10) writes its string literals with each hole `{...}` replaced by the text of a value. This subclause defines that text. Every value prints exactly: an integer in full in decimal, whatever its width and a fixed-point value as the exact decimal expansion of its value. No value is ever rounded for display unless the hole asks for a precision, and none is printed in scientific notation [IM-90, IM-91, LS-210]."
  },
  {
   "id": "spec-04p:holes",
   "edition": "SPEC-04P.2",
   "title": "7.5.1 Holes",
   "clauses": "LS-198 LS-199 LS-214 LS-215",
   "url": "/specifications/spec-04p/2/#holes",
   "internal": 0,
   "content": "#### 7.5.1 Holes\n\nA hole names an expression and, optionally, how to print it: the expression's own text before its value, a conversion applied first and a format specification.\n\n**Syntax**\n\n```ebnf\nhole        = \"{\" hole_expr [ \"=\" ] [ \"!\" conversion ] [ \":\" spec ] \"}\" ;\nhole_expr   = or_expr ;\nconversion  = \"bits\" | \"raw\" | \"lanes\" \"(\" lane_type \")\" | \"ratio\" ;   (* \"ratio\" is reserved, 7.5.4 *)\nlane_type   = \"I8\" | \"I16\" | \"I32\" | \"I64\" | \"U8\" | \"U16\" | \"U32\" | \"U64\" ;\n```\n\n`or_expr` is the expression of 6.7 without an unparenthesized conditional expression or `catch`. `spec` is in 7.5.3, and which `lane_type` applies to which value is in 7.5.4.\n\n**Constraints**\n\n1. <a id=\"LS-198\"></a>Holes may appear in the string literals of a print statement and in the message of an `assert` (6.10.9). A hole in any other string literal is diagnosed C1033 [LS-198].\n2. <a id=\"LS-199\"></a>The hole expression is the longest prefix of the hole's text that is an `or_expr`. It shall not be empty and shall not contain a string literal or a brace, and a conditional expression in it shall be in parentheses: `{(ok ? a : b)}`. A hole that breaks these rules, has text left over after its expression, or names a conversion other than those of 7.5.4 and `ratio` is diagnosed C1035 [LS-198, LS-199].\n3. The value of a hole shall not be a struct, a handle, an arena or a pool; such a hole is diagnosed C1037 [LS-214]. A hole whose value is an error value, or an array or view of rank 2 or more, has no rendering in this edition (6.16), and an implementation refuses a program that has one (3.16). The other values, of an integer type, a fixed-point type or `Bool` and rank-1 arrays and views of them, are rendered as 7.5.2 states.\n4. <a id=\"LS-215\"></a>A literal brace in a string literal is written twice, `{{` or `}}`; a single `}` is diagnosed C1039 [LS-215].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:holes-p1",
   "edition": "SPEC-04P.2",
   "title": "7.5.1 Holes (part 2)",
   "clauses": "LS-195 LS-197 LS-198 LS-200",
   "url": "/specifications/spec-04p/2/#holes",
   "internal": 0,
   "content": "5. `{expr}` prints the value of `expr` in the default rendering of its type (7.5.2) [LS-198].\n6. <a id=\"LS-200\"></a>`{expr=}` prints the text of `expr` exactly as written in the source, spaces included, then `=`, then the value. The `=` comes immediately before `!`, `:` or the closing brace [LS-198, LS-200].\n7. `{expr!conv}` applies a conversion (7.5.4) before rendering, and `{expr:spec}` applies a format specification (7.5.3). The three parts may be combined, in the order `{expr=!conv:spec}`; `{expr:}` with an empty specification is `{expr}` [LS-198].\n8. <a id=\"LS-197\"></a>The holes of a statement are evaluated from left to right, each once, before anything from the statement is written. When the evaluation or the rendering of a hole faults, nothing from that statement is written; what earlier statements wrote stays written [LS-197].\n9. <a id=\"LS-195\"></a>The bytes written depend only on the values and the holes. They do not depend on locale, host operating system or executor: digits are the ASCII digits and the minus sign is `-` (U+002D) [LS-195].\n\n**Examples**\n\n10. This example shows plain holes, holes that print their own text with `=`, a format specification, a conditional expression in parentheses and doubled braces:\n\n```cint holes.ci\nI64 n = 5;\nI64 x = 7;\nBool ok = true;\n\"{n} {n=} {n + 1 =} {n=:>4} {(ok ? n : x)} {{literal}}\\n\";\n```\n\n```text\n5 n=5 n + 1 =6 n=   5 5 {literal}\n```\n\n11. A conditional expression needs parentheses:\n\n```cint hole_cond.ci\nBool ok = true;\n\"{ok ? 1 : 2}\\n\";\n```\n\n```text\nerror[C1035]: invalid character or string literal\n  --> hole_cond.ci:2:3\n...\n```\n\n12. A fault in a hole writes nothing from its statement:\n\n```cint hole_fault.ci\nI64 x = I64.max;\n\"before\\n\";\n\"a {x} b {x + 1} c\\n\";\n```"
  },
  {
   "id": "spec-04p:holes-p2",
   "edition": "SPEC-04P.2",
   "title": "7.5.1 Holes (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#holes",
   "internal": 0,
   "content": "```text\nbefore\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> hole_fault.ci:3:13\n   |\n 3 | \"a {x} b {x + 1} c\\n\";\n   |             ^ add.checked.i64\n   ...\n```"
  },
  {
   "id": "spec-04p:default-rendering",
   "edition": "SPEC-04P.2",
   "title": "7.5.2 Default rendering",
   "clauses": "IM-90 LS-207 LS-214",
   "url": "/specifications/spec-04p/2/#default-rendering",
   "internal": 0,
   "content": "#### 7.5.2 Default rendering\n\nEach type has one default text, the one a hole without a specification prints.\n\n**Semantics**\n\n1. <a id=\"IM-90\"></a><a id=\"LS-214\"></a>An integer of any width prints as its exact value in decimal: a `-` before a negative value, no sign before any other, no leading zeros and no grouping. `I1024` and `U512` values print every digit [IM-90, LS-214].\n2. <a id=\"LS-207\"></a>A fixed-point value prints as the shortest exact decimal expansion of its value with at least one digit after the point: `3.0`, `-0.25`. The value `A / 2^f` of a `Q<i>.<f>` always has a terminating decimal expansion of at most `f` fractional digits, so the default rendering is always exact [IM-90, LS-207, LS-214].\n3. A `Bool` prints as `true` or `false` [IM-90, LS-214].\n4. A rank-1 array or view prints as `[`, its elements in order separated by `, `, then `]`, every element, each rendered as the hole specifies [LS-214].\n\n**Examples**\n\n5. This example shows integers of every width:\n\n```cint render_int.ci\nI8 a = -128;\nU64 b = U64.max;\nI128 c = I128.min;\nI1024 d = I1024.max;\n\"{a} {b} {c}\\n{d}\\n\";\n```\n\n```text\n-128 18446744073709551615 -170141183460469231731687303715884105728\n89884656743115795386465259539451236680898848947115328636715040578866337902750481566354238661203768010560056939935696678829394884407208311246423715319737062188883946712432742638151109800623047059726541476042502884419075341171231440736956555270413618581675255342293149119973622969239858152417678164812112068607\n```\n\n6. This example shows unsigned wide types:\n\n```cint render_unsigned_wide.ci\nU128 a = U128.max;\nU256 b = 1 << 200;\n\"{a}\\n{b}\\n\";\n```\n\n```text\n340282366920938463463374607431768211455\n1606938044258990275541962092341162602522202993782792835301376\n```\n\n7. This example shows fixed point. The smallest positive `Q32.32` value, `2^-32`, needs 32 fractional digits:"
  },
  {
   "id": "spec-04p:default-rendering-p1",
   "edition": "SPEC-04P.2",
   "title": "7.5.2 Default rendering (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#default-rendering",
   "internal": 0,
   "content": "```cint render_fixed.ci\nQ32.32 a = 1.5;\nQ32.32 b = 3;\nQ32.32 c = Q32.32.raw(1);\nQ16.16 d = -0.25;\n\"{a} {b} {d}\\n{c}\\n\";\n```\n\n```text\n1.5 3.0 -0.25\n0.00000000023283064365386962890625\n```\n\n8. This example shows arrays and views:\n\n```cint render_array.ci\nvoid show() {\n    I32[3] a = [1, -2, 3];\n    Bool[2] f = [true, false];\n    \"{a} {a[1..]} {f} {a:+}\\n\";\n}\nshow();\n```\n\n```text\n[1, -2, 3] [-2, 3] [true, false] [+1, -2, +3]\n```"
  },
  {
   "id": "spec-04p:format-specifications",
   "edition": "SPEC-04P.2",
   "title": "7.5.3 Format specifications",
   "clauses": "LS-202 LS-206 LS-213",
   "url": "/specifications/spec-04p/2/#format-specifications",
   "internal": 0,
   "content": "#### 7.5.3 Format specifications\n\nA format specification, after the `:` of a hole, controls the width and alignment of the text, the sign, the base, digit grouping, the number of fractional digits of a fixed-point value, and the scale of an integer printed as a decimal fraction. Its syntax follows Python's format specification mini-language; where the two differ, the rules here apply.\n\n**Syntax**\n\n```ebnf\nspec      = [ [ fill ] align ] [ sign ] [ \"#\" ] [ \"0\" ] [ width ] [ group ]\n            [ \".\" precision ] [ kind ] [ \"/\" scale ] ;\nfill      = (* any Unicode scalar value other than \"}\" *) ;\nalign     = \"<\" | \">\" | \"^\" ;\nsign      = \"-\" | \"+\" | \" \" ;\nwidth     = digit { digit } ;\ngroup     = \"_\" | \",\" ;\nprecision = digit { digit } ;\nkind      = \"d\" | \"x\" | \"X\" | \"o\" | \"b\" | \"t\" | \"c\" ;\nscale     = \"1\" \"0\" { \"0\" } ;\ndigit     = \"0\" .. \"9\" ;\n```\n\n**Constraints**\n\n1. <a id=\"LS-202\"></a>The digits of `width`, `precision` and `scale` are the ASCII digits `0` to `9`. A specification that does not match the syntax, including a digit of another script, is diagnosed C1037 [LS-202].\n2. <a id=\"LS-213\"></a>A specification shall apply to the type of the value. Each of these is diagnosed C1037 [LS-213]:\n   - a precision on an integer;\n   - on `Bool`, anything but fill, alignment and width;\n   - with `t`: `#`, a sign flag, `0` or a group;\n   - with `c`: `#`, `0`, a group or a sign flag;\n   - `,` with `x`, `X`, `o` or `b`;\n   - `#` with `d` or with the default decimal kind;\n   - a width with neither an alignment nor the `0` flag;\n   - the `0` flag together with an alignment or a group;\n   - a scale together with a kind other than `d`, with `#`, with a group, or with a conversion;\n   - on a fixed-point value, a kind, a scale or `#`.\n3. <a id=\"LS-206\"></a>A precision together with a scale is diagnosed C1036 [LS-206, LS-213].\n\n**Semantics**"
  },
  {
   "id": "spec-04p:format-specifications-p1",
   "edition": "SPEC-04P.2",
   "title": "7.5.3 Format specifications (part 2)",
   "clauses": "LS-202 LS-203 LS-204 LS-205 LS-206 LS-208 LS-209 LS-210 LS-211 LS-212",
   "url": "/specifications/spec-04p/2/#format-specifications",
   "internal": 0,
   "content": "4. <a id=\"LS-211\"></a><a id=\"LS-212\"></a>*Width, fill and alignment.* `width` is the minimum length of the text in Unicode scalar values. A shorter text is padded with the fill character, a space by default: after the text for `<`, before it for `>`, and on both sides for `^`, with the extra character, when the padding is odd, on the right. A text longer than the width is never truncated. Width and alignment apply to every rendering, `Bool` included and to each element of an array, not to the array as a whole [LS-202, LS-211, LS-212].\n5. *Sign.* `-` prints a sign before negative values only, the default. `+` prints `+` before zero and positive values. A space prints a space before them [LS-202].\n6. *Zero padding.* The `0` flag with a width pads with `0` digits between the sign, or the radix prefix, and the digits, to the width [LS-202].\n7. <a id=\"LS-203\"></a><a id=\"LS-204\"></a>*Kinds.* An integer prints by its mathematical value in every kind, with `-` before a negative value: `{-255:x}` is `-ff`. `d` is decimal, the default; `x` and `X` are hexadecimal with lowercase or uppercase digits; `o` is octal; `b` is binary. With `#`, the prefix `0x`, `0o` or `0b` precedes the digits, always in lowercase, so `{255:#X}` is `0xFF`. The storage bit pattern of a negative value is printed only through the `!bits` conversion of 7.5.4 [LS-202, LS-203, LS-204].\n8. *Groups.* `_` separates every three digits in decimal and every four in `x`, `X`, `o` and `b`, counted from the right; `,` separates every three digits in decimal [LS-202].\n9. <a id=\"LS-205\"></a>*Balanced ternary.* `t` prints the shortest `0t` literal (6.4.5) of the value: the prefix `0t`, then the digits `N`, `0` and `P` for -1, 0 and 1, most significant first, with no leading `0` digit; the sign is carried by the digits. `{8:t}` is `0tP0N`, `{-8:t}` is `0tN0P` and `{0:t}` is `0t0`. The text is always a valid literal of th"
  },
  {
   "id": "spec-04p:format-specifications-p2",
   "edition": "SPEC-04P.2",
   "title": "7.5.3 Format specifications (part 3)",
   "clauses": "LS-209",
   "url": "/specifications/spec-04p/2/#format-specifications",
   "internal": 0,
   "content": "**Faults**\n\n14. The fault `E_NARROW` is raised by a hole of kind `c` whose value is not a Unicode scalar value: a negative value, a surrogate code point from U+D800 to U+DFFF, or a value above U+10FFFF. The record holds the operation identifier `format.char.t`, the value as its one operand and as the exact result, and no limit. Its position is the first character of the hole expression [LS-209].\n\n**Examples**\n\n15. This example shows width, fill, alignment and sign:\n\n```cint spec_layout.ci\nI64 p = 42;\nI64 n = -42;\nI64 z = 0;\nBool ok = true;\n\"[{n}] [{z:+}] [{p: }] [{n:08}] [{p:>6}] [{p:<6}] [{p:*^7}] [{ok:>7}]\\n\";\n```\n\n```text\n[-42] [+0] [ 42] [-0000042] [    42] [42    ] [**42***] [   true]\n```\n\n16. This example shows bases, prefixes and groups:\n\n```cint spec_bases.ci\nI64 h = 255;\nI64 m = -255;\nU32 w = 0xDEADBEEF;\nI64 big = 1234567;\n\"[{h:x}] [{h:#X}] [{m:x}] [{h:o}] [{h:#b}] [{w:#_x}] [{big:_}] [{big:,}] [{m:#010x}]\\n\";\n```\n\n```text\n[ff] [0xFF] [-ff] [377] [0b11111111] [0xdead_beef] [1_234_567] [1,234,567] [-0x00000ff]\n```\n\n17. This example shows balanced ternary and scaled integers:\n\n```cint spec_ternary_scale.ci\nI64 e = 8;\nI64 m = -8;\nI64 money = 123456;\nI64 cents = -5;\nI64 low = I64.min;\n\"[{e:t}] [{m:t}] [{e:*^9t}] [{money:/100}] [{cents:/100}] [{money:+010/100}]\\n\";\n\"{low:/100}\\n\";\n```\n\n```text\n[0tP0N] [0tN0P] [**0tP0N**] [1234.56] [-0.05] [+001234.56]\n-92233720368547758.08\n```\n\n18. A specification that does not apply is found during translation:\n\n```cint spec_mismatch.ci\nI64 n = 42;\n\"{n:.3}\\n\";\n```\n\n```text\nerror[C1037]: invalid format specification\n  --> spec_mismatch.ci:2:3\n...\n```\n\n19. This example shows characters. 233 is U+00E9, `\u00e9`:\n\n```cint spec_char.ci\nI64 c = 233;\n\"[{c:c}] [{c:>3c}]\\n\";\n```\n\n```text\n[\u00e9] [  \u00e9]\n```\n\n20. Precision on fixed point rounds ties to even and never prints `-0`:"
  },
  {
   "id": "spec-04p:format-specifications-p3",
   "edition": "SPEC-04P.2",
   "title": "7.5.3 Format specifications (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#format-specifications",
   "internal": 0,
   "content": "```cint spec_precision.ci\nQ32.32 a = 0.125;\nQ32.32 b = 0.375;\nQ32.32 c = -0.03125;\nQ32.32 d = 1.5;\n\"{a:.2} {b:.2} {c:.1} {d:.0} {d:>8} {d:+.3}\\n\";\n```\n\n```text\n0.12 0.38 0.0 2      1.5 +1.500\n```"
  },
  {
   "id": "spec-04p:format-conversions",
   "edition": "SPEC-04P.2",
   "title": "7.5.4 Conversions",
   "clauses": "LS-201 LS-213",
   "url": "/specifications/spec-04p/2/#format-conversions",
   "internal": 0,
   "content": "#### 7.5.4 Conversions\n\nA conversion, after the `!` of a hole, prints a value through another reading of the same bits: the two's complement pattern of an integer, the storage integer of a fixed-point value, or an integer split into lanes.\n\n**Constraints**\n\n1. <a id=\"LS-201\"></a>`!bits` applies to integers and to fixed-point values, `!raw` to fixed-point values only and `!lanes(T)` to integers only, with `T` an unsigned type whose width divides the width of the value. Any other use, any conversion applied to `Bool`, `!ratio` applied to an integer and `!bits` together with the kind `t` or `c`, are diagnosed C1037 [LS-201, LS-213].\n\n**Semantics**\n\n2. `!bits` gives the two's complement bit pattern of the value as an unsigned integer of the same width: for `I8` -1 it is 255. On a fixed-point value it is the pattern of the storage integer. With `x`, `X`, `o` or `b`, the digits are padded with zeros to the full width of the type [LS-201].\n3. `!raw` gives the storage integer of a fixed-point value, a signed integer, as `x.raw` does (6.3.2). The format specification then applies with the rules of integers [LS-201].\n4. `!lanes(T)` splits the bit pattern of the value into lanes of the width of `T`, lane 0 the least significant and prints them as an array of `T` values, lane 0 first. The format specification applies to each lane [LS-201].\n\n5. The conversion name `ratio` is reserved, and this edition gives `!ratio` no meaning. Applied to an integer or to `Bool` it is diagnosed C1037 (paragraph 1); applied to a fixed-point value, an implementation refuses the program (3.16) [LS-201].\n\n**Examples**\n\n6. This example shows `!bits`, `!lanes` and `!raw` on integers and on a fixed-point value:"
  },
  {
   "id": "spec-04p:format-conversions-p1",
   "edition": "SPEC-04P.2",
   "title": "7.5.4 Conversions (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#format-conversions",
   "internal": 0,
   "content": "```cint conversions.ci\nI8 m1 = -1;\nI8 low = -128;\nI64 n = -42;\nU32 w = 0x12345678;\nQ8.8 q = -2.5;\n\"[{m1!bits}] [{m1!bits:x}] [{low!bits:#b}] [{n!bits:x}]\\n\";\n\"[{w!lanes(U8):02x}] [{w!lanes(U16)}] [{w=!lanes(U8)}]\\n\";\n\"[{q!raw}] [{q!raw:x}] [{q!bits:x}]\\n\";\n```\n\n```text\n[255] [ff] [0b10000000] [ffffffffffffffd6]\n[[78, 56, 34, 12]] [[22136, 4660]] [w=[120, 86, 52, 18]]\n[-640] [-280] [fd80]\n```\n\n**Notes**\n\n7. C's `printf(\"%x\", -1)` reinterprets a negative value as unsigned without saying so. In cint, `{-1:x}` prints `-1`, and the pattern `ffffffffffffffff` appears only when the hole asks for it with `!bits`."
  },
  {
   "id": "spec-04p:debugging",
   "edition": "SPEC-04P.2",
   "title": "8 Faults, agreement and debugging",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#debugging",
   "internal": 0,
   "content": "## 8 Faults, agreement and debugging\n\nThis clause explains how to find out why a program did what it did. 8.1 reads the record that a fault produces, field by field. 8.2 states which outcomes of a run are identical on every implementation, executor and machine and how to compare two runs. 8.3 shows how saved outputs and tests detect a change of behavior. 8.4 describes checkpoints, recordings and replay and 8.5 introduces the debug tools through a first session. What a fault is, and the state a fault leaves, are in 5.2.3; fuel and call depth are in 5.2.4 and 5.2.5."
  },
  {
   "id": "spec-04p:fault-record",
   "edition": "SPEC-04P.2",
   "title": "8.1 The fault record",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#fault-record",
   "internal": 0,
   "content": "### 8.1 The fault record\n\nA fault stops the entry that raised it (5.2.3) and produces one fault record: a fixed set of fields that say what failed, with which values, where, and in which program. The record holds no time, no memory address and no name of an executor, so every conforming implementation produces, for the same fault, a record equal in every field except `revision` and `source-map` (8.2). Every tool prints the record in one layout, the *fault report*.\n\n**Semantics**"
  },
  {
   "id": "spec-04p:fault-record-p1",
   "edition": "SPEC-04P.2",
   "title": "8.1 The fault record (part 2)",
   "clauses": "IM-106 LS-278",
   "url": "/specifications/spec-04p/2/#fault-record",
   "internal": 0,
   "content": "1. <a id=\"IM-106\"></a>A fault produces exactly one fault record. Its fields are [IM-106, LS-278]:\n   - `code`: the fault code (Annex B).\n   - `operation`: the operation identifier of the operation that faulted, such as `add.checked.i64`, at most 64 ASCII characters (Annex B).\n   - `operands`: every operand of that operation as a typed value, exact and never rounded or shortened, in source order; at most 8.\n   - `exact`: the value that failed the range check. For an operation that does not round, it is the exact result (3.4). For an operation that rounds, such as `muldiv`, `div_round` or a conversion with a `round` clause, it is the value after the operation's one rounding. A record of `E_OVERFLOW` or `E_NARROW` has it; a record of another code has none unless the subclause of its operation gives one.\n   - `limit`: the bound that was crossed: `MIN(T)` or `MAX(T)` of the result type, the largest permitted shift count, the extent of the indexed dimension, the fuel allowance or the depth limit. A record with no bound to cross, such as one of `E_DIV_ZERO`, has none.\n   - `position`: the module-relative path of the source file, such as `month.ci`, the line and the column, both counted from 1 and the column counted in Unicode scalar values, of the operator token or of the callee's name for a call.\n   - `revision`: the revision (3.31) of the program to which the position refers.\n   - `source-map`: the digest of the program's *source map*, the table that gives the line and column of each fault site. The revision leaves source positions out, so an edit that only moves code, such as reformatting, keeps the revision; this field is the one that ties the record's positions to the source text they were taken from. SPEC-01P.2 defines the digest and the encoding of the whole record.\n   - `address`: present only for a fault inside a kernel dispatch (paragraph 4).\n   - `stack`: the call"
  },
  {
   "id": "spec-04p:fault-record-p2",
   "edition": "SPEC-04P.2",
   "title": "8.1 The fault record (part 3)",
   "clauses": "IM-107 IM-111 IM-112",
   "url": "/specifications/spec-04p/2/#fault-record",
   "internal": 0,
   "content": "2. <a id=\"IM-107\"></a>The `stack` field holds one position for each active call of a user function: the position of the callee's name at that call, outermost call first. The entry (3.20) is called by the host, not by program code, so it contributes no position: a fault in the entry's own code has an empty stack, and a fault `k` calls below the entry has `k` positions. A call that faults `E_DEPTH` is not entered; its position is the record's `position` and is not in the stack, so under a depth limit `D` the stack has at most `D - 1` positions [IM-107].\n\n3. <a id=\"IM-111\"></a>The record never holds a native memory address, register contents, the time of day, a thread identifier or the name of the executor that ran the program. A tool may print such things beside the record, marked as not part of it [IM-111].\n\n4. <a id=\"IM-112\"></a>An entry faults at most once. In sequential code the fault is the first in evaluation order (6.2.4). In a kernel dispatch several work-items can reach a fault; the record describes the *canonical fault*, the one that is least in this order [IM-112]:\n   - the *dispatch number*, which counts the dispatches of the current entry from 0 in program order and starts again at 0 in each entry;\n   - the *phase*: 0 for the checks made when the dispatch begins, 1 for the work-items, 2 for the reduction epilogue that follows them (6.13);\n   - in phase 1, the *work-item index*, the row-major position of the work-item in the iteration space: in `kernel K[n, m]`, work-item `(i, j)` has index `i * m + j`;\n   - in phase 1, the step ordinal of paragraph 5.\n\n   The `address` field holds the kernel's qualified name and these numbers; in phases 0 and 2 it has no work-item index and no step ordinal. Sequential code has no address."
  },
  {
   "id": "spec-04p:fault-record-p3",
   "edition": "SPEC-04P.2",
   "title": "8.1 The fault record (part 4)",
   "clauses": "IM-113 IM-114 IM-115",
   "url": "/specifications/spec-04p/2/#fault-record",
   "internal": 0,
   "content": "5. <a id=\"IM-113\"></a>The *step ordinal* numbers the counted operations that a work-item evaluates, from 0, in evaluation order, including those inside the functions it calls. The step ordinal of a fault is the ordinal of the operation that faulted. Each evaluation of these operations is counted: every arithmetic operator in each of its plain, wrapping and saturating forms, the shifts and unary `-` included; every conversion; every subscript and every slice, whether it reads or is the place of a store; every call of a built-in operation of clause 7; and every call of a user function, counted at the call, before the callee's own operations. Literals, reads of variables, comparisons, the bitwise operators `&`, `|`, `^` and `~`, the logical operators, the conditional operator itself, loop control and fuel charges are not counted [IM-113].\n\n6. <a id=\"IM-114\"></a>An operation is counted even when the compiler has proved that it cannot fault, and however it is compiled. In the kernel body `out[i] = a[i] + b[i] * c[i];`, with the `+` overflowing, the place `out[i]` is step 0, because the place is evaluated first, `a[i]` is 1, `b[i]` 2, `c[i]` 3, `*` 4 and `+` 5, so the step ordinal is 5 [IM-114].\n\n7. <a id=\"IM-115\"></a>The canonical order is a definition, not a statement about which processor lane failed first. Every executor reports the canonical fault, in whatever order it ran the work-items; SPEC-02P.1 states how an executor that runs work-items in parallel finds it [IM-115]."
  },
  {
   "id": "spec-04p:fault-record-p4",
   "edition": "SPEC-04P.2",
   "title": "8.1 The fault record (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#fault-record",
   "internal": 0,
   "content": "8. Every tool prints a fault record as a fault report, in this layout:\n   - the line `fault[CODE]:` followed by a fixed message for the code;\n   - the line `-->` followed by the position;\n   - the source line, with a caret under the operator token and the operation identifier beside it;\n   - one line for each field of the record, in this order: `operation`, `operand-count`, one `operand` line for each operand, `exact`, `limit`, `revision`, `source-map`, `address` and `stack-depth`, then one `called from` line for each position of the stack, outermost first. A field that is absent reads `none`;\n   - two lines that are not part of the record: `fuel-consumed`, the fuel the entry consumed before the fault, and `state`, which says what the fault left (5.2.3).\n\n   An operand and the limit are written as the name of their type and their value in decimal, such as `I8 127`. A fixed-point value is written with its raw value (6.3.2): the type, the word `raw` and the raw value, so 300.75 of type `Q16.16` reads `Q16.16 raw 19709952`. A value in Z, such as the operand of a conversion decided during translation (6.6), reads `Z 300`. The exact result is written as a decimal integer alone; when the result type of the operation is a fixed-point type, it is a raw value.\n\n   `cint run` writes the program's output to the standard output and the report to the standard error. With `--json` it writes the same fields as one JSON object (8.2, Example 8)."
  },
  {
   "id": "spec-04p:fault-record-p5",
   "edition": "SPEC-04P.2",
   "title": "8.1 The fault record (part 6)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#fault-record",
   "internal": 0,
   "content": "9. The session tools `cint workbench` and `cint debug` (8.5) print further lines after `state`, under the line `= noncanonical: not part of the fault record`: `stack-source`, the source line of each position of the stack; `work-item-tuple`, the index of a faulting work-item as a tuple; `workbench-position`, the entry or boundary of the session (8.4); `site`, the identifier that `cint explain` gives the operation that faulted (8.5); and `backend`, the executor that ran the entry. None of these lines is part of the record.\n\n**Examples**\n\n10. This example shows a deposit that does not fit. The fourth amount added to the total exceeds `I64.max`:\n\n```cint month.ci\n// month.ci: four deposits in whole cents; the last one is too large.\nI64 add_cents(I64 total, I64 cents) {\n    return total + cents;\n}\n\nI64 month() {\n    I64[4] amounts = [1999, 425, 10, 9223372036854775000];\n    I64 total = 0;\n    for i in 0..4 {\n        total = add_cents(total, amounts[i]);\n        \"after deposit {i}: {total}\\n\";\n    }\n    return total;\n}\n\nI64 m = month();\n\"month: {m}\\n\";\n```\n\n```text\nafter deposit 0: 1999\nafter deposit 1: 2424\nafter deposit 2: 2434\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> month.ci:3:18\n   |\n 3 |     return total + cents;\n   |                  ^ add.checked.i64\n   |\n   = operation: add.checked.i64\n   = operand-count: 2\n   = operand: I64 2434\n   = operand: I64 9223372036854775000\n   = exact:   9223372036854777434\n   = limit:   I64 9223372036854775807\n...\n   = source-map: none\n   = address: none\n   = stack-depth: 2\n   = called from: month.ci:16:9\n   = called from: month.ci:10:17\n   = fuel-consumed: 10 (not part of the fault record)\n   = state: the program stopped; stdout holds what it wrote before the fault\n```\n\nThe report, read from the top:"
  },
  {
   "id": "spec-04p:fault-record-p6",
   "edition": "SPEC-04P.2",
   "title": "8.1 The fault record (part 7)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#fault-record",
   "internal": 0,
   "content": "| Line | What it says here |\n|---|---|\n| `after deposit ...` | The program's own output: three lines written before the fault, on the standard output. The report follows on the standard error. |\n| `fault[E_OVERFLOW]` | The fault code, then the fixed message for that code. |\n| `--> month.ci:3:18` | The position: file `month.ci`, line 3, the 18th character of the line, which is the `+` of `total + cents`. |\n| excerpt | Line 3 of the source, a caret under the `+`, and the operation beside it. |\n| `operation` | `add.checked.i64`, the checked `+` of two `I64` values. |\n| `operand-count`, `operand` | Two operands in source order: `total`, which is 2434 after three deposits, and `cents`, the fourth amount. The record holds values, not names. |\n| `exact` | The sum of the operands in Z, which `I64` cannot hold. |\n| `limit` | `I64.max`, the bound that the exact result crossed. |\n| `revision` | Left out above: 64 hexadecimal digits that identify the program (3.31). |\n| `source-map` | The field for the digest of the source map (paragraph 1). cint 0.2.0 records none, so it reads `none`. |\n| `address` | `none`: the fault is not inside a kernel dispatch. |\n| `stack-depth`, `called from` | Two active calls, outermost first. The script's top-level statements are the entry and add no position; they call `month` at `month.ci:16:9`, and `month` calls `add_cents` at `month.ci:10:17`. |\n| `fuel-consumed` | 10: 1 when the entry begins, 1 for the call of `month`, 4 for the iterations of the loop and 4 for the calls of `add_cents` (5.2.4). |\n| `state` | What the fault left: the program stopped, and its output holds what it wrote before the fault (5.2.3). |\n\n11. A rounding operation records the rounded value as its exact result. `muldiv` forms `I64.max * 3`, divides it by 2 and rounds the quotient once, half up, to 13835058055282163711 (7.2.3); that value fails the range check:"
  },
  {
   "id": "spec-04p:fault-record-p7",
   "edition": "SPEC-04P.2",
   "title": "8.1 The fault record (part 8)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#fault-record",
   "internal": 0,
   "content": "```cint rounded.ci\n// rounded.ci: a price raised by half, rounded half up to a whole cent.\nI64 raise(I64 cents) {\n    return muldiv(I64, cents, 3, 2, half_up);\n}\n\n\"{raise(5)}\\n\";\n\"{raise(I64.max)}\\n\";\n```\n\n```text\n8\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> rounded.ci:3:12\n   |\n 3 |     return muldiv(I64, cents, 3, 2, half_up);\n   |            ^ muldiv.checked.i64.i64.half_up\n   |\n   = operation: muldiv.checked.i64.i64.half_up\n   = operand-count: 3\n   = operand: I64 9223372036854775807\n   = operand: I64 3\n   = operand: I64 2\n   = exact:   13835058055282163711\n   = limit:   I64 9223372036854775807\n...\n```\n\nThe position of a call of a built-in operation is the callee's name: `rounded.ci:3:12` is the first letter of `muldiv`.\n\n12. An index fault has the index as its operand and the extent of the array as its limit. It has no exact result:\n\n```cint lookup.ci\n// lookup.ci: a rate for each quarter, indexed from 0.\nI64 rate(I64 quarter) {\n    I64[4] rates = [5, 6, 7, 8];\n    return rates[quarter];\n}\n\n\"{rate(3)}\\n\";\n\"{rate(4)}\\n\";\n```\n\n```text\n8\nfault[E_BOUNDS]: index out of bounds\n  --> lookup.ci:4:17\n   |\n 4 |     return rates[quarter];\n   |                 ^ index.checked.i64\n   |\n   = operation: index.checked.i64\n   = operand-count: 1\n   = operand: I64 4\n   = exact:   none\n   = limit:   I64 4\n...\n```\n\n13. A fault in a kernel has an address. Work-items 2 and 4 of this dispatch both overflow; the record describes work-item 2. The reference writes the same record as lines of text (SPEC-09P.1):\n\n```console\n$ cat scale.ci\n// scale.ci: one work-item per element; work-items 2 and 4 overflow I32.\nkernel scale[n](in I32[n] xs, out I32[n] ys) over [i: n] {\n    ys[i] = xs[i] * 1000;\n}\n\nvoid run() {\n    I32[5] xs = [5, 7, 3000000, 4, 2500000];\n    I32[5] ys;\n    scale(xs, ys);\n    \"{ys[0]}\\n\";\n}"
  },
  {
   "id": "spec-04p:fault-record-p8",
   "edition": "SPEC-04P.2",
   "title": "8.1 The fault record (part 9)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#fault-record",
   "internal": 0,
   "content": "\"start\\n\";\nrun();\n$ cint run scale.ci\nstart\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> scale.ci:3:19\n   |\n 3 |     ys[i] = xs[i] * 1000;\n   |                   ^ mul.checked.i32\n   |\n   = operation: mul.checked.i32\n   = operand-count: 2\n   = operand: I32 3000000\n   = operand: I32 1000\n   = exact:   3000000000\n   = limit:   I32 2147483647\n   = revision: f9a1803eff0a14c869489fb3338645e1219abaca73514174cccd7463a5a4710c\n   = source-map: none\n   = address: scale.scale, dispatch 0, phase 1, work-item 2, step 2\n   = stack-depth: 2\n   = called from: scale.ci:14:1\n   = called from: scale.ci:9:5\n   = fuel-consumed: 7 (not part of the fault record)\n   = state: the program stopped; stdout holds what it wrote before the fault\n$ python3 -m cint_ref run --format 4 scale.ci\ncase scale\nformat 4\nsource reference\noutcome fault\nstdout-bytes 6\nstdout-sha256 46210dddc66714c3d8d226711510cf8421774214016c508c72a833a05370f6b5\nfuel-consumed 7\nfault.code E_OVERFLOW\nfault.operation mul.checked.i32\nfault.operand I32 3000000\nfault.operand I32 1000\nfault.exact 3000000000\nfault.limit I32 2147483647\nfault.position scale.ci:3:19\nfault.revision self\nfault.source-map self\nfault.phase work-item\nfault.kernel scale.scale\nfault.address 0 2 2\nfault.stack-depth 2\nfault.stack scale.ci:14:1\nfault.stack scale.ci:9:5\n```"
  },
  {
   "id": "spec-04p:fault-record-p9",
   "edition": "SPEC-04P.2",
   "title": "8.1 The fault record (part 10)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#fault-record",
   "internal": 0,
   "content": "The address reads: kernel `scale` of module `scale`; dispatch 0, the first of the entry; phase 1, the work-items; work-item 2, whose element 3000000 times 1000 is 3000000000. Work-item 4 would fault as well, but 2 is the lower index. The step ordinal is 2: in `ys[i] = xs[i] * 1000;` the place `ys[i]` is step 0, `xs[i]` step 1 and the `*` step 2. The dispatch `scale(xs, ys)` at line 9 is a position of the stack, as a call is. The reference writes the phase by name and the address as the dispatch number, the work-item index and the step ordinal, and writes `self` for the revision and the source map, which it does not compute (8.2).\n\n**Notes**\n\n14. A report is read in three steps. The position and the excerpt show which operation failed. The operands and the exact result show why: which values were combined, and how far the result lies outside the type. The stack shows how the program reached that operation, from the outermost call inward.\n\n15. After the source is edited, a saved report can point at a line that now holds other code. The revision changes with every change of the compiled program, so a report whose revision differs from the program's belongs to other code. An edit that only moves code, such as reformatting, changes positions but not the revision; that is what the `source-map` field is for (paragraph 1).\n\n16. The `fuel-consumed` line is not part of the record, but the fuel an entry consumes is one of the outcomes on which every implementation agrees (8.2).\n\n17. cint 0.2.0 records no source map in the `source-map` field of a fault record: every report of 0.2.0 prints `none` there. A recording and a case name the digest of the source map in their header (8.4), and `cint debug replay` prints it (8.5)."
  },
  {
   "id": "spec-04p:agreement",
   "edition": "SPEC-04P.2",
   "title": "8.2 Determinism and agreement",
   "clauses": "IM-159",
   "url": "/specifications/spec-04p/2/#agreement",
   "internal": 0,
   "content": "### 8.2 Determinism and agreement\n\nA cint run has no hidden inputs. Given the same semantic inputs (3.24), every conforming implementation, on every executor and machine, writes the same output bytes, ends with no fault record or with one that is equal in every field except `revision` and `source-map` (paragraph 3), and consumes the same fuel. This subclause states exactly which outcomes are identical, what is not covered and how to compare two runs.\n\n**Semantics**\n\n1. <a id=\"IM-159\"></a>The outcome of an entry is decided by its *execution identity*, the tuple of [IM-159]:\n   - the language profile and the fuel model;\n   - the revision of the program and the digest of its source map;\n   - the entry, and its arguments;\n   - the state before the entry;\n   - the effects the host supplied to the entry (paragraph 2);\n   - the fuel allowance, the call-depth limit and the frame-arena capacity.\n\n   Two runs with equal execution identity *agree* when they produce equal:\n   - state after the entry;\n   - return value, or the absence of one;\n   - fault record, or the absence of one;\n   - fuel consumed by the entry;\n   - *effect-request trace*: the ordered list of the requests the entry made of the host, each with its ordinal, call site, name and arguments, together with the bytes of every print.\n\n   A program's output is the bytes of its print requests, in order, so two runs that agree write the same output bytes, including the bytes written before a fault. Each item is compared through the encoding and digest that SPEC-01P.2 gives it."
  },
  {
   "id": "spec-04p:agreement-p1",
   "edition": "SPEC-04P.2",
   "title": "8.2 Determinism and agreement (part 2)",
   "clauses": "IM-160",
   "url": "/specifications/spec-04p/2/#agreement",
   "internal": 0,
   "content": "2. <a id=\"IM-160\"></a>The effects the host supplied are its answers to the entry's requests, in order: the status of each, its result, and the contents it wrote into the program's arrays. The requests the entry sent out are not among them. In this document \"deterministic\" means only this: equal execution identity gives the five equal outcomes of paragraph 1. Host time, thread scheduling, memory addresses and host effects that were not recorded are not inputs of an entry, so none of them can change an outcome. A conforming implementation agrees with the reference on every execution in the scope of both, except in the `revision` and `source-map` fields of a fault record (paragraph 3). An entry ended by a failure of host resources, such as the host running out of memory, has no execution identity, and this paragraph says nothing about it. The *build identity* of a compiled program, which names the executable or kernel binary that a build produced, is separate: an x86-64 executable and a CUDA kernel binary of the same program have different build identities and the same revision. Agreement says nothing about whether a program's integer results are numerically adequate for the problem it models, for example in place of a floating-point computation; that is a separate question with its own evidence [IM-160]."
  },
  {
   "id": "spec-04p:agreement-p2",
   "edition": "SPEC-04P.2",
   "title": "8.2 Determinism and agreement (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#agreement",
   "internal": 0,
   "content": "3. A program is in the scope of both the reference and a compiler when the reference runs it and the compiler builds it without a refusal (4, paragraph 4). For such a program and the same semantic inputs, the compiled program and the reference write the same output bytes, consume the same fuel and end with fault records equal in every field except `revision` and `source-map`, which the reference does not compute and writes as `self`. A disagreement is a defect of one of them or an ambiguity in this document, never a choice between them. Agreement on one program is a measurement of that program and shows nothing about another [SPEC-09P.1 REF-06].\n\n4. Every tool runs the same compiled form of a program: `cint run`, `cint test`, `cint workbench`, `cint debug`, `cint interp`, and every executor. No tool has arithmetic, fault or post-fault rules of its own. A difference between any two of them on the same semantic inputs is a defect.\n\n5. Observation does not change meaning. Inspecting, watching, tracing, checkpointing and recording never change the state of a run, its step ordinals, the fuel it consumes or its fault.\n\n**Examples**\n\n6. The reference is run as `python3 -m cint_ref` (SPEC-09P.1), and `--format 4` selects the text form of an outcome shown below. The output of `month.ci` (8.1, Example 10) has the same digest under `cint` and under the reference, and the reference ends with the same fault record:"
  },
  {
   "id": "spec-04p:agreement-p3",
   "edition": "SPEC-04P.2",
   "title": "8.2 Determinism and agreement (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#agreement",
   "internal": 0,
   "content": "```console\n$ cint run month.ci 2> /dev/null | sha256sum\n2f1ada714964d61a382d8867eb0903f28bca1dbc9d918982300c7f445df4f3df  -\n$ python3 -m cint_ref run --format 4 month.ci\ncase month\nformat 4\nsource reference\noutcome fault\nstdout-bytes 66\nstdout-sha256 2f1ada714964d61a382d8867eb0903f28bca1dbc9d918982300c7f445df4f3df\nfuel-consumed 10\nfault.code E_OVERFLOW\nfault.operation add.checked.i64\nfault.operand I64 2434\nfault.operand I64 9223372036854775000\nfault.exact 9223372036854777434\nfault.limit I64 9223372036854775807\nfault.position month.ci:3:18\nfault.revision self\nfault.source-map self\nfault.address none\nfault.stack-depth 2\nfault.stack month.ci:16:9\nfault.stack month.ci:10:17\n```\n\n`2> /dev/null` discards the report, so `sha256sum` reads the output alone. The reference's `stdout-sha256` is the same digest, of the same 66 bytes. Every field of its fault matches the report of 8.1, and so does the fuel consumed, 10.\n\n7. The fuel allowance is a semantic input. Given an allowance of 9, the same program has another outcome, and every implementation gives it: the tenth charge, for the fourth call of `add_cents`, faults `E_FUEL`. The record's position is that call, its limit is the allowance, and it has no operands and no exact result. The output is the same 66 bytes, because the fault comes after the third print:\n\n```console\n$ python3 -m cint_ref run --fuel 9 --format 4 month.ci\ncase month\nformat 4\nsource reference\noutcome fault\nstdout-bytes 66\nstdout-sha256 2f1ada714964d61a382d8867eb0903f28bca1dbc9d918982300c7f445df4f3df\nfuel-consumed 9\nfault.code E_FUEL\nfault.operation fuel.charge\nfault.exact none\nfault.limit I64 9\nfault.position month.ci:10:17\nfault.revision self\nfault.source-map self\nfault.address none\nfault.stack-depth 1\nfault.stack month.ci:16:9\n```\n\n8. With `--json`, `cint run` writes the record as one JSON object, after the program's output:"
  },
  {
   "id": "spec-04p:agreement-p4",
   "edition": "SPEC-04P.2",
   "title": "8.2 Determinism and agreement (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#agreement",
   "internal": 0,
   "content": "```console\n$ cint --json run month.ci\nafter deposit 0: 1999\nafter deposit 1: 2424\nafter deposit 2: 2434\n{\"address\":null,\"code\":\"E_OVERFLOW\",\"column\":18,\"exact\":{\"t\":\"Z\",\"v\":\"9223372036854777434\"},\"file\":\"month.ci\",\"limit\":{\"t\":\"I64\",\"v\":\"9223372036854775807\"},\"line\":3,\"noncanonical\":{\"fuel_consumed\":\"10\"},\"operands\":[{\"t\":\"I64\",\"v\":\"2434\"},{\"t\":\"I64\",\"v\":\"9223372036854775000\"}],\"operation\":\"add.checked.i64\",\"revision\":\"92b1e2717518c491d86f09d90528fa1930c049c76f2c4aad6f9e0392f84da4ac\",\"schema\":\"CINT-FAULT-1\",\"severity\":\"fault\",\"source_map\":null,\"stack\":[{\"column\":9,\"file\":\"month.ci\",\"line\":16},{\"column\":17,\"file\":\"month.ci\",\"line\":10}]}\n```\n\nThe key `schema` names the format, `CINT-FAULT-1`. Every value is a string of decimal digits beside its type, as in `{\"t\":\"I64\",\"v\":\"2434\"}`, so a JSON reader that converts numbers to binary floating point cannot change it; the exact result has the type `Z`. The key `revision` holds the program's revision, which the report of 8.1 left out. What is not part of the record is under `noncanonical`, here the fuel consumed.\n\n**Notes**"
  },
  {
   "id": "spec-04p:agreement-p5",
   "edition": "SPEC-04P.2",
   "title": "8.2 Determinism and agreement (part 6)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#agreement",
   "internal": 0,
   "content": "9. To compare a run A with a run B, for two implementations, two executors or two machines:\n   - Fix the semantic inputs: the same program text, so the same revision; the same input values; the same fuel allowance, depth limit and frame-arena capacity.\n   - Keep the output and the report apart: `cint run p.ci > a.out 2> a.err`.\n   - Compare the output bytes with `cmp` or a digest.\n   - Compare the reports from the `fault[` line through the last `called from` line, and the `fuel-consumed` line. Under `--json`, compare every key outside `noncanonical`, and `fuel_consumed` inside it.\n   - A difference in any of these is a defect of A or of B, not a property of the program. Reduce the program to the smallest one that still shows it. For two executors on one recorded run, `cint debug diff` makes this comparison at every boundary (8.5).\n\n10. Two agreeing runs can still differ in what is not an outcome: the time and memory they take, the files a build writes, the text of the `state` line, which each tool words for its own context, and the lines under `noncanonical`. The reference writes `self` where an implementation writes the revision and the source map.\n\n11. Agreement shows that two implementations give the same outcome, not that either outcome is what the programmer intended. Two implementations can agree and both be wrong. This document decides which outcome is correct, and the conformance suite checks it on many programs.\n\n12. In C, two compilers or one compiler at two optimization levels, can produce different output from one program whose behavior is undefined or unspecified, such as a signed overflow or an unsequenced modification. cint has no such behavior (Annex C), so a difference between two cint implementations is a defect of one of them or an ambiguity in this document (paragraph 3)."
  },
  {
   "id": "spec-04p:agreement-p6",
   "edition": "SPEC-04P.2",
   "title": "8.2 Determinism and agreement (part 7)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#agreement",
   "internal": 0,
   "content": "13. cint 0.2.0 has three executors (3.19): `cpu-c17`, which compiles the program to C; `cpu-sir-interp`, the interpreter `cint-interp`; and `gpu-cuda`, which runs kernels on NVIDIA GPUs."
  },
  {
   "id": "spec-04p:goldens",
   "edition": "SPEC-04P.2",
   "title": "8.3 Golden outputs and tests",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#goldens",
   "internal": 0,
   "content": "### 8.3 Golden outputs and tests\n\nA *golden* is an output saved from a run that has been checked once, kept with the program and compared byte for byte with the output of every subsequent run of the same program on the same inputs. A difference means that the program, or the implementation that runs it, changed behavior. Because every conforming implementation gives the same outcome (8.2), a golden made on one executor or machine checks a run on any other. A golden can be a saved output, compared with `diff`; the expectations written into a module's tests (6.15.3), checked by `cint test`; or the reference's record of a whole outcome, the fault included.\n\n**Semantics**\n\n1. `cint test FILE` runs every test of the module `FILE` (6.15.3), in source order, each from the module's initial state, and prints one line for each test: the word `test`, the file and line of the test, its name in quotes and `ok` or `FAILED`. A failed test is followed by its fault report, whose `state` line says that the test's output is not shown; when an `assert` on a comparison fails, the record's operands are the two sides of the comparison, exactly and with their types (6.10.9). The last line counts the tests that passed. Tests may run in parallel; the order and the results reported are those of running them one after another.\n\n**Examples**\n\n2. This example shows a program whose output is worth keeping. `div_round` rounds the tax on 200 cents, 16.5 cents, to the even cent (7.2):\n\n```cint invoice.ci\n// invoice.ci: tax at 8.25 percent on three subtotals, in whole cents.\nI64 tax(I64 subtotal) {\n    return div_round(subtotal * 825, 10000, half_even);\n}\n\nvoid invoice() {\n    I64[3] subtotals = [200, 2434, 600];\n    for i in 0..3 {\n        I64 s = subtotals[i];\n        \"tax on {s}: {tax(s)}\\n\";\n    }\n}\n\ninvoice();\n```\n\n```text\ntax on 200: 16\ntax on 2434: 201\ntax on 600: 50\n```"
  },
  {
   "id": "spec-04p:goldens-p1",
   "edition": "SPEC-04P.2",
   "title": "8.3 Golden outputs and tests (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#goldens",
   "internal": 0,
   "content": "3. This example shows making and checking a golden. After the output is checked once, it is saved; each run after that is compared with it, and so is the reference's output. A change of rounding mode in `invoice_up.ci` changes one line of the output, and the comparison shows it:\n\n```console\n$ cint run invoice.ci > invoice.golden\n$ cat invoice.golden\ntax on 200: 16\ntax on 2434: 201\ntax on 600: 50\n$ cint run invoice.ci | diff invoice.golden - && echo same\nsame\n$ python3 -m cint_ref run --stdout ref.out invoice.ci > /dev/null\n$ diff invoice.golden ref.out && echo same\nsame\n$ diff invoice.ci invoice_up.ci\n1c1\n< // invoice.ci: tax at 8.25 percent on three subtotals, in whole cents.\n---\n> // invoice_up.ci: invoice.ci with half_up in place of half_even.\n3c3\n<     return div_round(subtotal * 825, 10000, half_even);\n---\n>     return div_round(subtotal * 825, 10000, half_up);\n$ cint run invoice_up.ci | diff invoice.golden -\n1c1\n< tax on 200: 16\n---\n> tax on 200: 17\n```\n\n4. Tests keep the expectations inside the module. `tax.ci` states three: the tax on 2434 cents, the tie at 200 cents and the overflow of `subtotal * 825` near `I64.max`. As a script it also prints one line, which `cint run` shows; `cint test` runs the tests instead:\n\n```cint tax.ci\n// tax.ci: sales tax at 8.25 percent, in whole cents, rounded half to even.\nI64 tax(I64 subtotal) {\n    return div_round(subtotal * 825, 10000, half_even);\n}\n\ntest \"tax on 2434 cents\" {\n    assert(tax(2434) == 201);\n}\n\ntest \"a tie rounds to the even cent\" {\n    assert(tax(200) == 16);\n}\n\ntest \"a subtotal near I64.max overflows\" expect_fault E_OVERFLOW {\n    _ = tax(I64.max);\n}\n\n\"tax on 200: {tax(200)}\\n\";\n```\n\n```text\ntax on 200: 16\n```\n\n5. `tax_up.ci` is `tax.ci` with `half_up` in place of `half_even`. Its tie test fails, and the report shows both sides of the comparison: the tax is 17 where 16 was expected:"
  },
  {
   "id": "spec-04p:goldens-p2",
   "edition": "SPEC-04P.2",
   "title": "8.3 Golden outputs and tests (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#goldens",
   "internal": 0,
   "content": "```console\n$ cint test tax.ci\ntest tax.ci:6 \"tax on 2434 cents\" ... ok\ntest tax.ci:10 \"a tie rounds to the even cent\" ... ok\ntest tax.ci:14 \"a subtotal near I64.max overflows\" ... ok\n3 of 3 tests passed\n$ cint test tax_up.ci\ntest tax_up.ci:6 \"tax on 2434 cents\" ... ok\ntest tax_up.ci:10 \"a tie rounds to the even cent\" ... FAILED\nfault[E_ASSERT]: assertion failed\n  --> tax_up.ci:11:12\n   |\n11 |     assert(tax(200) == 16);\n   |            ^ assert.checked.bool\n   |\n   = operation: assert.checked.bool\n   = operand-count: 2\n   = operand: I64 17\n   = operand: I64 16\n   = exact:   none\n   = limit:   none\n   = revision: 34ad5e3ae42e19c14239f8b71b3eee34f41bf4ac14dad8b7bd8200ce87ce381a\n   = source-map: none\n   = address: none\n   = stack-depth: 0\n   = fuel-consumed: 2 (not part of the fault record)\n   = state: the test stopped; its output is not shown\ntest tax_up.ci:14 \"a subtotal near I64.max overflows\" ... ok\n2 of 3 tests passed\n```\n\n6. This example shows a golden of a whole outcome. A saved output does not hold the fault, which goes to the standard error. The reference writes the outcome of a run as lines of text: the length and digest of the output, the fuel consumed and the fields of the fault (SPEC-09P.1). Saved, these lines are a golden of the whole outcome; `python3 -m cint_ref check` runs the program again and exits with status 0 when the outcome is the saved one:"
  },
  {
   "id": "spec-04p:goldens-p3",
   "edition": "SPEC-04P.2",
   "title": "8.3 Golden outputs and tests (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#goldens",
   "internal": 0,
   "content": "```console\n$ python3 -m cint_ref run month.ci > month.expect\n$ cat month.expect\ncase month\nsource reference\noutcome fault\nstdout-bytes 66\nstdout-sha256 2f1ada714964d61a382d8867eb0903f28bca1dbc9d918982300c7f445df4f3df\nfuel-consumed 10\nfault.code E_OVERFLOW\nfault.operation add.checked.i64\nfault.operand I64 2434\nfault.operand I64 9223372036854775000\nfault.exact 9223372036854777434\nfault.limit I64 9223372036854775807\nfault.position month.ci:3:18\nfault.revision self\nfault.address none\nfault.stack-depth 2\n$ python3 -m cint_ref check month.ci month.expect && echo same\nsame\n```\n\n**Notes**\n\n7. A golden is only as good as its one check. Read the output before saving it, and check it against an independent computation where one exists: here, 8.25 percent of 2434 cents is 200.805 cents, which rounds to 201.\n\n8. When a comparison with a golden fails, read the difference before replacing the golden. A golden replaced to make a comparison pass checks nothing.\n\n9. A test states its expectation inside the module and runs with every `cint test`; a saved output records everything the program prints, including lines no test mentions. A program that prints a report benefits from both.\n\n10. A golden made with any conforming implementation, on any executor or machine, is valid for every other (8.2). A golden that differs between two of them shows a defect in one of them, not a property of the program."
  },
  {
   "id": "spec-04p:replay",
   "edition": "SPEC-04P.2",
   "title": "8.4 Checkpoints, recordings and replay",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#replay",
   "internal": 0,
   "content": "### 8.4 Checkpoints, recordings and replay\n\nA host program runs a cint program as a sequence of entries (3.20), and the end of an entry is a *boundary*. At a boundary no function of the program is running, and the program's *state* is its module-level variables, its arenas and pools and its fault record, with its identifier counters, its count of entries begun and its count of effects completed (SPEC-01P.2, 3.10). A *checkpoint* saves the state at a boundary. A *recording* saves everything needed to run a sequence of entries again, and *replay* runs them again and checks each boundary against the recording. The debug tools go back in time by replay: they never run a program backward.\n\nThe examples of this subclause drive entries with `cint workbench`, which 8.5 introduces: each line of cint source typed after the prompt `ci[N]>` is one entry, and a line that starts with `:` is a command.\n\n**Semantics**\n\n1. Boundaries are the ends of entries, and the host program decides where entries begin and end. Program code cannot make a boundary inside an entry, and the locals of a running function are not part of the state, so no checkpoint is taken in the middle of a loop. A program that does all its work in one `main` has one boundary, at its end. In a session, each entry is one step (Note 11)."
  },
  {
   "id": "spec-04p:replay-p1",
   "edition": "SPEC-04P.2",
   "title": "8.4 Checkpoints, recordings and replay (part 2)",
   "clauses": "H-19",
   "url": "/specifications/spec-04p/2/#replay",
   "internal": 0,
   "content": "2. A checkpoint holds the state at a boundary, which carries the program's revision, inside an *envelope*, a header that names the format, the runtime contract version (3.43) and the build of the program that wrote it (SPEC-01P.2); the envelope is not part of any identity. Restoring a checkpoint into a program of another revision fails. A checkpoint taken on another executor or by another build of the same revision is accepted. A build of the same source under another runtime contract version has another revision, so a checkpoint does not restore across that change: a restore requires the checkpoint's runtime contract to be exactly the context's [SPEC-03P.1 H-19].\n\n3. Restoring a checkpoint makes its state current exactly, the fault record included, together with the fuel allowance and depth limit that were in force when it was taken. Before a restore, a session saves the current state as an automatic checkpoint `auto-N`, unless a checkpoint of the same state exists, so a restore loses nothing. A restore does not rewind the outside world: output printed after the checkpoint stays printed."
  },
  {
   "id": "spec-04p:replay-p2",
   "edition": "SPEC-04P.2",
   "title": "8.4 Checkpoints, recordings and replay (part 3)",
   "clauses": "H-14",
   "url": "/specifications/spec-04p/2/#replay",
   "internal": 0,
   "content": "4. A recording holds [SPEC-03P.1 H-14]:\n   - a header: the language profile, the fuel model, the runtime contract version, the revision, the digest of the source map, the mode (`full`, which holds every input, or `digest`, which holds digests of the inputs), and the boundary density, which says whether boundaries are the ends of entries only or also the ends of kernel dispatches;\n   - the initial state, as a checkpoint;\n   - the code of every revision the recording runs: each module's compiled form and its source;\n   - the events, in order: each entry, with its arguments, fuel allowance, depth limit and frame-arena capacity; each effect, with its status, its result and, for a print, its bytes; each outcome, with its status, fault record, fuel consumed, result and state digest; each clearing of a fault, checkpoint, restore and change of revision; and last an end event, which holds the head of the chain of digests over the events. A recording without its end event is incomplete and is never loaded.\n\n   A *case* is a recording in `full` mode that holds the source of every module, so it runs on another machine with nothing but the tools.\n\n5. To reach a boundary, replay restores the latest checkpoint at or before it and runs the recorded entries again, with their recorded arguments, fuel allowances and limits and with the recorded answers of the host in place of the outside world. At each boundary it compares the outcome with the recording: the status, the fault record, the fuel consumed, the result and the state digest. The first difference stops replay with the status `DIVERGED` and the boundary where it happened. A print is compared with its recorded bytes and is not printed again. Going back one step is replay to the previous boundary."
  },
  {
   "id": "spec-04p:replay-p3",
   "edition": "SPEC-04P.2",
   "title": "8.4 Checkpoints, recordings and replay (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#replay",
   "internal": 0,
   "content": "6. Replay covers only what was recorded. `cint run` records nothing; a `cint workbench` session records every entry, and `cint debug locate` records the run it makes (8.5). Replay runs the recorded revisions, never code edited since. It compares outcomes at boundaries only, so a difference that appears and disappears inside one entry is not detected. Reaching a boundary costs a run from the nearest earlier checkpoint.\n\n7. In a session, a fault leaves the state that 5.2.3 describes, and its record stays until it is cleared. Before the next entry the session clears it, as a host program does. Clearing changes nothing else, is recorded as an event, and is printed as `context reset`.\n\n**Examples**\n\n8. The module `ledger.ci` keeps a balance in cents. It has only declarations, so it is an importable module, not a script (5.1.2):\n\n```cint\n// ledger.ci: a balance kept in whole cents.\nexport I64 balance = 0;\n\nexport I64 deposit(I64 cents) {\n    balance = balance + cents;\n    return balance;\n}\n\nexport I64 deposit_all[n](in I64[n] amounts) {\n    for i in 0..n {\n        _ = deposit(amounts[i]);\n    }\n    return balance;\n}\n\nexport I64 month() {\n    I64[4] amounts = [1999, 425, 10, 9223372036854775000];\n    return deposit_all(amounts);\n}\n\ntest \"three deposits\" {\n    I64[3] amounts = [1999, 425, 10];\n    assert(deposit_all(amounts) == 2434);\n}\n\ntest \"a deposit past I64.max faults\" expect_fault E_OVERFLOW {\n    _ = deposit(I64.max);\n    _ = deposit(1);\n}\n```\n\n9. This example shows a session that checkpoints, faults, replays and restores. In the output, `auto-N` names an automatic checkpoint, and an *observe result* is the answer to an observation request that the program made of its host (8.2):"
  },
  {
   "id": "spec-04p:replay-p4",
   "edition": "SPEC-04P.2",
   "title": "8.4 Checkpoints, recordings and replay (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#replay",
   "internal": 0,
   "content": "```console\n$ cint workbench ledger.ci\ncint workbench   profile cint-core-1   backend cpu-sir-interp   new session\nci[1]> :load ledger.ci\nloaded ledger (ledger.ci)\nci[2]> ledger.deposit(1999)\n= 1999 : I64\nci[3]> :checkpoint paid\ncheckpoint paid   #1   revisions: ledger@r1\nci[3]> ledger.deposit(425)\n= 2424 : I64\nci[4]> ledger.deposit(10)\n= 2434 : I64\nci[5]> ledger.deposit(9223372036854775000)\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> ledger.ci:5:23\n   |\n 5 |     balance = balance + cents;\n   |                       ^ add.checked.i64\n   |\n   = operation: add.checked.i64\n   = operand-count: 2\n   = operand: I64 2434\n   = operand: I64 9223372036854775000\n   = exact:   9223372036854777434\n   = limit:   I64 9223372036854775807\n...\n   = state: no store completed in this entry; context reset\n...\nci[6]> ledger.balance\n= 2434 : I64\nci[7]> :effects\nnew context\nrevisions: ledger@r1\nentry 2   ledger.deposit(1999)\n  value I64 1999   fuel 2   state 8c69387e\nentry 3   ledger.deposit(425)\n  value I64 2424   fuel 2   state 4cd4a38f\nentry 4   ledger.deposit(10)\n  value I64 2434   fuel 2   state 345376d9\nentry 5   ledger.deposit(9223372036854775000)\n  fault E_OVERFLOW   fuel 2   state 5d62ad7e\ncontext reset\nentry 6   ledger.balance\n  value I64 2434   fuel 1   state 4da4d5f3\nentries 5   prints 0   context resets 1   changes of revision set 0\nci[7]> :save-case ledger.case\nnote: the case includes every recorded observe result verbatim; this case has none\ncase ledger.case   checkpoint paid   entries 3..6   effects 0   density entry\nci[7]> :watch ledger.balance\nwatch 1   ledger.balance = 2434 : I64\nci[7]> :replay paid\nreplaying 4 entries from paid to the current state (entry 3 to entry 6), comparing prints and outcomes with the recording\nwatch 1   entry 3   ledger.balance = 2424\nwatch 1   entry 4   ledger.balance = 2434\nentry 5: E_OVERFLOW reproduced, its fault recor"
  },
  {
   "id": "spec-04p:replay-p5",
   "edition": "SPEC-04P.2",
   "title": "8.4 Checkpoints, recordings and replay (part 6)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#replay",
   "internal": 0,
   "content": "Step by step:\n\n- `cint workbench ledger.ci` loads the module as entry 1; its exports are named `ledger.deposit` and `ledger.balance`.\n- Entry 2 deposits 1999. `:checkpoint paid` saves the state at the boundary after entry 2, with the revision of each loaded module: `ledger@r1` is the first revision of `ledger` in the session.\n- Entries 3 and 4 deposit 425 and 10. Entry 5 faults. Its `state` line says that no store of the entry completed, so `balance` keeps 2434, and that the session cleared the fault before the next entry. Entry 6 reads 2434.\n- `:effects` lists the recording: each entry with its value or fault, its fuel and the first 8 hexadecimal digits of the state digest at its boundary. The clearing of the fault, `context reset`, is an event of its own.\n- `:save-case ledger.case` writes a case that starts from the checkpoint `paid` and holds entries 3 to 6. None of them printed, so the case holds no effects.\n- `:watch ledger.balance` asks for each change of the balance at a boundary. `:replay paid` restores `paid` and runs entries 3 to 6 again: the watch reports the changes at entries 3 and 4, entry 5 faults again with a record equal to the recorded one, and all 4 boundaries match the recording.\n- `:goto 3` saves the current state as `auto-1`, then makes the boundary after entry 3 current by restore and replay. Entry 7 reads 2424 there. Entries typed after `:goto` start a new branch, named after the boundary.\n- `:restore paid` saves the current state as `auto-3` and makes `paid` current, where entry 8 reads 1999. `:diff auto-1` compares the current state with `auto-1`, binding by binding: the balance differs, and both values are shown."
  },
  {
   "id": "spec-04p:replay-p6",
   "edition": "SPEC-04P.2",
   "title": "8.4 Checkpoints, recordings and replay (part 7)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#replay",
   "internal": 0,
   "content": "10. The case replays outside the session. A case saved from a session holds each typed entry as a function `wb_entry` of a module `session.ci`. `cint debug replay` prints one row for each boundary, with the event of the recording that ends it, the entry, its outcome and its fuel. `--to 2` stops after boundary 2. `cint debug locate --changed` finds the last boundary at which a binding changed:"
  },
  {
   "id": "spec-04p:replay-p7",
   "edition": "SPEC-04P.2",
   "title": "8.4 Checkpoints, recordings and replay (part 8)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#replay",
   "internal": 0,
   "content": "```console\n$ cint debug replay ledger.case\ncase       ledger.case   4 boundaries   13 events   mode full   density entry\nrevision   b355aac957aa2a7c3354721d8f5655d61f73d8eb7b3f3663754b473f33d8dbc4\nsource-map 51d7e33355e7ac6a2ef888d9be9a20ac4ff75b2816ffa6e52ab43eccc6763f40\nboundary  event  entry                          outcome                  fuel\n       1      2  wb_entry()                     value I64 2424           2\n       2      5  wb_entry()                     value I64 2434           2\n       3      8  wb_entry()                     faulted E_OVERFLOW       2\n       4     12  wb_entry()                     value I64 2434           1\nreplay     ok, 4 of 4 boundaries compared with the recording\nchain      086cf3fa7c8e63463e760f70b6aa1a3fb478c2337568b1c5c40cc2e5ad80f3dd\nstate      4da4d5f350a73fd9086179f8c15d41e47bf4343c82dd6c8df690d7a0935da4d9\n$ cint debug replay ledger.case --to 2\ncase       ledger.case   4 boundaries   13 events   mode full   density entry\nrevision   b355aac957aa2a7c3354721d8f5655d61f73d8eb7b3f3663754b473f33d8dbc4\nsource-map 51d7e33355e7ac6a2ef888d9be9a20ac4ff75b2816ffa6e52ab43eccc6763f40\nboundary  event  entry                          outcome                  fuel\n       1      2  wb_entry()                     value I64 2424           2\n       2      5  wb_entry()                     value I64 2434           2\nreplay     ok, 2 of 4 boundaries compared with the recording\nchain      848c931491de4e7f7ebf29fabc5e8bec777181e820fcc6f009b3a0eb8a16550b\nstate      345376d98439eb1b1034db3124deb6ffd1c87f7720ab6a6a0f94e3b2a998e6e7\n$ cint debug locate ledger.case --changed ledger.balance\ncase       ledger.case   4 boundaries\ntarget     boundary 2 of 4, wb_entry(): the last change of ledger.balance, from 2424 to 2434\nbracket    boundary 1, wb_entry(): value I64 2424; then boundary 2\nthe last 2 counted operations of boundary 2, of 3 trace events (:trace "
  },
  {
   "id": "spec-04p:replay-p8",
   "edition": "SPEC-04P.2",
   "title": "8.4 Checkpoints, recordings and replay (part 9)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#replay",
   "internal": 0,
   "content": "`chain` is the head of the chain of digests over the events replayed, and `state` the state digest at the last boundary replayed. Its first 8 digits are those that `:effects` showed for the same boundary: entry 6 for the whole case, entry 4 for `--to 2`. Boundary 2, entry 4 of the session, is the last change of the balance; the fault at boundary 3 stored nothing.\n\n**Notes**\n\n11. A program meant to be stepped through is written as a module whose exported function performs one step, called once for each step by its host program or by `:run` in a session. Each call then ends at a boundary that can be checkpointed, watched and replayed.\n\n12. A checkpoint costs storage in proportion to the state; replay costs time in proportion to the distance from the nearest checkpoint. Checkpoints taken often make replay short."
  },
  {
   "id": "spec-04p:debug-tools",
   "edition": "SPEC-04P.2",
   "title": "8.5 The debug tools",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#debug-tools",
   "internal": 0,
   "content": "### 8.5 The debug tools\n\nFive more commands of `cint` run the debug tools and the interpreter. `cint workbench` runs a *session*: cint source entered one entry at a time, with commands to inspect, checkpoint, restore and replay; `cint repl` runs the same session loop. `cint explain` describes what the compiler knows about a function without running it. `cint debug` finds the fault of a program or a recording, replays recordings and cases and compares two executors on a case. `cint interp FILE` runs a program on `cpu-sir-interp`, as `cint run` runs it on `cpu-c17`. The `backend` and `evaluator` fields of their output name the executor (3.19). This subclause teaches a first session and the commands used most; SPEC-06P.1 defines every command, option and output format.\n\n**Semantics**\n\n1. A session compiles each entry with the compiler that `cint run` uses and runs it on `cpu-sir-interp`. The type rules are those of clause 6: a session has no conversions, dynamic types or relaxed overflow checks of its own. The same entry in a session and in a compiled program gives the same values, output, state after a fault and fault record except its `revision`."
  },
  {
   "id": "spec-04p:debug-tools-p1",
   "edition": "SPEC-04P.2",
   "title": "8.5 The debug tools (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#debug-tools",
   "internal": 0,
   "content": "2. A session follows these rules:\n   - A line that starts with `:` is a command. Any other line is cint source, a declaration, a statement or an expression, and is one entry.\n   - Entries are numbered from 1, and the prompt `ci[N]>` shows the number the next entry takes. `:load` and `:run` each make one entry; the other commands make none. A position inside an entry is written `entry N:line:column`.\n   - An entry that is not complete at the end of a line continues on the next, after the prompt `..>`.\n   - A declaration adds to the *session module*. A variable declared at the prompt is a module-level variable of it, which keeps its value from entry to entry and is part of the state. A declaration makes a new revision of the session module.\n   - An expression entry prints its value and its type.\n   - Entries typed after a restore or a `:goto` start a new *branch* of the session's recording (8.4, example 9).\n   - `cint workbench FILE` loads the module `FILE` as entry 1, which the session shows as the line `ci[1]> :load FILE`. Its exports are named with the module's name, as in `ledger.deposit`.\n   - `:run f(args)` calls the exported function `f` of the session module as the entry itself, as `cint run` calls a program's entry, so `f` adds no position to a stack. An expression entry `f(args)` is an entry that calls `f`, and that call is a position of the stack.\n\n3. This clause uses the following commands:"
  },
  {
   "id": "spec-04p:debug-tools-p2",
   "edition": "SPEC-04P.2",
   "title": "8.5 The debug tools (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#debug-tools",
   "internal": 0,
   "content": "   | Command | What it does |\n   |---|---|\n   | `:load FILE` | Compiles and loads a module, as a new revision, and brings its exports into scope. |\n   | `:run f(args)` | Calls the exported function `f` as the entry. |\n   | `:inspect EXPR [/hex]` | Shows the value of `EXPR` exactly, and in hexadecimal with `/hex`. It is not an entry and changes nothing. |\n   | `:trace` | Lists the counted operations of the last entry, by replaying it on `cpu-sir-interp`. |\n   | `:fuel N`, `:depth N` | Sets the fuel allowance or the depth limit of each entry. By default an entry has no allowance and a depth limit of 256; `:fuel none` removes the allowance. |\n   | `:checkpoint NAME` | Saves the state at the current boundary under a name. |\n   | `:restore NAME` | Makes the state of a checkpoint current (8.4). |\n   | `:diff NAME` | Compares the current state with a checkpoint, binding by binding. |\n   | `:watch EXPR` | Evaluates `EXPR` at every boundary and reports each change. |\n   | `:replay NAME` | Runs the recorded entries again from a checkpoint and compares each outcome with the recording. |\n   | `:goto N`, `:goto fault` | Makes current the boundary after entry `N`, or after the entry that faulted, by restore and replay. |\n   | `:effects` | Lists the recording of the current branch. |\n   | `:save-case PATH` | Writes a case (8.4) for `cint debug`. |\n   | `:quit [--yes]` | Ends the session; `--yes` ends it without asking about unsaved work. |"
  },
  {
   "id": "spec-04p:debug-tools-p3",
   "edition": "SPEC-04P.2",
   "title": "8.5 The debug tools (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#debug-tools",
   "internal": 0,
   "content": "4. `cint explain FILE:NAME` describes the function or kernel `NAME` of the module `FILE` without running it: its signature, with the mode of each parameter; its effect class, `pure` when it prints nothing and calls nothing that prints, and `observe` otherwise (`pure` here means only that; such a function may write module state); every *fault site*, an operation that can fault, with its identifier `NAME#n`, its position, its operation identifier and its fault code, and whether a fault there is possible or excluded; its fuel charges; and its compiled form. A site's identifier is fixed for a revision, and the `site` line of a fault report names the site that faulted.\n\n5. `cint debug locate PROGRAM --entry NAME` runs the exported function `NAME` of a module as the entry, on `cpu-sir-interp` under a recording, and replays the recording to the first boundary that ends in a fault or an error result. It prints the fault report, the *bracket*, which is the last boundary before that one and the boundary itself, and the last counted operations of the faulting entry. Given a recording or a case in place of a program, it replays that. With `--changed BINDING` it looks instead for the last boundary at which the binding changed, scanning backward: it replays the last interval between checkpoints, then the one before, until it finds the change. It does not bisect, because a value can change and change back between two checkpoints. `--save-case PATH` keeps what it recorded as a case."
  },
  {
   "id": "spec-04p:debug-tools-p4",
   "edition": "SPEC-04P.2",
   "title": "8.5 The debug tools (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#debug-tools",
   "internal": 0,
   "content": "6. `cint debug diff CASE` runs a case on two executors from the same checkpoint, with the same effects: `cpu-c17`, the baseline and `cpu-sir-interp`, the candidate. The output labels them `reference` and `candidate`; the label `reference` names the baseline executor, not the reference of 3.18. It compares the state digest at each boundary, and the outcome, and reports the first of these that applies:\n   - `invalid-case`: the case failed validation;\n   - `refused`: the candidate reported a refusal (3.16) for the case, which shows no agreement;\n   - `unreproduced`: a difference did not repeat when the candidate ran again;\n   - `fault-difference`: one side faulted and the other did not, or the two fault records differ;\n   - `value-difference`: a state differs; the first differing boundary, binding and element are reported with both values;\n   - `agree`: every boundary is equal, and so are the results and the fault records.\n\n7. `cint debug CASE` opens a recording or a case in a read-only session. `:effects`, `:goto`, `:inspect`, `:trace` and `:replay` work there; an entry typed there is not accepted, so nothing typed is ever presented as part of the recording.\n\n**Examples**\n\n8. This example shows a first session. It starts with no module loaded:"
  },
  {
   "id": "spec-04p:debug-tools-p5",
   "edition": "SPEC-04P.2",
   "title": "8.5 The debug tools (part 6)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#debug-tools",
   "internal": 0,
   "content": "```console\n$ cint workbench\ncint workbench   profile cint-core-1   backend cpu-sir-interp   new session\nci[1]> 6 * 7\n= 42 : I64\nci[2]> I8 small = 100;\nsmall = 100 : I8\nci[3]> small + 27\n= 127 : I8\nci[4]> small + 28\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> entry 4:1:7\n   |\n 1 | small + 28\n   |       ^ add.checked.i8\n   |\n   = operation: add.checked.i8\n   = operand-count: 2\n   = operand: I8 100\n   = operand: I8 28\n   = exact:   128\n   = limit:   I8 127\n   = revision: 7a2e7048b4517fe4ed50dc022b2835a872cb724a37ca8b173bde6ad95e9f97ce\n   = source-map: none\n   = address: none\n   = stack-depth: 0\n   = fuel-consumed: 1 (not part of the fault record)\n   = state: no store completed in this entry; context reset\n   = noncanonical: not part of the fault record\n   = workbench-position: entry 4\n   = site: wb_entry#2\n   = backend: cpu-sir-interp\nci[5]> small +| 28\n= 127 : I8\nci[6]> :inspect small /hex\nsmall : I8   (signed, 8 bits)\n  exact   100\n  hex     0x64\nci[6]> export I64 cube(I64 x) {\n..>     return x * x * x;\n..> }\ncube : (I64) -> I64   revision session@r2\nci[7]> :run cube(2097151)\n= 9223358842721533951 : I64\nci[8]> :run cube(2097152)\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> entry 6:2:18\n   |\n 2 |     return x * x * x;\n   |                  ^ mul.checked.i64\n   |\n   = operation: mul.checked.i64\n   = operand-count: 2\n   = operand: I64 4398046511104\n   = operand: I64 2097152\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n   = revision: fe6b5d6907815d89bd5e60d39033ae0188a65e04a93827b9952bef82dc894535\n   = source-map: none\n   = address: none\n   = stack-depth: 0\n   = fuel-consumed: 1 (not part of the fault record)\n   = state: no store completed in this entry; context reset\n   = noncanonical: not part of the fault record\n   = workbench-position: entry 8\n   = site: cube#3\n   = backend: cpu-sir-interp\nci"
  },
  {
   "id": "spec-04p:debug-tools-p6",
   "edition": "SPEC-04P.2",
   "title": "8.5 The debug tools (part 7)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#debug-tools",
   "internal": 0,
   "content": "Step by step:\n\n- The first line names the language profile, `cint-core-1`, and the executor that runs each entry, `cpu-sir-interp`.\n- `6 * 7` is an expression entry, and prints its value and type.\n- `I8 small = 100;` declares a module-level variable of the session module.\n- `small + 27` is 127, `I8.max`. `small + 28` faults at `entry 4:1:7`, the `+` in line 1 of entry 4. The stack is empty because the fault is in the entry's own code. Under `noncanonical`, `site` names the fault site `wb_entry#2` of the entry's compiled code.\n- `small +| 28` is the saturating form, which gives 127 and does not fault (6.7.6).\n- `:inspect` shows the value exactly and in hexadecimal; it makes no entry, so the prompt stays at 6.\n- The declaration of `cube` takes three lines, continued after `..>`. It makes the second revision of the session module, `session@r2`.\n- `:run cube(2097151)` makes `cube` the entry: 2097151 cubed fits in `I64`. `:run cube(2097152)` faults at the second `*`, because 2^42 times 2^21 is 2^63, one more than `I64.max`. The position `entry 6:2:18` lies in the text of entry 6, where `cube` was declared; `workbench-position` says that entry 8 ran it. The stack is empty because `:run` makes `cube` the entry.\n- `:trace` replays the last entry and lists its counted operations: the first `*` gave 4398046511104 and the second faulted.\n\n9. This example shows limits in a session. With a fuel allowance of 3, the call of `deposit` inside `deposit_all` would be the fourth charge: 1 when the entry begins, 1 for the call of `deposit_all` and 1 for the first iteration. With a depth limit of 2, the entry has depth 1 and `deposit_all` depth 2, so the call of `deposit` would exceed the limit and is not entered:"
  },
  {
   "id": "spec-04p:debug-tools-p7",
   "edition": "SPEC-04P.2",
   "title": "8.5 The debug tools (part 8)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#debug-tools",
   "internal": 0,
   "content": "```console\n$ cint workbench ledger.ci\ncint workbench   profile cint-core-1   backend cpu-sir-interp   new session\nci[1]> :load ledger.ci\nloaded ledger (ledger.ci)\nci[2]> :fuel 3\nfuel: 3 units per entry\nci[2]> I64[5] small = [1, 2, 3, 4, 5];\nsmall : I64[5]   5 elements   host\n  [0] = 1\n  [1] = 2\n  [2] = 3\n  [3] = 4\n  [4] = 5\nci[3]> ledger.deposit_all(small)\nfault[E_FUEL]: fuel allowance exhausted\n  --> ledger.ci:11:13\n   |\n11 |         _ = deposit(amounts[i]);\n   |             ^ fuel.charge\n   |\n   = operation: fuel.charge\n   = operand-count: 0\n   = exact:   none\n   = limit:   I64 3\n   = revision: e5f6a0f59e784400137676ad2d3022e75d83e23ed40f7cbdfbe0db4fc63fdfdf\n   = source-map: none\n   = address: none\n   = stack-depth: 1\n   = called from: entry 3:1:8\n   = fuel-consumed: 3 (not part of the fault record)\n   = state: no store completed in this entry; context reset\n   = noncanonical: not part of the fault record\n   = stack-source: entry 3:1:8\n   |\n 1 | ledger.deposit_all(small)\n   |        ^\n   |\n   = workbench-position: entry 3\n   = site: deposit_all#6\n   = backend: cpu-sir-interp\nci[4]> :fuel none\nfuel: no allowance per entry\nci[4]> :depth 2\ndepth: 2 per entry\nci[4]> ledger.deposit_all(small)\nfault[E_DEPTH]: call depth limit exceeded\n  --> ledger.ci:11:13\n   |\n11 |         _ = deposit(amounts[i]);\n   |             ^ call.enter\n   |\n   = operation: call.enter\n   = operand-count: 0\n   = exact:   none\n   = limit:   I64 2\n   = revision: e5f6a0f59e784400137676ad2d3022e75d83e23ed40f7cbdfbe0db4fc63fdfdf\n   = source-map: none\n   = address: none\n   = stack-depth: 1\n   = called from: entry 4:1:8\n   = fuel-consumed: 3 (not part of the fault record)\n   = state: no store completed in this entry; context reset\n   = noncanonical: not part of the fault record\n   = stack-source: entry 4:1:8\n   |\n 1 | ledger.deposit_all(small)\n   |        ^\n   |\n   = workbench-position: entry 4\n   = site:"
  },
  {
   "id": "spec-04p:debug-tools-p8",
   "edition": "SPEC-04P.2",
   "title": "8.5 The debug tools (part 9)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#debug-tools",
   "internal": 0,
   "content": "Both faults are at the callee's name of the call that failed, have no operands and no exact result, and have the allowance or the limit as their limit. The stack holds one position, the call of `deposit_all` in the entry; the call of `deposit` that failed is the record's position, not a position of the stack (8.1, paragraph 2).\n\n10. `cint explain` lists the fault sites of `deposit`. Lines about analysis, fuel charges and how each executor compiles the function are left out:\n\n```console\n$ cint explain ledger.ci:deposit\nmodule ledger.ci   revision fe98a3096002b4f1708db7ae5b9254a718cc55103ac59c209538413ab8ec92da\n\nfunction deposit   ledger.sites:4   pure\n  signature  (in cents: I64) -> I64\n  fault sites (2): 2 possible, 0 statically excluded\n    deposit#1  ledger.ci:4:12  fuel.charge      E_FUEL possible\n    deposit#2  ledger.ci:5:23  add.checked.i64  E_OVERFLOW possible\n...\n  sir\nexport func @ledger.deposit(%cents: I64) -> I64 {\n  fuel.charge 1                                  #1 @ledger.ci:4:12\n  %t0 = load.global @balance\n  %t1 = add.checked.i64 %t0, %cents              #2 @ledger.ci:5:23\n  store.global @balance, %t1\n  %t2 = load.global @balance\n  return %t2\n}\n```\n\nThe function line gives `ledger.sites:4`, the line of `deposit` in the module's SIR text (3.41), the textual form of the compiled program, not a source position: the SIR text is a separate file with its own line numbers. `deposit` is `pure`: it prints nothing. It has two fault sites: `deposit#1`, the fuel charge when the function is called, and `deposit#2`, the `+` at line 5. The section `sir` is the function's part of that SIR text, the compiled form, which `cpu-sir-interp` runs; `#1` and `#2` mark the two sites. The module's revision is the one in the reports of the next example.\n\n11. `cint debug locate` runs `month` under a recording, finds its fault and keeps the recording as the case `month.case`:"
  },
  {
   "id": "spec-04p:debug-tools-p9",
   "edition": "SPEC-04P.2",
   "title": "8.5 The debug tools (part 10)",
   "clauses": "IM-121",
   "url": "/specifications/spec-04p/2/#debug-tools",
   "internal": 0,
   "content": "```console\n$ cint debug locate ledger.ci --entry month --save-case month.case\nprogram    ledger.ci   evaluator cpu-sir-interp, recorded as the case month.case\ntarget     boundary 1 of 1, month(): the first fault, reproduced by replay\nbracket    the initial state; then boundary 1\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> ledger.ci:5:23\n   |\n 5 |     balance = balance + cents;\n   |                       ^ add.checked.i64\n   |\n   = operation: add.checked.i64\n   = operand-count: 2\n   = operand: I64 2434\n   = operand: I64 9223372036854775000\n   = exact:   9223372036854777434\n   = limit:   I64 9223372036854775807\n   = revision: fe98a3096002b4f1708db7ae5b9254a718cc55103ac59c209538413ab8ec92da\n   = source-map: none\n   = address: none\n   = stack-depth: 2\n   = called from: ledger.ci:18:12\n   = called from: ledger.ci:11:13\n   = fuel-consumed: 10 (not part of the fault record)\n   = state: the post-fault state of SPEC-01 IM-121, reached by replay\n   = noncanonical: not part of the fault record\n   = stack-source: ledger.ci:18:12\n   |\n18 |     return deposit_all(amounts);\n   |            ^\n   |\n   = stack-source: ledger.ci:11:13\n   |\n11 |         _ = deposit(amounts[i]);\n   |             ^\n   |\n   = workbench-position: boundary 1\n   = site: deposit#2\n   = backend: cpu-sir-interp, by replay\nthe last 16 counted operations of boundary 1, of 19 trace events (:trace shows them all)\n  ord  position           operation              operands                 value\n    0  ledger.ci:18:12    call                   4, 0\n    1  ledger.ci:11:28    index.checked.i64      0\n    2  ledger.ci:11:13    call                   1999\n    3  ledger.ci:5:23     add.checked.i64        0, 1999                  1999\n    -  ledger.ci:11:13    return                                          1999\n    4                     add.wrap.i64           0, 1                     1\n    5  ledger."
  },
  {
   "id": "spec-04p:debug-tools-p10",
   "edition": "SPEC-04P.2",
   "title": "8.5 The debug tools (part 11)",
   "clauses": "IM-121",
   "url": "/specifications/spec-04p/2/#debug-tools",
   "internal": 0,
   "content": "The entry is `month`, so its call of `deposit_all` at line 18 is the outermost position of the stack. The `state` line names IM-121, the state after a fault (5.2.3); `reached by replay` says that `locate` reached that state by replaying the recording. The bracket is the initial state and boundary 1, because the run has one entry. The trace shows the loop of `deposit_all` reading each amount, calling `deposit` and adding, until the fourth addition faults.\n\n12. The case replays, and `cint debug diff` finds that `cpu-c17` and `cpu-sir-interp` agree on it:\n\n```console\n$ cint debug replay month.case\ncase       month.case   1 boundary   2 events   mode full   density entry\nrevision   fe98a3096002b4f1708db7ae5b9254a718cc55103ac59c209538413ab8ec92da\nsource-map 5166a2a13a791ed722204de3e5d81ef0913bd6a97ca5a14701a7a5b85836bed7\nboundary  event  entry                          outcome                  fuel\n       1      1  month()                        faulted E_OVERFLOW       10\nreplay     ok, 1 of 1 boundary compared with the recording\nchain      ffa80772fafde299a3d0c4a7e288de3a8a9955434949a2822d8ef3b5150ea745\nstate      4ffbd08ab16440492352753af4f115886f504a056574fb17a8caa7de901c2b7c\n$ cint debug diff month.case\ncase       month.case   1 boundary   density entry\nreference  cpu-c17\ncandidate  cpu-sir-interp\nboundaries 1 of 1 compared\noutcome    agree\n```\n\n13. A case opens read-only, as the first line says. The session starts at the end of the case's last entry, and the prompt shows the number an entry would take. The balance after the fault is 2434: the three deposits that completed stay stored (5.2.3):"
  },
  {
   "id": "spec-04p:debug-tools-p11",
   "edition": "SPEC-04P.2",
   "title": "8.5 The debug tools (part 12)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#debug-tools",
   "internal": 0,
   "content": "```console\n$ cint debug month.case\ncint workbench   profile cint-core-1   backend cpu-sir-interp   debug month.case (read-only)\ncase: entries 1   boundaries 1\nat the end of entry 1, reached by replay\nci[2]> :effects\nnew context\nentry 1   ledger.ci: month()\n  fault E_OVERFLOW   fuel 10   state 4ffbd08a\nentries 1   prints 0   context resets 0   changes of revision set 0\nci[2]> :goto fault\nat the end of entry 1, reached by replay\nci[2]> :inspect ledger.balance\nledger.balance : I64\n  exact   2434\nci[2]> :quit\n```\n\n**Notes**\n\n14. A routine for an unexpected fault has these steps:\n   - Read the report (8.1): the position, the operands and the exact result say what failed, and the stack says how the program got there.\n   - Run `cint explain` on the function to see its fault sites; the report's `site` line names the one that faulted.\n   - Run `cint debug locate` on the program to see the operations that led to the fault, and keep the run as a case with `--save-case`.\n   - Run `cint debug diff` on the case. `agree` means the two executors agree on this compiled form; a defect in the compiler that produced the form is not excluded. Any other outcome points at one of the executors.\n   - Fix the program, then add a test or a golden (8.3) that would have caught the fault.\n\n15. In a trace, `ord` numbers the operations of the whole entry from 0, in evaluation order. A row with `-` is a return, listed but not numbered. An `add.wrap.i64` row that the source does not contain, without a position in Example 11, is a loop's step of its index variable from one value to the next. The step ordinal of a kernel fault (8.1, paragraph 5) is a different count: it starts at 0 in each work-item and does not count loop steps. The operands and values of a trace are exact, and the row that faulted shows the fault code as its value."
  },
  {
   "id": "spec-04p:grammar",
   "edition": "SPEC-04P.2",
   "title": "Annex A (normative) Grammar",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#grammar",
   "internal": 0,
   "content": "## Annex A (normative) Grammar\n\nThis annex is the complete grammar of the language: every token and every syntactic form that a program of this edition may contain. Clauses 6 and 7 give each form with its meaning, in Syntax parts that use the names and definitions of this annex; a Syntax part that shows only some alternatives of a production says so. This annex collects the forms in one place and adds the rules that decide between two readings of the same text."
  },
  {
   "id": "spec-04p:grammar-notation",
   "edition": "SPEC-04P.2",
   "title": "A.1 Notation",
   "clauses": "LS-295",
   "url": "/specifications/spec-04p/2/#grammar-notation",
   "internal": 0,
   "content": "### A.1 Notation\n\n1. <a id=\"LS-295\"></a>A production has the form `name = definition ;`. In a definition, `|` separates alternatives, `[ x ]` is optional, `{ x }` is repeated zero or more times, `( )` groups, quoted text is a terminal, `\"a\" .. \"z\"` is any character in that range, and `(* *)` encloses a comment. Lexical productions, which define tokens, have names in capitals; the others define the syntax over tokens [LS-295].\n2. A source file is read as a sequence of tokens from first character to last. At each point the token taken is the longest that the lexical productions allow. White space and comments may separate two tokens and are otherwise ignored; they are required only between two tokens that would otherwise read as one, such as a keyword and an identifier [LS-295].\n3. The grammar gives the form of a program. A text that it produces may still break a constraint of clauses 5 to 7, which a diagnostic reports, such as an operand of the wrong type, a constant out of range, or a `switch` that does not cover its values. Those rules are not repeated here [LS-295].\n4. A text that the grammar does not produce is not a program of this edition. A.8 lists the forms outside the grammar that are diagnosed with a code of their own. The forms listed in 6.16, among them `var` declarations, `enum` declarations and tuples, are reserved: this edition gives them no meaning, and an implementation rejects or refuses a program that uses one and does not run it. The reference refuses such a program (3.16). Any other text outside the grammar is a syntax error, C1050 [LS-295]."
  },
  {
   "id": "spec-04p:grammar-lexical",
   "edition": "SPEC-04P.2",
   "title": "A.2 Lexical grammar",
   "clauses": "LS-296",
   "url": "/specifications/spec-04p/2/#grammar-lexical",
   "internal": 0,
   "content": "### A.2 Lexical grammar\n\n5. <a id=\"LS-296\"></a>The lexical productions are these [LS-296]:\n\n```ebnf\n(* characters *)\nletter      = \"A\" .. \"Z\" | \"a\" .. \"z\" | \"_\" ;\ndigit       = \"0\" .. \"9\" ;\nnonzero     = \"1\" .. \"9\" ;\nhexdigit    = digit | \"a\" .. \"f\" | \"A\" .. \"F\" ;\noctdigit    = \"0\" .. \"7\" ;\nbindigit    = \"0\" | \"1\" ;\nterndigit   = \"N\" | \"0\" | \"P\" ;\nsep         = \"_\" ;                                     (* only between two digits *)\n\n(* separators, skipped between tokens *)\nWHITE_SPACE   = \" \" | TAB | LF ;      (* TAB is U+0009 and LF is U+000A; a CR LF pair reads as LF *)\nLINE_COMMENT  = \"//\" { line_char } ;\nBLOCK_COMMENT = \"/*\" { BLOCK_COMMENT | any_char } \"*/\" ;   (* comments nest *)\nline_char     = (* any Unicode scalar value except a line end *) ;\nany_char      = (* any Unicode scalar value *) ;\n\n(* names *)\nIDENT       = letter { letter | digit } ;               (* not a KEYWORD; at most 255 bytes *)\nKEYWORD     = \"as\" | \"assert\" | \"break\" | \"by\" | \"case\" | \"catch\" | \"const\" | \"continue\"\n            | \"default\" | \"defer\" | \"distinct\" | \"do\" | \"else\" | \"enum\" | \"errdefer\" | \"error\"\n            | \"expect_fault\" | \"export\" | \"fallthrough\" | \"false\" | \"for\" | \"if\" | \"import\"\n            | \"in\" | \"in_place\" | \"inout\" | \"kernel\" | \"out\" | \"over\" | \"profile\" | \"reduce\"\n            | \"return\" | \"schedule\" | \"secret\" | \"static_assert\" | \"struct\" | \"switch\" | \"test\"\n            | \"true\" | \"try\" | \"type\" | \"var\" | \"void\" | \"where\" | \"while\" ;\nINT_TYPE    = \"I8\" | \"I16\" | \"I32\" | \"I64\" | \"I128\" | \"I256\" | \"I512\" | \"I1024\"\n            | \"U8\" | \"U16\" | \"U32\" | \"U64\" | \"U128\" | \"U256\" | \"U512\" ;   (* spelled as IDENT *)\nFIXED_TYPE  = \"Q\" nonzero { digit } \".\" ( \"0\" | nonzero { digit } ) ;"
  },
  {
   "id": "spec-04p:grammar-lexical-p1",
   "edition": "SPEC-04P.2",
   "title": "A.2 Lexical grammar (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#grammar-lexical",
   "internal": 0,
   "content": "(* literals *)\nINT_LIT     = DEC_INT | HEX_INT | OCT_INT | BIN_INT | TERN_INT ;\nDEC_INT     = \"0\" | nonzero { [ sep ] digit } ;\nHEX_INT     = \"0x\" hexdigit { [ sep ] hexdigit } ;\nOCT_INT     = \"0o\" octdigit { [ sep ] octdigit } ;\nBIN_INT     = \"0b\" bindigit { [ sep ] bindigit } ;\nTERN_INT    = \"0t\" terndigit { [ sep ] terndigit } ;\nFRAC_LIT    = DEC_FRAC | HEX_FRAC ;\nDEC_FRAC    = DEC_INT \".\" digit { [ sep ] digit } ;\nHEX_FRAC    = HEX_INT \".\" hexdigit { [ sep ] hexdigit } ;\nCHAR_LIT    = \"'\" ( char_char | escape ) \"'\" ;\nSTRING      = '\"' { str_char | escape | \"{{\" | \"}}\" | hole } '\"' ;\nchar_char   = (* any Unicode scalar value except \"'\", \"\\\" and a line end *) ;\nstr_char    = (* any Unicode scalar value except '\"', \"\\\", \"{\", \"}\" and a line end *) ;\nescape      = \"\\\" ( \"\\\" | '\"' | \"'\" | \"n\" | \"r\" | \"t\" | \"0\"\n                  | \"x\" octdigit hexdigit\n                  | \"u{\" hexdigit [ hexdigit [ hexdigit [ hexdigit [ hexdigit [ hexdigit ] ] ] ] ] \"}\" ) ;\n\n(* operators and punctuators *)\nPUNCT       = \"<<%=\" | \"<<=\" | \">>=\" | \"+%=\" | \"-%=\" | \"*%=\" | \"+|=\" | \"-|=\" | \"*|=\" | \"..=\"\n            | \"<<%\" | \"<<\" | \">>\" | \"+%\" | \"-%\" | \"*%\" | \"+|\" | \"-|\" | \"*|\"\n            | \"==\" | \"!=\" | \"<=\" | \">=\" | \"&&\" | \"||\" | \"++\" | \"--\"\n            | \"+=\" | \"-=\" | \"*=\" | \"/=\" | \"%=\" | \"&=\" | \"|=\" | \"^=\" | \"..\"\n            | \"+\" | \"-\" | \"*\" | \"/\" | \"%\" | \"<\" | \">\" | \"&\" | \"|\" | \"^\" | \"~\" | \"!\" | \"?\"\n            | \":\" | \"=\" | \"(\" | \")\" | \"[\" | \"]\" | \"{\" | \"}\" | \",\" | \";\" | \".\"\n            | \"@\" | \"as%\" | \"as?\" ;\n```"
  },
  {
   "id": "spec-04p:grammar-lexical-p2",
   "edition": "SPEC-04P.2",
   "title": "A.2 Lexical grammar (part 3)",
   "clauses": "LS-296 LS-297",
   "url": "/specifications/spec-04p/2/#grammar-lexical",
   "internal": 0,
   "content": "6. A token that begins with a digit extends over every letter, digit and `_` that follows it and over a following `.` only when a digit follows the point (a hexadecimal digit after `0x`), so `1..5` is `1`, `..`, `5`, and `12ab` is one token that matches no production. The whole token shall match `INT_LIT` or `FRAC_LIT`. A literal's magnitude is within the limit of 5.3 (C1023) [LS-296].\n7. A word that matches `IDENT` and is a `KEYWORD` is that keyword. Every keyword is reserved, including `distinct`, `do`, `enum`, `in_place`, `schedule`, `secret`, `type` and `var`, which no production of this edition uses. The words `as%` and `as?` are single tokens: `as` followed at once by `%` or `?` [LS-296].\n8. The spellings of `INT_TYPE`, `Bool` and the mode and operation names are identifiers, not keywords. A declaration shall not declare a name that matches `I`, `U`, `Q` or `T` followed only by digits (C1010) [LS-296].\n9. Outside comments, character literals and string literals, every character of a source file is ASCII (C1013). A `\\x` escape gives a value from 00 to 7F, and a backslash sequence that `escape` does not produce, such as `\\xff`, is C1032; a `\\u{...}` escape gives a Unicode scalar value, not a surrogate code point and not above U+10FFFF (C1031). A character literal holds exactly one character or escape [LS-296].\n10. Fault names, mode names, the operation names `add` and `mul` as the first argument of `fold_checked` (7.3), and the words `round` and `at` are identifiers, matched by their spelling in the positions where the productions name them. A fault name shall be one of the codes of 5.2.3 (C1011) [LS-297]."
  },
  {
   "id": "spec-04p:grammar-holes",
   "edition": "SPEC-04P.2",
   "title": "A.3 Holes and format specifications",
   "clauses": "LS-298",
   "url": "/specifications/spec-04p/2/#grammar-holes",
   "internal": 0,
   "content": "### A.3 Holes and format specifications\n\n11. <a id=\"LS-298\"></a>A hole is the text from a `{` in a string literal that is not doubled to the next `}`. Holes are allowed in the string literals of a print statement and of the message of an `assert`. The text of a hole is read with the lexical productions of A.2 and these productions [LS-298]:\n\n```ebnf\nhole        = \"{\" hole_expr [ \"=\" ] [ \"!\" conversion ] [ \":\" spec ] \"}\" ;\nhole_expr   = or_expr ;\nconversion  = \"bits\" | \"raw\" | \"lanes\" \"(\" lane_type \")\" | \"ratio\" ;   (* \"ratio\" is reserved, 7.5.4 *)\nlane_type   = \"I8\" | \"I16\" | \"I32\" | \"I64\" | \"U8\" | \"U16\" | \"U32\" | \"U64\" ;\nspec        = [ [ fill ] align ] [ sign ] [ \"#\" ] [ \"0\" ] [ width ] [ group ]\n              [ \".\" precision ] [ kind ] [ \"/\" scale ] ;\nfill        = (* any Unicode scalar value other than \"}\" *) ;\nalign       = \"<\" | \">\" | \"^\" ;\nsign        = \"-\" | \"+\" | \" \" ;\nwidth       = digit { digit } ;\ngroup       = \"_\" | \",\" ;\nprecision   = digit { digit } ;\nkind        = \"d\" | \"x\" | \"X\" | \"o\" | \"b\" | \"t\" | \"c\" ;\nscale       = \"1\" \"0\" { \"0\" } ;\n```\n\n12. The `hole_expr` of a hole contains no string literal, and a conditional expression in it is in parentheses (C1035). Which conversions and specifications apply to which types is in 7.5.3 and 7.5.4, which diagnose the others with C1037, a signed `lane_type` among them [LS-298]."
  },
  {
   "id": "spec-04p:grammar-modules-and-declarations",
   "edition": "SPEC-04P.2",
   "title": "A.4 Modules and declarations",
   "clauses": "LS-299",
   "url": "/specifications/spec-04p/2/#grammar-modules-and-declarations",
   "internal": 0,
   "content": "### A.4 Modules and declarations\n\n13. <a id=\"LS-299\"></a>The productions of modules and declarations are these [LS-299]:\n\n```ebnf\nmodule        = [ profile_decl ] { import_decl } { top_item } ;\nprofile_decl  = \"profile\" STRING \";\" ;                  (* the STRING is \"cint-core-1\" *)\nimport_decl   = \"import\" module_path\n                [ \"as\" IDENT | \".\" \"{\" IDENT { \",\" IDENT } [ \",\" ] \"}\" ] \";\" ;\nmodule_path   = IDENT { \".\" IDENT } ;\n\ntop_item      = [ \"export\" ] declaration\n              | test_decl\n              | static_assert\n              | statement ;\n\ndeclaration   = const_decl | var_decl | func_decl | kernel_decl\n              | struct_decl | error_decl | memory_decl ;\nconst_decl    = \"const\" type IDENT \"=\" expr \";\" ;\nvar_decl      = type IDENT [ \"=\" expr ] \";\" ;\nmemory_decl   = ( \"Arena\" | \"Pool\" ) \"(\" memory_elem \",\" expr \")\" IDENT \";\" ;\n\nfunc_decl     = result_type IDENT [ size_params ] \"(\" [ params ] \")\" block ;\nresult_type   = \"void\" | base_type | union_type ;\nunion_type    = qualified \"!\" ( \"void\" | base_type ) ;\nsize_params   = \"[\" IDENT { \",\" IDENT } \"]\" ;\nparams        = param { \",\" param } [ \",\" ] ;\nparam         = [ \"in\" | \"inout\" ] type IDENT ;\n\nkernel_decl   = \"kernel\" IDENT size_params \"(\" [ kparam { \",\" kparam } [ \",\" ] ] \")\"\n                [ over_clause ] [ where_clause ] block ;\nkparam        = ( \"in\" | \"out\" | \"inout\" ) type IDENT ;\nover_clause   = \"over\" \"[\" IDENT \":\" shape_expr { \",\" IDENT \":\" shape_expr } \"]\" ;\nwhere_clause  = \"where\" constraint { \",\" constraint } ;\nconstraint    = shape_expr ( \"==\" | \"<\" | \"<=\" | \">\" | \">=\" ) shape_expr ;\nshape_expr    = IDENT | INT_LIT | IDENT ( \"+\" | \"-\" ) INT_LIT ;"
  },
  {
   "id": "spec-04p:grammar-modules-and-declarations-p1",
   "edition": "SPEC-04P.2",
   "title": "A.4 Modules and declarations (part 2)",
   "clauses": "LS-299",
   "url": "/specifications/spec-04p/2/#grammar-modules-and-declarations",
   "internal": 0,
   "content": "struct_decl   = \"struct\" IDENT \"{\" { field } \"}\" ;\nfield         = type IDENT \";\" ;\nerror_decl    = \"error\" IDENT [ \":\" INT_TYPE ]\n                ( \"{\" IDENT { \",\" IDENT } [ \",\" ] \"}\"\n                | \"=\" qualified { \"|\" qualified } \";\" ) ;\n\ntest_decl     = \"test\" STRING [ \"expect_fault\" IDENT [ \"at\" DEC_INT ] ] block ;\nstatic_assert = \"static_assert\" \"(\" expr [ \",\" STRING ] \")\" \";\" ;\n```\n\n14. A `profile_decl`, when present, is the first item of the file, and every `import_decl` precedes every `top_item` (C3012). `export` does not precede a `test_decl` or a `static_assert`. The `STRING` of a `profile_decl`, a `test_decl` or a `static_assert` contains no hole (C1033) [LS-299].\n15. A `func_decl`, a `kernel_decl`, a `struct_decl`, an `error_decl`, a `memory_decl` and a `test_decl` appear only as top items, never inside a block. A capacity is written only in a `memory_decl` [LS-299]."
  },
  {
   "id": "spec-04p:grammar-types",
   "edition": "SPEC-04P.2",
   "title": "A.5 Types",
   "clauses": "LS-300",
   "url": "/specifications/spec-04p/2/#grammar-types",
   "internal": 0,
   "content": "### A.5 Types\n\n16. <a id=\"LS-300\"></a>The productions of types are these [LS-300]:\n\n```ebnf\ntype          = base_type [ shape ] ;\nbase_type     = INT_TYPE | \"Bool\" | FIXED_TYPE | memory_type | qualified ;\nmemory_type   = ( \"Arena\" | \"Pool\" ) \"(\" memory_elem \")\"\n              | \"Handle\" \"(\" memory_elem [ \"[\" [ \"_\" ] \"]\" ] \")\" ;\nmemory_elem   = INT_TYPE | \"Bool\" | qualified ;         (* an integer, Bool or struct type *)\nqualified     = IDENT [ \".\" IDENT ] ;                  (* a struct or error-set name *)\nshape         = \"[\" [ extent { \",\" extent } ] \"]\" ;\nextent        = \"_\" | expr ;\n```\n\n17. `[]` is `[_]`. A shape has one to four extents, and an array element is not itself an array. A `qualified` name has at most one module prefix [LS-300]."
  },
  {
   "id": "spec-04p:grammar-statements",
   "edition": "SPEC-04P.2",
   "title": "A.6 Statements",
   "clauses": "LS-301",
   "url": "/specifications/spec-04p/2/#grammar-statements",
   "internal": 0,
   "content": "### A.6 Statements\n\n18. <a id=\"LS-301\"></a>The productions of statements are these [LS-301]:\n\n```ebnf\nblock         = \"{\" { statement } \"}\" ;\nstatement     = block\n              | const_decl\n              | var_decl\n              | view_decl\n              | simple_stmt \";\"\n              | discard\n              | print_stmt\n              | if_stmt\n              | [ IDENT \":\" ] loop_stmt\n              | switch_stmt\n              | jump_stmt\n              | defer_stmt\n              | assert_stmt\n              | static_assert\n              | reduce_stmt ;\n\nview_decl     = ( \"in\" | \"inout\" ) type IDENT \"=\" expr \";\" ;\nsimple_stmt   = place assign_op expr\n              | place ( \"++\" | \"--\" )\n              | [ \"try\" ] call ;\nplace         = IDENT { \".\" IDENT | \"[\" index_list \"]\" } ;\nassign_op     = \"=\" | \"+=\" | \"-=\" | \"*=\" | \"/=\" | \"%=\" | \"<<=\" | \">>=\" | \"&=\" | \"|=\" | \"^=\"\n              | \"+%=\" | \"-%=\" | \"*%=\" | \"<<%=\" | \"+|=\" | \"-|=\" | \"*|=\" ;\ndiscard       = \"_\" \"=\" expr \";\" ;"
  },
  {
   "id": "spec-04p:grammar-statements-p1",
   "edition": "SPEC-04P.2",
   "title": "A.6 Statements (part 2)",
   "clauses": "LS-301",
   "url": "/specifications/spec-04p/2/#grammar-statements",
   "internal": 0,
   "content": "print_stmt    = STRING { STRING } \";\" ;\nif_stmt       = \"if\" \"(\" expr \")\" block [ \"else\" ( if_stmt | block ) ] ;\nloop_stmt     = while_stmt | for_stmt ;\nwhile_stmt    = \"while\" \"(\" expr \")\" block ;\nfor_stmt      = \"for\" IDENT \"in\" range block\n              | \"for\" \"(\" for_init \";\" expr \";\" simple_stmt \")\" block ;\nrange         = expr ( \"..\" | \"..=\" ) expr [ \"by\" expr ] ;\nfor_init      = type IDENT \"=\" expr | simple_stmt ;\nswitch_stmt   = \"switch\" \"(\" expr \")\" \"{\" { case_clause } [ default_clause ] \"}\" ;\ncase_clause   = \"case\" case_item { \",\" case_item } \":\" statement { statement } ;\ncase_item     = or_expr [ \"..=\" or_expr ] ;\ndefault_clause = \"default\" \":\" statement { statement } ;\njump_stmt     = ( \"break\" | \"continue\" ) [ IDENT ] \";\"\n              | return_stmt\n              | \"fallthrough\" \";\" ;\nreturn_stmt   = \"return\" [ expr ] \";\" ;\ndefer_stmt    = ( \"defer\" | \"errdefer\" ) ( block | simple_stmt \";\" | discard ) ;\nassert_stmt   = \"assert\" \"(\" expr [ \",\" STRING { STRING } ] \")\" \";\" ;\nreduce_stmt   = \"reduce\" IDENT \"=\" reduction \";\" ;\nreduction     = ( \"sum\" | \"sum_wrap\" | \"sum_sat\" | \"min\" | \"max\" | \"count\" ) \"(\" expr \")\"\n              | \"fold_checked\" \"(\" \"add\" \",\" expr \",\" expr \")\" ;\n```\n\n19. A `view_decl` is a statement of a block, not a top item. A `reduce_stmt` appears only in the body of a kernel. A label names only a `while` or `for` statement [LS-301]."
  },
  {
   "id": "spec-04p:grammar-expressions",
   "edition": "SPEC-04P.2",
   "title": "A.7 Expressions",
   "clauses": "LS-302",
   "url": "/specifications/spec-04p/2/#grammar-expressions",
   "internal": 0,
   "content": "### A.7 Expressions\n\n20. <a id=\"LS-302\"></a>The productions of expressions are these [LS-302]:\n\n```ebnf\nexpr          = cond_expr [ \"catch\" ( \"(\" IDENT \")\" block | cond_expr ) ] ;\ncond_expr     = or_expr [ \"?\" expr \":\" cond_expr ] ;\nor_expr       = and_expr { \"||\" and_expr } ;\nand_expr      = cmp_expr { \"&&\" cmp_expr } ;\ncmp_expr      = bor_expr [ cmp_op bor_expr ] ;\ncmp_op        = \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\" ;\nbor_expr      = bxor_expr { \"|\" bxor_expr } ;\nbxor_expr     = band_expr { \"^\" band_expr } ;\nband_expr     = shift_expr { \"&\" shift_expr } ;\nshift_expr    = add_expr { ( \"<<\" | \">>\" | \"<<%\" ) add_expr } ;\nadd_expr      = mul_expr { ( \"+\" | \"-\" | \"+%\" | \"-%\" | \"+|\" | \"-|\" ) mul_expr } ;\nmul_expr      = conv_expr { ( \"*\" | \"/\" | \"%\" | \"*%\" | \"*|\" ) conv_expr } ;\nconv_expr     = unary_expr { conv_op type [ round_clause ] } ;\nconv_op       = \"as\" | \"as%\" | \"as?\" ;\nround_clause  = \"round\" IDENT ;                          (* IDENT is a mode name *)\nunary_expr    = neg_literal\n              | ( \"-\" | \"-%\" | \"~\" | \"!\" | \"try\" ) unary_expr\n              | postfix_expr ;\nneg_literal   = \"-\" ( INT_LIT | CHAR_LIT | FRAC_LIT [ round_clause ] ) ;\npostfix_expr  = ( call | primary ) { \"[\" index_list \"]\" | \".\" IDENT } ;\ncall          = IDENT [ \".\" IDENT ] \"(\" [ args ] \")\" ;\nargs          = arg { \",\" arg } [ \",\" ] ;\narg           = [ IDENT \"=\" ] expr ;\nindex_list    = index { \",\" index } ;\nindex         = expr\n              | [ expr ] \"..\" [ expr ] [ \"by\" expr ]\n              | [ expr ] \"..=\" expr [ \"by\" expr ] ;"
  },
  {
   "id": "spec-04p:grammar-expressions-p1",
   "edition": "SPEC-04P.2",
   "title": "A.7 Expressions (part 2)",
   "clauses": "LS-302",
   "url": "/specifications/spec-04p/2/#grammar-expressions",
   "internal": 0,
   "content": "primary       = literal\n              | STRING { STRING }                        (* an argument for an `in U8[_]` parameter *)\n              | IDENT\n              | ( INT_TYPE | \"Bool\" | FIXED_TYPE ) [ \".\" IDENT ]\n              | FIXED_TYPE \".\" \"raw\" \"(\" [ args ] \")\"\n              | \"(\" expr \")\"\n              | array_literal\n              | \".\" IDENT ;\nliteral       = INT_LIT | CHAR_LIT | FRAC_LIT [ round_clause ] | bool_literal ;\nbool_literal  = \"false\" | \"true\" ;\narray_literal = \"[\" [ expr { \",\" expr } [ \",\" ] ] \"]\" ;\n```\n\n21. A `neg_literal` is formed whenever a `-` in the position of an operand is followed by an `INT_LIT`, `CHAR_LIT` or `FRAC_LIT` token, whatever white space or comments lie between them: `- 5` is the literal -5. A binary `-` is not affected [LS-302].\n22. A `call` names its callee directly: a function, a built-in operation, a struct (a constructor), a kernel (a dispatch), after a module name a function, kernel or struct of that module or after the name of an arena or a pool one of its members (paragraph 28). An expression in parentheses, an indexed expression or the result of a call is not called [LS-302].\n23. A `STRING` used as a value is an argument for a parameter of type `in U8[_]`, which receives its bytes. Its adjacent literals are one string, and it contains no hole (C1033) [LS-302].\n24. `( INT_TYPE | \"Bool\" | FIXED_TYPE ) \".\" IDENT` names a property of the type, such as `I64.max`; the type alone is a type argument (A.8, paragraph 30) [LS-302]."
  },
  {
   "id": "spec-04p:grammar-disambiguation",
   "edition": "SPEC-04P.2",
   "title": "A.8 Disambiguation and diagnosed forms",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#grammar-disambiguation",
   "internal": 0,
   "content": "### A.8 Disambiguation and diagnosed forms"
  },
  {
   "id": "spec-04p:grammar-disambiguation-p1",
   "edition": "SPEC-04P.2",
   "title": "A.8 Disambiguation and diagnosed forms (part 2)",
   "clauses": "LS-295 LS-303 LS-304 LS-305 LS-306 LS-307",
   "url": "/specifications/spec-04p/2/#grammar-disambiguation",
   "internal": 0,
   "content": "25. <a id=\"LS-303\"></a>A statement that begins with a type followed by an identifier, or with `const`, `in` or `inout`, is a declaration. At module level, a result type, an identifier, then `(` or `[` begin a function declaration, and a `const_decl` or a `var_decl` is a `declaration`, not a `statement`, so it does not make the module a script (5.1.2). A `_` followed by `=` begins a `discard`. Any other statement that does not begin with a keyword or a string literal is a simple statement [LS-303].\n26. <a id=\"LS-304\"></a>In a `case_item`, a conditional expression is in parentheses, so the `:` that ends the case is never read as part of it; `case_item` is an `or_expr` for this reason [LS-304].\n27. <a id=\"LS-305\"></a>In `for x in a..b`, the `range` belongs to the `for` statement: `in` is never an expression operator, and `..` and `..=` appear only in an `index`, a `range` and a `case_item`, never as expression operators [LS-305].\n28. <a id=\"LS-306\"></a>`a.f(args)`, where `a` is a name, is a `call` of `f` qualified by `a`. When `a` names an imported module, `f` is a function, kernel or struct of that module. When `a` names an arena, `f` is one of its members `alloc`, `alloc_result`, `child` and `reset`; when `a` names a pool, `f` is one of `insert`, `insert_result` and `remove` (6.14). A program does not declare members [LS-306].\n29. `a.f` without an argument list is a field of the struct `a`, the storage integer `a.raw` of a fixed-point value, or a name, constant or struct of the module `a` [LS-306].\n30. In an argument list, an argument that is a type name and not a value is a type argument; only the built-in operations take type arguments (7.1). The mode and operation positions of the built-in operations take a bare identifier (7.1) [LS-307].\n31. These forms are outside the grammar, and the reference diagnoses each with the code shown; 5.1.3 gives the position of each ["
  },
  {
   "id": "spec-04p:grammar-disambiguation-p2",
   "edition": "SPEC-04P.2",
   "title": "A.8 Disambiguation and diagnosed forms (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#grammar-disambiguation",
   "internal": 0,
   "content": "| Form | Code | Subclause |\n|---|---|---|\n| `;` where a statement or a body is expected | C1040 | 6.10.1 |\n| `=` as the top operator of a condition of `if`, `while` or a C-form `for` | C1041 | 6.10.2 |\n| `++` or `--` inside an expression | C1042 | 6.7.14 |\n| a condition of `if` or `while` without parentheses, or a body of `if`, `while` or `for` without braces | C1043 | 6.10.2 |\n| a shape after the capacity of a `memory_decl`, as in `Arena(I64, 4)[2] a;` | C2051 | 6.14.1 |\n| an assignment whose left side is not a `place` | C2058 | 6.7.14 |\n| `&&` with `\\|\\|`, a bitwise operator with an arithmetic operand or another bitwise operator, a shift with an arithmetic operand or a unary operator before a conversion, without parentheses | C2101 | 6.7.2 |\n| a second comparison operator in one `cmp_expr` | C2102 | 6.7.2 |\n| an `import_decl` after a `top_item` | C3012 | 6.15.1 |\n| `expect_fault` outside the header of a test | C3021 | 6.15.3 |\n| an expression statement that is not a call, or a keyword where a name is expected | C4012 | 6.10.1 |\n| a `memory_decl` inside a block | C4012 | 6.14.1 |\n| `..` in a `case_item` | C4022 | 6.10.5 |\n| a `case_clause` with no statement | C4023 | 6.10.5 |\n| `default` before a `case_clause`, or twice | C4025 | 6.10.5 |\n| `out` on a function parameter | C5001 | 6.9.5 |\n| a hole that does not match `hole`, other than in its `spec` | C1035 | 7.5.1 |\n| a hole in any other string literal | C1033 | 7.5.1 |\n| a single `}` in a string literal | C1039 | 6.4.8 |\n| a `spec` that does not match the production `spec` | C1037 | 7.5.3 |\n| blocks or expressions nested deeper than the implementation allows | C9004 | 5.3 |"
  },
  {
   "id": "spec-04p:codes-and-operation-identifiers",
   "edition": "SPEC-04P.2",
   "title": "Annex B (informative) Codes and operation identifiers",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#codes-and-operation-identifiers",
   "internal": 0,
   "content": "## Annex B (informative) Codes and operation identifiers\n\nThis annex collects the codes that translation and execution report: the diagnostic codes of translation (B.1), the fault codes of execution (B.2) and the operation identifiers that name the operation in a fault record (B.3). Each diagnostic code and fault code is defined in the subclause that the tables name. B.3 is the exception: it states the form and the spelling of operation identifiers, and its paragraphs that carry clause identifiers are normative."
  },
  {
   "id": "spec-04p:diagnostic-codes",
   "edition": "SPEC-04P.2",
   "title": "B.1 Diagnostic codes",
   "clauses": "LS-283 LS-313",
   "url": "/specifications/spec-04p/2/#diagnostic-codes",
   "internal": 0,
   "content": "### B.1 Diagnostic codes\n\n1. A diagnostic code is `C` followed by four digits, and its first digit gives its category, as the table of 5.1.3, paragraph 1 shows [LS-283].\n\n2. The table lists every diagnostic code, with its meaning and the subclause that defines it; that subclause gives its position. Five codes, C5051, C6002, C9001, C9002 and C9102, are reported by cint and not by the reference. C9102 is both a refusal and the code of some constraints (4, paragraph 4). cint refuses some constructs with C9102 before it reaches their other rules, so it does not report every code of the table [LS-313]."
  },
  {
   "id": "spec-04p:diagnostic-codes-p1",
   "edition": "SPEC-04P.2",
   "title": "B.1 Diagnostic codes (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#diagnostic-codes",
   "internal": 0,
   "content": "| Code | Meaning | Subclause |\n|---|---|---|\n| C1001 | a source file named with the extension `.cint` | 5.1.1 |\n| C1002 | a byte-order mark, invalid UTF-8 or the byte 0x00 | 6.4.1 |\n| C1003 | a forbidden invisible or bidirectional character | 6.4.1 |\n| C1004 | a control character, or a CR not followed by LF | 6.4.1, 6.4.2 |\n| C1005 | an unterminated block comment | 6.4.3 |\n| C1010 | a declared name that is `I`, `U`, `Q` or `T` followed only by digits | 6.4.4 |\n| C1011 | an unknown fault name after `expect_fault` | 6.4.4 |\n| C1012 | an identifier over 255 bytes | 6.4.4 |\n| C1013 | a non-ASCII character outside a literal or a comment | 6.4.1 |\n| C1020 | an uppercase radix prefix, such as `0X` | 6.4.5 |\n| C1021 | a misplaced digit separator `_` | 6.4.5 |\n| C1022 | a decimal literal of two or more digits that begins with `0` | 6.4.5 |\n| C1023 | a literal over 4,096 bits of magnitude | 6.4.5 |\n| C1024 | a radix prefix or a point with no digit after it, or a digit outside the radix | 6.4.5 |\n| C1030 | a character literal that is empty or holds more than one character | 6.4.7 |\n| C1031 | an escape that is not a Unicode scalar value | 6.4.7, 6.4.8 |\n| C1032 | an unknown escape, or `\\x` above 7F | 6.4.7, 6.4.8 |\n| C1033 | a hole outside a print statement or an `assert` message | 6.4.8, 7.5.1 |\n| C1034 | a line break in a string literal | 6.4.8 |\n| C1035 | an invalid hole: empty, unterminated, holding a string literal or an unparenthesized conditional expression, or naming an unknown conversion | 7.5.1 |\n| C1036 | a precision together with a scale | 7.5.3 |\n| C1037 | a format specification that does not match the syntax or does not apply to the value | 7.5.3, 7.5.4 |\n| C1038 | an unterminated string or character literal | 6.4.7, 6.4.8 |\n| C1039 | a single `}` in a string literal | 6.4.8 |\n| C1040 | an empty statement | 6.10.1 |\n| C1041 | an assignment in a condition | 6.10.2 |\n"
  },
  {
   "id": "spec-04p:fault-codes",
   "edition": "SPEC-04P.2",
   "title": "B.2 Fault codes",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#fault-codes",
   "internal": 0,
   "content": "### B.2 Fault codes\n\n3. A fault code names the kind of fault. Its number is the code's value in the canonical encodings of SPEC-01P.2. The table of 5.2.3, paragraph 1 lists every fault code with its number and the operations that raise it."
  },
  {
   "id": "spec-04p:operation-identifiers",
   "edition": "SPEC-04P.2",
   "title": "B.3 Operation identifiers",
   "clauses": "IM-130",
   "url": "/specifications/spec-04p/2/#operation-identifiers",
   "internal": 0,
   "content": "### B.3 Operation identifiers\n\n4. <a id=\"IM-130\"></a>The operation of a fault record, and the text after the caret in a fault report, is an operation identifier of this form. Every identifier is lowercase ASCII [IM-130]:\n\n```ebnf\nop_id      = name \".\" form \".\" op_type { \".\" op_type } [ \".\" mode ] | system_id ;\nform       = \"checked\" | \"wrap\" | \"sat\" | \"result\" | \"add\" | \"mul\" ;\nop_type    = \"i8\" | \"i16\" | \"i32\" | \"i64\" | \"i128\" | \"i256\" | \"i512\" | \"i1024\"\n           | \"u8\" | \"u16\" | \"u32\" | \"u64\" | \"u128\" | \"u256\" | \"u512\" | \"bool\"\n           | \"q\" digit { digit } \"_\" digit { digit } ;      (* Q16.16 is q16_16 *)\nname       = (* the name of the operation, as in the table of paragraph 9 *) ;\nmode       = (* a rounding mode name, 6.7.15 *) ;\nsystem_id  = \"fuel.charge\" | \"call.enter\"\n           | \"index.checked.\" ( op_type | \"struct\" ) | \"slice.checked.\" ( op_type | \"struct\" )\n           | \"copy.shape\" | \"copy.alias\" | \"decl.shape\"\n           | \"assert.checked.bool\" | \"format.char.\" op_type | \"unassigned\"\n           | \"bind.\" check_name\n           | \"arena.alloc\" | \"arena.reset\" | \"pool.deref\" | \"pool.insert\" | \"handle.check\" ;\ncheck_name = \"alias\" | \"injective\" | \"limit\" | \"permission\" | \"placement\"\n           | \"shape\" | \"stale\" | \"type\" | \"where\" ;\n```"
  },
  {
   "id": "spec-04p:operation-identifiers-p1",
   "edition": "SPEC-04P.2",
   "title": "B.3 Operation identifiers (part 2)",
   "clauses": "IM-131 IM-132 IM-133 IM-134",
   "url": "/specifications/spec-04p/2/#operation-identifiers",
   "internal": 0,
   "content": "5. <a id=\"IM-131\"></a>`form` is the form of the operator: `checked` for a checked operation, `wrap` and `sat` for the wrapping and saturating forms, and `result` for the result forms. `add` and `mul` occur only as the operation folded by `fold_checked` [IM-131].\n6. The first `op_type` is the operand type. A second `op_type` is present when the result type differs from the operand type: for a conversion, the source and then the target. `sum`, `dot` and `muldiv` always write the operand or element type and then the result type, even when the two are equal; `qmul` writes the types of its two operands and then of its result, and `mul_int` the fixed-point type and then the integer type [IM-132].\n7. `mode` is present exactly when the operation rounds, whether the mode was written or is the default. It names the mode the operation used [IM-133].\n8. A record holds the identifier of an operation that faulted. The wrapping, saturating and result forms of arithmetic never fault, so `sat` and `result` appear in no record, and `wrap` only in `shl.wrap.t`, the form of `<<%`, whose count is checked. Operations that cannot fault, such as the two-operand `min` and `max` (7.2.1), `uabs`, `mul_full`, `sum_wrap`, `sum_sat` and `count`, likewise appear in no record [IM-131].\n9. <a id=\"IM-134\"></a>The identifiers of the operations that can fault are these [IM-134]. In the table, `t` is the operand type, `s` and `t` the source and target of a conversion, `e` the element type, `r` the result type, `q`, `qa` and `qb` fixed-point types and `n` an integer type, each spelled as `op_type`:"
  },
  {
   "id": "spec-04p:operation-identifiers-p2",
   "edition": "SPEC-04P.2",
   "title": "B.3 Operation identifiers (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#operation-identifiers",
   "internal": 0,
   "content": "| Source form | Identifier | Faults | Example |\n|---|---|---|---|\n| `a + b`, `a - b`, `a * b` (integer); `+`, `-` (fixed point) | `add.checked.t`, `sub.checked.t`, `mul.checked.t` | `E_OVERFLOW` | `add.checked.i64` |\n| `-a` | `neg.checked.t` | `E_OVERFLOW` | `neg.checked.i64` |\n| `a / b`, `a % b` (integer) | `div.checked.t`, `rem.checked.t` | `E_DIV_ZERO`, `E_OVERFLOW` | `div.checked.i64` |\n| `div_trunc`, `rem_trunc`, `div_euclid`, `rem_euclid` | `name.checked.t` | `E_DIV_ZERO`, `E_OVERFLOW` | `rem_euclid.checked.i64` |\n| `div_round(a, b, mode)` | `div_round.checked.t.mode` | `E_DIV_ZERO`, `E_OVERFLOW` | `div_round.checked.i64.half_even` |\n| `a << k`, `a <<% k`, `a >> k` | `shl.checked.t`, `shl.wrap.t`, `shr.checked.t` | `E_OVERFLOW`, `E_SHIFT` | `shl.wrap.u8` |\n| `rotl`, `rotr` | `rotl.checked.t`, `rotr.checked.t` | `E_SHIFT` | `rotl.checked.u32` |\n| `abs` | `abs.checked.t` | `E_OVERFLOW` | `abs.checked.i8` |\n| `clamp(x, lo, hi)` | `clamp.checked.t` | `E_DOMAIN` | `clamp.checked.i64` |\n| `x as T` | `as.checked.s.t[.mode]` | `E_NARROW` | `as.checked.q16_16.i8.half_even` |\n| `muldiv(R, a, b, c, mode)` | `muldiv.checked.t.r.mode` | `E_DIV_ZERO`, `E_OVERFLOW` | `muldiv.checked.i64.i64.floor` |\n| `isqrt`, `isqrt_round` | `isqrt.checked.t`, `isqrt_round.checked.t.mode` | `E_DOMAIN`, `E_OVERFLOW` | `isqrt_round.checked.i128.half_even` |\n| fixed-point `*`, `mul` | `mul.checked.q.mode` | `E_OVERFLOW` | `mul.checked.q16_16.half_even` |\n| fixed-point `/`, `div` | `div.checked.q.mode` | `E_DIV_ZERO`, `E_OVERFLOW` | `div.checked.q16_16.floor` |\n| fixed-point `sqrt` | `sqrt.checked.q.mode` | `E_DOMAIN`, `E_OVERFLOW` | `sqrt.checked.q16_16.half_even` |\n| `qmul(R, a, b[, mode])` | `qmul.checked.qa.qb.r[.mode]` | `E_OVERFLOW` | `qmul.checked.q16_16.q1_15.q16_16.half_even` |\n| `mul_int(a, n)` | `mul_int.checked.q.n` | `E_OVERFLOW` | `mul_int.checked.q16_16.i64` |\n| `sum(R, xs)` | `sum"
  },
  {
   "id": "spec-04p:operation-identifiers-p3",
   "edition": "SPEC-04P.2",
   "title": "B.3 Operation identifiers (part 4)",
   "clauses": "IM-130 IM-135",
   "url": "/specifications/spec-04p/2/#operation-identifiers",
   "internal": 0,
   "content": "10. <a id=\"IM-135\"></a>The table fixes the spelling of each identifier. The subclause that defines the operation states its fault, its operands, its exact result and its limit [IM-135].\n11. The table lists the identifiers that a cint program can produce. The other `bind.` identifiers name checks on the arguments that a host program passes to an entry or a kernel, and SPEC-03P.1 defines them. An executor whose entry checks of a dispatch fail refuses it with one of the `bind.` checks that SPEC-02P.1 lists [IM-130]."
  },
  {
   "id": "spec-04p:defined-behavior-and-deliberate-absences",
   "edition": "SPEC-04P.2",
   "title": "Annex C (informative) Defined behavior and deliberate absences",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#defined-behavior-and-deliberate-absences",
   "internal": 0,
   "content": "## Annex C (informative) Defined behavior and deliberate absences\n\nThis annex is for a reader who knows C. C leaves many behaviors undefined, unspecified or to the implementation, and a C program that meets one of them can do different things on different compilers, or on the same compiler with different options. Clause 4, paragraph 6, states that within the scope of this document cint has no such behavior. C.1 lists, kind by kind, what cint does where C leaves the outcome open, and where C defines a behavior that cint defines differently. C.2 lists the features of C and of other languages that cint leaves out, each with its reason and what a program writes instead."
  },
  {
   "id": "spec-04p:behavior-that-c-leaves-open",
   "edition": "SPEC-04P.2",
   "title": "C.1 Behavior that C leaves open",
   "clauses": "IM-128",
   "url": "/specifications/spec-04p/2/#behavior-that-c-leaves-open",
   "internal": 0,
   "content": "### C.1 Behavior that C leaves open\n\n1. <a id=\"IM-128\"></a>Every operation of this document has a defined result or a defined fault for every input, and every program that is accepted has exactly one outcome for each set of semantic inputs (clause 4, paragraph 2). This claim is about the language. The claim that the C an implementation emits evaluates no C operation whose behavior C leaves undefined, and the assumptions that claim rests on, are stated in SPEC-09P.1; this annex adds nothing to that scope [IM-128].\n2. The tables below follow the lists of Annex J of the C standard, ISO/IEC 9899:2018 (C17). The first column names the C17 subclause that sets the behavior. The last column names the subclause of this document that defines what cint does."
  },
  {
   "id": "spec-04p:behavior-that-c-leaves-open-p1",
   "edition": "SPEC-04P.2",
   "title": "C.1 Behavior that C leaves open (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#behavior-that-c-leaves-open",
   "internal": 0,
   "content": "| C17 | Undefined in C | In cint | See |\n|---|---|---|---|\n| 6.5 | A signed arithmetic result outside the range of its type | Every plain operator is checked: the operation faults `E_OVERFLOW`. The wrapping operators `+%`, `-%` and `*%` and the saturating operators `+\\|`, `-\\|` and `*\\|`, give a defined result where the program writes them | 6.7.6, 6.7.7 |\n| 6.5.5 | Division or remainder by zero | `/` and `%` fault `E_DIV_ZERO` | 6.7.7 |\n| 6.5.5 | `INT_MIN / -1` and `INT_MIN % -1` | `MIN(T) / -1` faults `E_OVERFLOW`; `MIN(T) % -1` is 0 | 6.7.7 |\n| 6.5.7 | A shift count that is negative or not less than the width | The shift faults `E_SHIFT`. The count is not reduced modulo the width | 6.7.8 |\n| 6.5.7 | A left shift of a negative value, or one whose result does not fit | `a << k` is `a * 2^k`, checked like `*`: `-1 << 1` is -2, and a result outside the type faults `E_OVERFLOW` | 6.7.8 |\n| 6.5.2.1, 6.5.6 | An array subscript, or pointer arithmetic, outside the array object | There is no pointer arithmetic. Every index and every slice bound is checked against its extent, and one outside it faults `E_BOUNDS` | 6.12.2, 6.12.3 |\n| 6.2.4, 6.7.9 | Reading an automatic object that was not initialized | A variable of an integer type, of `Bool` or of an error-set type without an initializer is C2050. An array without one has every element 0 | 6.9.1, 6.12.1 |\n| 6.2.4 | Using an object, through a pointer, after its lifetime has ended | There are no pointers. A view cannot be stored in a struct, an array or a module-level variable, so it does not outlive what it refers to. A handle whose storage has been released faults `E_STALE_HANDLE` | 6.3.5, 6.14 |\n| 6.5 | Two unsequenced side effects on one object, or a side effect and an unsequenced read of it, as in `i = i++` | Assignment, compound assignment, `++` and `--` are statements, not expressions, and the operands of an expression a"
  },
  {
   "id": "spec-04p:behavior-that-c-leaves-open-p2",
   "edition": "SPEC-04P.2",
   "title": "C.1 Behavior that C leaves open (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#behavior-that-c-leaves-open",
   "internal": 0,
   "content": "| C17 | Unspecified in C | In cint | See |\n|---|---|---|---|\n| 6.5, 6.5.2.2 | The order in which the operands of an operator and the arguments of a call are evaluated, and the order of their side effects | From left to right. Each operand is evaluated completely before the next begins, and the first fault in that order is the one reported | 6.2.4 |\n| 6.5.16 | Which operand of an assignment is evaluated first | The place is evaluated and checked first, then the value, then the store is made | 6.2.4 |\n| 6.7.9 | The order of the side effects of the expressions in an initializer list | The elements of an array literal and the arguments of a struct constructor are evaluated from left to right | 6.2.4 |"
  },
  {
   "id": "spec-04p:behavior-that-c-leaves-open-p3",
   "edition": "SPEC-04P.2",
   "title": "C.1 Behavior that C leaves open (part 4)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#behavior-that-c-leaves-open",
   "internal": 0,
   "content": "| C17 | Implementation-defined in C | In cint | See |\n|---|---|---|---|\n| 5.2.4.2.1, 6.2.5 | The widths and ranges of `short`, `int`, `long` and `long long` | Every integer type name states its width: `I8` to `I1024` and `U8` to `U512`. The width fixes the range | 6.3.1 |\n| 6.2.5 | Whether plain `char` is signed | There is no `char` type. A character literal is an integer that takes its type from its context | 6.4.7, 6.5 |\n| 6.2.6.2 | The representation of signed integers, of which C17 permits three | A value is a member of Z, and its meaning does not depend on how it is represented. Arithmetic and conversions are defined on values | 6.2.1, 6.6 |\n| 6.3.1.3 | The result of converting a value to a signed type that cannot hold it | `as` faults `E_NARROW`; `as%` wraps the value into the type; `as?` returns an error | 6.6 |\n| 6.5.7 | The result of `>>` on a negative value | `a >> k` is `floor(a / 2^k)`: `-7 >> 1` is -4 | 6.7.8 |\n| 5.1.1.2, 5.2.1 | How the bytes of a source file map to the source character set | A source file is UTF-8 | 6.4.1 |\n| 5.2.4.1 | The translation limits above the minimums | Every implementation accepts the minimums of 5.3, and rejects a program beyond its own limits with a diagnostic | 5.3 |\n| 7.11, J.4 | Output that depends on the locale | A program's output bytes depend only on the program and its semantic inputs | 5.2.2, 7.5 |\n\n3. Some behaviors that C defines, cint defines differently. A C programmer meets these first:"
  },
  {
   "id": "spec-04p:behavior-that-c-leaves-open-p4",
   "edition": "SPEC-04P.2",
   "title": "C.1 Behavior that C leaves open (part 5)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#behavior-that-c-leaves-open",
   "internal": 0,
   "content": "| C17 | Defined in C | In cint | See |\n|---|---|---|---|\n| 6.2.5 | Unsigned arithmetic wraps modulo 2^N | Unsigned arithmetic is checked like signed arithmetic. `+%`, `-%` and `*%` wrap where the program writes them | 6.7.6, 6.7.7 |\n| 6.3.1.1, 6.3.1.8 | The integer promotions and the usual arithmetic conversions: `-1 < 1u` is 0 | There are no implicit conversions, except from an error set to a larger one (6.3.7). Operands of two different types are C2001 | 6.6, 6.7.10 |\n| 6.5.5 | `/` truncates toward 0: `-7 / 2` is -3 and `-7 % 2` is -1 | `/` rounds toward negative infinity, and a remainder other than 0 has the sign of the divisor: `-7 / 2` is -4 and `-7 % 2` is 1 | 6.7.7 |\n| 6.5.10 | `x & 1 == 0` is `x & (1 == 0)` | The bitwise operators bind tighter than the comparisons: `x & 1 == 0` is `(x & 1) == 0` | 6.7.1 |\n| 6.8.4.1, 6.8.5 | A condition is any scalar, and a value other than 0 is true | A condition has type `Bool`; an integer there is C2002 | 6.3.3 |\n| 6.8.4.2 | Control passes from one `case` into the next unless a `break` stops it | Control leaves the `switch` at the end of a clause, and continues into the next only after `fallthrough;` | 6.10.5 |\n| 6.5.16 | An assignment is an expression, so `if (x = 0)` compiles | An assignment is a statement; one written as a condition is C1041 | 6.7.14 |\n\n**Examples**\n\n4. This example shows floor division and the arithmetic right shift. A C compiler prints `-3 -1` for the first two values; the third is implementation-defined in C:\n\n```cint c_division.ci\nI64 a = -7;\nI64 b = 2;\n\"{a / b} {a % b} {a >> 1}\\n\";\n```\n\n```text\n-4 1 -4\n```\n\n5. `I64.min % -1` is 0. `I64.min / -1` has the exact result 2^63, one more than `I64.max`, so it faults:\n\n```cint c_min_div.ci\nI64 m = I64.min;\nI64 d = -1;\n\"{m % d}\\n\";\nI64 q = m / d;\n\"{q}\\n\";\n```"
  },
  {
   "id": "spec-04p:behavior-that-c-leaves-open-p5",
   "edition": "SPEC-04P.2",
   "title": "C.1 Behavior that C leaves open (part 6)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#behavior-that-c-leaves-open",
   "internal": 0,
   "content": "```text\n0\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> c_min_div.ci:4:11\n   |\n 4 | I64 q = m / d;\n   |           ^ div.checked.i64\n   |\n   = operation: div.checked.i64\n   = operand-count: 2\n   = operand: I64 -9223372036854775808\n   = operand: I64 -1\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n   ...\n```\n\n6. A shift count of 64 on `I64` faults. In C the shift is undefined; the x86-64 shift instruction uses the count modulo 64, so a compiler that emits that instruction gives 1, and one that folds the expression may give another value:\n\n```cint c_shift.ci\nI64 x = 1;\nI64 k = 64;\nI64 y = x << k;\n\"{y}\\n\";\n```\n\n```text\nfault[E_SHIFT]: shift count outside 0..w-1\n  --> c_shift.ci:3:11\n   |\n 3 | I64 y = x << k;\n   |           ^ shl.checked.i64\n   |\n   = operation: shl.checked.i64\n   = operand-count: 2\n   = operand: I64 1\n   = operand: I64 64\n   = exact:   none\n   = limit:   I64 63\n   ...\n```\n\n7. Unsigned arithmetic is checked. The wrapping operator gives the result that C's `uint8_t` arithmetic gives after conversion back to `uint8_t`:\n\n```cint c_unsigned.ci\nU8 a = 200;\nU8 b = 100;\nU8 w = a +% b;\n\"{w}\\n\";\nU8 c = a + b;\n\"{c}\\n\";\n```\n\n```text\n44\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> c_unsigned.ci:5:10\n   |\n 5 | U8 c = a + b;\n   |          ^ add.checked.u8\n   |\n   = operation: add.checked.u8\n   = operand-count: 2\n   = operand: U8 200\n   = operand: U8 100\n   = exact:   300\n   = limit:   U8 255\n   ...\n```\n\n8. A conversion to a narrower type that cannot hold the value faults, where C17 leaves the result to the implementation. `as%` keeps the low 8 bits:\n\n```cint c_narrow.ci\nI64 big = 300;\nI8 low = big as% I8;\n\"{low}\\n\";\nI8 small = big as I8;\n\"{small}\\n\";\n```"
  },
  {
   "id": "spec-04p:behavior-that-c-leaves-open-p6",
   "edition": "SPEC-04P.2",
   "title": "C.1 Behavior that C leaves open (part 7)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#behavior-that-c-leaves-open",
   "internal": 0,
   "content": "```text\n44\nfault[E_NARROW]: the value does not fit the destination type\n  --> c_narrow.ci:4:16\n   |\n 4 | I8 small = big as I8;\n   |                ^ as.checked.i64.i8\n   |\n   = operation: as.checked.i64.i8\n   = operand-count: 1\n   = operand: I64 300\n   = exact:   300\n   = limit:   I8 127\n   ...\n```\n\n9. In C, `-1 < 1u` converts -1 to `UINT_MAX` and is false. cint has no conversion to apply, so the comparison is rejected:\n\n```cint c_promotion.ci\nI64 a = -1;\nU64 b = 1;\nBool less = a < b;\n\"{less}\\n\";\n```\n\n```text\nerror[C2001]: type mismatch\n  --> c_promotion.ci:3:17\n   |\n 3 | Bool less = a < b;\n   |                 ^\n```\n\n10. A variable without an initializer is rejected, so no read can see an indeterminate value:\n\n```cint c_uninit.ci\nvoid main() {\n    I64 total;\n    \"{total}\\n\";\n}\n```\n\n```text\nerror[C2050]: uninitialized variable\n  --> c_uninit.ci:2:9\n   |\n 2 |     I64 total;\n   |         ^\n```\n\n11. A function that can reach its closing brace without a `return` is rejected, even when no call reaches it:\n\n```cint c_no_return.ci\nI64 ramp(I64 v) {\n    if (v > 0) {\n        return 1;\n    }\n}\n\"{ramp(5)}\\n\";\n```\n\n```text\nerror[C4001]: missing return\n  --> c_no_return.ci:1:5\n   |\n 1 | I64 ramp(I64 v) {\n   |     ^\n```\n\n12. A `switch` clause ends at the next `case`. The C reading of this code would print all three lines:\n\n```cint c_switch.ci\nI64 x = 4;\nswitch (x) {\n    case 4: { \"four\\n\"; }\n    case 5: { \"five\\n\"; }\n    default: { \"other\\n\"; }\n}\n```\n\n```text\nfour\n```\n\n**Notes**"
  },
  {
   "id": "spec-04p:behavior-that-c-leaves-open-p7",
   "edition": "SPEC-04P.2",
   "title": "C.1 Behavior that C leaves open (part 8)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#behavior-that-c-leaves-open",
   "internal": 0,
   "content": "13. C does not address what happens when deep recursion or large local arrays exhaust the stack, and on most hosts the process ends with a signal. In cint each entry has a call-depth limit and a frame arena, and passing either faults at the same operation on every implementation (5.2.5, 5.2.6).\n14. The scope of the claim excludes code reached through the host interface, defects in an implementation or in the C compiler that builds its output, hardware faults, and host resources an implementation cannot detect running out (clause 4, paragraph 6)."
  },
  {
   "id": "spec-04p:deliberate-absences",
   "edition": "SPEC-04P.2",
   "title": "C.2 Deliberate absences",
   "clauses": "LS-271",
   "url": "/specifications/spec-04p/2/#deliberate-absences",
   "internal": 0,
   "content": "### C.2 Deliberate absences\n\n1. <a id=\"LS-271\"></a>The features in the table below are absent from `cint-core-1`, and an implementation shall not add them [LS-271]."
  },
  {
   "id": "spec-04p:deliberate-absences-p1",
   "edition": "SPEC-04P.2",
   "title": "C.2 Deliberate absences (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#deliberate-absences",
   "internal": 0,
   "content": "| Absent | Reason | Instead |\n|---|---|---|\n| Floating-point types, literals and operations | Each operation rounds, so results are not exact. In C the result also depends on the evaluation format (`FLT_EVAL_METHOD`), on whether the compiler contracts an expression such as `a * b + c` into one operation with one rounding (C17 6.5), and on the math library | The fixed-point types (6.3.2), the wide integer types (6.3.1) and integers scaled by a unit the program chooses |\n| Raw pointers and pointer arithmetic | A pointer can alias anything and carries no bounds | Views, which carry a shape and a permission (6.3.5, 6.12); handles, checked by generation (6.14) |\n| Implicit conversions and the integer promotions | They change values without a trace in the text: in C, `-1 < 1u` is false | The conversions `as`, `as%` and `as?` (6.6); literals typed by their context (6.5). The one implicit conversion is from an error set to a larger one (6.3.7) |\n| The preprocessor and macros | Text substitution hides meaning from tools, and a diagnostic would point into text the programmer did not write | `const` declarations (6.9.2); modules and `import` (6.15.1) |\n| Undefined behavior | A program with undefined behavior has no meaning to debug or to compare | Checked operators and faults (5.2.3) |\n| Uninitialized variables | A read before the first write has no defined value | Required initializers (6.9.1); arrays with every element 0 (6.12.1) |\n| `goto`, `setjmp` and `longjmp` | Control can jump into or out of any block of a function | Labeled `break` and `continue` (6.10.6); `defer` and `errdefer` (6.10.7) |\n| Exceptions | Any call could leave the caller, unseen in its text | Error unions with `try` and `catch`, which mark each exit (6.3.7, 6.11); a fault stops the program and is not caught (5.2.3) |\n| Implicit `switch` fallthrough | A missing `break` is a known C weakness (CWE-484) | `fa"
  },
  {
   "id": "spec-04p:deliberate-absences-p2",
   "edition": "SPEC-04P.2",
   "title": "C.2 Deliberate absences (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#deliberate-absences",
   "internal": 0,
   "content": "**Examples**\n\n2. A second function with the name of the first is rejected at the second name, whatever its parameter types:\n\n```cint c_overload.ci\nI64 twice(I64 v) {\n    return v * 2;\n}\nI32 twice(I32 v) {\n    return v * 2;\n}\n\"{twice(4)}\\n\";\n```\n\n```text\nerror[C3001]: duplicate name\n  --> c_overload.ci:4:5\n   |\n 4 | I32 twice(I32 v) {\n   |     ^\n```\n\n3. The last element is reached by its index. An index of -1 is outside the extent:\n\n```cint c_negindex.ci\nvoid main() {\n    I64[3] a = [10, 20, 30];\n    I64 last = a[len(a) - 1];\n    \"{last}\\n\";\n    I64 k = -1;\n    I64 bad = a[k];\n    \"{bad}\\n\";\n}\n```\n\n```text\n30\nfault[E_BOUNDS]: index out of bounds\n  --> c_negindex.ci:6:16\n   |\n 6 |     I64 bad = a[k];\n   |                ^ index.checked.i64\n   |\n   = operation: index.checked.i64\n   = operand-count: 1\n   = operand: I64 -1\n   = exact:   none\n   = limit:   I64 3\n   ...\n```\n\n**Notes**\n\n4. Compile-time functions and a string type of variable length are not part of this edition, and they are not listed here (6.16)."
  },
  {
   "id": "spec-04p:cint-for-c-and-python-programmers",
   "edition": "SPEC-04P.2",
   "title": "Annex D (informative) cint for C and Python programmers",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#cint-for-c-and-python-programmers",
   "internal": 0,
   "content": "## Annex D (informative) cint for C and Python programmers\n\nThis annex lists the habits of each language that carry over and those that do not, and points each to the clause that holds the rule. Annex C lists the features that cint leaves out and gives the reasons. The Python spellings are those of the Python Language Reference and the Python Standard Library. The C spellings are those of ISO/IEC 9899:2018, except the case range `case 1 ... 5:`, which is a GCC extension."
  },
  {
   "id": "spec-04p:for-python-programmers",
   "edition": "SPEC-04P.2",
   "title": "D.1 For Python programmers",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#for-python-programmers",
   "internal": 0,
   "content": "### D.1 For Python programmers\n\n1. The habits in this table carry over with the change shown:\n\n| Python habit | cint spelling | Note |\n| --- | --- | --- |\n| `for i in range(n):` | `for i in 0..n { }` | Half-open, as in Python. `0..=n` includes `n` (6.10.4). |\n| `1_000_000` | `1_000_000` | As in PEP 515, except that `_` does not follow a base prefix: `0x_FF` is C1021 (6.4.5). |\n| `print(f\"x={x}\")` | `\"x={x}\\n\";` | A string literal on its own is a print statement. No newline is added (6.10.10). |\n| `f\"{x=}\"` | `\"{x=}\\n\";` | The same debug form (7.5.1). |\n| `a // b`, `a % b` | `a / b`, `a % b` | Floor division and its remainder, as in Python (6.7.7). |\n| `0 <= i < n` | `0 <= i && i < n` | A chained comparison is C2102 (6.7.2). |\n| `a[-1]` | `a[len(a) - 1]` | There are no negative indices: `a[-1]` faults with `E_BOUNDS` (6.12.2). |\n| `try: ... except E:` | `f() catch (e) { ... }` | For errors only. A fault is not caught (6.11.4). |\n| `with x:`, cleanup | `defer { ... }` | Runs when the block exits, by any path, and not after a fault (6.10.7). |\n| `assert x == y` with pytest | `assert(x == y);` inside `test \"name\" { }` | Both compared values are reported when the assertion fails (6.10.9, 6.15.3). |\n| `float` | none | Fixed point, such as `Q32.32` (6.3.2), or scaled integers, printed with a scale such as `{v:/100}` (7.5.3). |\n\n2. A Python `int` has no bound. Each cint integer type has a range, and every plain operator is checked: an operation whose exact result is outside the range faults (6.7). The forms `+%` and `+|` wrap and saturate where that is the intent (6.7.6).\n\n**Examples**\n\n3. This example shows a loop over a half-open range, the debug form of a hole and floor division:\n\n```cint py_loop.ci\nI64 total = 0;\nfor i in 0..5 {\n    total += i;\n}\n\"{total=} {-7 / 2} {-7 % 2}\\n\";\n```\n\n```text\ntotal=10 -4 1\n```"
  },
  {
   "id": "spec-04p:for-python-programmers-p1",
   "edition": "SPEC-04P.2",
   "title": "D.1 For Python programmers (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#for-python-programmers",
   "internal": 0,
   "content": "4. The last element is at `len(a) - 1`. An index of -1 is outside the array, and the fault record shows the index and the array's extent:\n\n```cint py_last.ci\nvoid main() {\n    I64[4] a = [10, 20, 30, 40];\n    \"{a[len(a) - 1]}\\n\";\n    \"{a[-1]}\\n\";\n}\n```\n\n```text\n40\nfault[E_BOUNDS]: index out of bounds\n  --> py_last.ci:4:8\n   |\n 4 |     \"{a[-1]}\\n\";\n   |        ^ index.checked.i64\n   |\n   = operation: index.checked.i64\n   = operand-count: 1\n   = operand: I64 -1\n   = exact:   none\n   = limit:   I64 4\n...\n```\n\n5. `defer` does the work of a `with` block or a `finally` clause. The deferred block runs when `step` returns, from the middle or from the end:\n\n```cint py_defer.ci\nvoid step(I64 k) {\n    \"open {k}\\n\";\n    defer {\n        \"close {k}\\n\";\n    }\n    if (k == 2) {\n        return;\n    }\n    \"work {k}\\n\";\n}\n\nfor k in 1..=2 {\n    step(k);\n}\n```\n\n```text\nopen 1\nwork 1\nclose 1\nopen 2\nclose 2\n```\n\n6. An expected failure is an error value, handled at the call:\n\n```cint py_catch.ci\nerror InputError { empty, too_long }\n\nInputError!I64 check_length(I64 n) {\n    if (n == 0) {\n        return .empty;\n    }\n    if (n > 80) {\n        return .too_long;\n    }\n    return n;\n}\n\nI64 a = check_length(12) catch 0;\nI64 b = check_length(0) catch 0;\n\"{a} {b}\\n\";\n```\n\n```text\n12 0\n```\n\n7. This example shows money in cents, held as an integer and printed with a scale:\n\n```cint py_cents.ci\nI64 cents = 123456;\nI64 fee = cents / 100;\n\"{cents:/100} {fee:/100}\\n\";\n```\n\n```text\n1234.56 12.34\n```\n\n8. A fixed-point value is a multiple of a power of two, held exactly. The hole prints that value with every digit:\n\n```cint py_third.ci\nQ32.32 third = 1.0 / 3;\n\"{third}\\n\";\n```\n\n```text\n0.33333333325572311878204345703125\n```\n\n9. A chained comparison is rejected, because Python and C read it differently:\n\n```cint py_chain.ci\nI64 i = 3;\nI64 n = 10;\nif (0 <= i < n) {\n    \"inside\\n\";\n}\n```"
  },
  {
   "id": "spec-04p:for-python-programmers-p2",
   "edition": "SPEC-04P.2",
   "title": "D.1 For Python programmers (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#for-python-programmers",
   "internal": 0,
   "content": "```text\nerror[C2102]: chained comparison\n  --> py_chain.ci:3:5\n   |\n 3 | if (0 <= i < n) {\n   |     ^\n```"
  },
  {
   "id": "spec-04p:for-c-programmers",
   "edition": "SPEC-04P.2",
   "title": "D.2 For C programmers",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#for-c-programmers",
   "internal": 0,
   "content": "### D.2 For C programmers\n\n1. The habits in this table carry over with the change shown:\n\n| C habit | cint spelling | Difference |\n| --- | --- | --- |\n| `int64_t x = 0;` | `I64 x = 0;` | A variable of an integer, fixed-point, `Bool` or error-set type always has an initializer (6.9.1). |\n| `(int32_t)x` | `x as I32` | Checked: `E_NARROW` when the value does not fit. `x as% I32` wraps (6.6). |\n| `x + y` with signed overflow | `x + y` | Faults with `E_OVERFLOW`, for signed and unsigned types alike. `x +% y` wraps and `x +| y` saturates (6.7.6). |\n| `switch` with fallthrough | `switch` without fallthrough | `fallthrough;` is written where it is meant. An empty case body is C4023 (6.10.5). |\n| `case 1 ... 5:` (GCC) | `case 1..=5:` | Case ranges are inclusive. `case 1..5:` is C4022 (6.10.5). |\n| `#include`, `#define` | `import name;`, `const` | There is no preprocessor (6.15.1, 6.9.2). |\n| `printf(\"%d\\n\", x)` | `\"{x}\\n\";` | Holes in a string literal (6.10.10, 7.5). |\n| `if (x)` with an integer `x` | `if (x != 0) { ... }` | A condition is `Bool` (C2002), and braces are required (C1043) (6.10.2). |\n| `(a & b) == c` | `a & b == c` | Bitwise operators bind more tightly than comparisons, so the parentheses that C needs can be left out (6.7.1). |\n| `int *p; p + 1` | views and indices | There are no pointers in source (6.12). |\n\n2. C leaves signed overflow, an index outside an array and a read of an uninitialized variable undefined. cint defines each: the first two fault, and the third cannot be written. Annex C goes through each kind of behavior that C leaves undefined, unspecified or implementation-defined.\n\n**Examples**\n\n3. Signed overflow is a fault, and its record holds the operands, the exact result and the bound it crossed:\n\n```cint c_overflow.ci\nI32 x = 2_147_483_647;\nI32 y = x + 1;\n\"{y}\\n\";\n```"
  },
  {
   "id": "spec-04p:for-c-programmers-p1",
   "edition": "SPEC-04P.2",
   "title": "D.2 For C programmers (part 2)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#for-c-programmers",
   "internal": 0,
   "content": "```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> c_overflow.ci:2:11\n   |\n 2 | I32 y = x + 1;\n   |           ^ add.checked.i32\n   |\n   = operation: add.checked.i32\n   = operand-count: 2\n   = operand: I32 2147483647\n   = operand: I32 1\n   = exact:   2147483648\n   = limit:   I32 2147483647\n...\n```\n\n4. Wrapping and saturation are written where they are meant, for unsigned types as for signed ones:\n\n```cint c_wrap.ci\nU8 a = 250;\nU8 b = 10;\nI64 big = 300;\n\"{a +% b} {a +| b} {big as% U8}\\n\";\n```\n\n```text\n4 255 44\n```\n\n5. A cast that loses information is a fault unless it is written to wrap:\n\n```cint c_narrow.ci\nI64 big = 300;\n\"{big as% U8}\\n\";\nU8 small = big as U8;\n\"{small}\\n\";\n```\n\n```text\n44\nfault[E_NARROW]: the value does not fit the destination type\n  --> c_narrow.ci:3:16\n   |\n 3 | U8 small = big as U8;\n   |                ^ as.checked.i64.u8\n   |\n   = operation: as.checked.i64.u8\n   = operand-count: 1\n   = operand: I64 300\n   = exact:   300\n   = limit:   U8 255\n...\n```\n\n6. `a & b == 2` tests the mask, as it reads. In C the same text compares `b` with 2 first:\n\n```cint c_prec.ci\nI64 a = 6;\nI64 b = 3;\nif (a & b == 2) {\n    \"the mask is 2\\n\";\n}\n\"{a & b == 2} {a | b}\\n\";\n```\n\n```text\nthe mask is 2\ntrue 7\n```\n\n7. A case falls through only where `fallthrough;` says so, and a case range is inclusive:\n\n```cint c_switch.ci\nvoid describe(I64 k) {\n    switch (k) {\n        case 0:\n            \"zero, \";\n            fallthrough;\n        case 1..=5:\n            \"small\\n\";\n        default:\n            \"large\\n\";\n    }\n}\n\ndescribe(0);\ndescribe(3);\ndescribe(9);\n```\n\n```text\nzero, small\nsmall\nlarge\n```\n\n8. An integer is not a condition:\n\n```cint c_if.ci\nI64 x = 3;\nif (x) {\n    \"nonzero\\n\";\n}\n```\n\n```text\nerror[C2002]: condition is not `Bool`\n  --> c_if.ci:2:5\n   |\n 2 | if (x) {\n   |     ^\n```"
  },
  {
   "id": "spec-04p:for-c-programmers-p2",
   "edition": "SPEC-04P.2",
   "title": "D.2 For C programmers (part 3)",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#for-c-programmers",
   "internal": 0,
   "content": "9. A function writes a caller's array through an `inout` view, where C would pass a pointer:\n\n```cint c_view.ci\nvoid bump(inout I64[_] counts, I64 k) {\n    counts[k] += 1;\n}\n\nvoid main() {\n    I64[3] counts;\n    bump(counts, 1);\n    bump(counts, 1);\n    \"{counts[1]}\\n\";\n}\n```\n\n```text\n2\n```"
  },
  {
   "id": "spec-04p:open-questions",
   "edition": "SPEC-04P.2",
   "title": "Annex E (informative) Open questions",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#open-questions",
   "internal": 0,
   "content": "## Annex E (informative) Open questions\n\nThis annex lists a question about a rule of this edition that the edition leaves open. Questions are numbered within each edition. Where this edition settles a question, the rule states the outcome, and the question is not listed here.\n\n1. **Checking a handle at a call.** In this edition a call does not check its handle arguments when it begins. Passing a stale handle does not fault, and the first use of it in the callee faults `E_STALE_HANDLE` (6.9.5, 6.14.4). The open question is whether a call checks each handle argument when it begins; such a check reports the fault at the caller's line. A caller that needs the fault at its own line uses the handle before the call."
  },
  {
   "id": "spec-04p:clause-index",
   "edition": "SPEC-04P.2",
   "title": "Annex F (informative) Clause index",
   "clauses": "IM-106",
   "url": "/specifications/spec-04p/2/#clause-index",
   "internal": 0,
   "content": "## Annex F (informative) Clause index\n\nEach clause identifier of this edition, with the section that states its rule and the sections that also cite it. Identifiers are the same in every edition and are never reused; section numbers belong to this edition. Each identifier has an anchor of its own name, such as `#IM-106`."
  },
  {
   "id": "spec-04p:clause-index-p1",
   "edition": "SPEC-04P.2",
   "title": "Annex F (informative) Clause index (part 2)",
   "clauses": "A-1 A-2 A-3 A-4 IM-1 IM-10 IM-100 IM-101 IM-102 IM-103 IM-104 IM-105",
   "url": "/specifications/spec-04p/2/#clause-index",
   "internal": 0,
   "content": "| Identifier | Stated in | Also cited in |\n|---|---|---|\n| A-1 | 6.13.2 |  |\n| A-2 | 6.13.2 |  |\n| A-3 | 6.13.2 |  |\n| A-4 | 6.13.2 |  |\n| IM-1 | 6.1 |  |\n| IM-4 | 6.3.1 |  |\n| IM-5 | 6.2.1 |  |\n| IM-6 | 6.3.1 |  |\n| IM-7 | 6.3.1 | 4 |\n| IM-8 | 6.3.1 |  |\n| IM-9 | 6.3.1 | 6.6 |\n| IM-10 | 6.3.3 | 6.6 |\n| IM-11 | 6.3.1 |  |\n| IM-16 | 6.3.1 |  |\n| IM-19 | 6.4.5 |  |\n| IM-20 | 6.4.7 | 6.4.5, 6.5 |\n| IM-21 | 6.5 |  |\n| IM-22 | 6.5 |  |\n| IM-23 | 6.8 |  |\n| IM-24 | 6.5 |  |\n| IM-25 | 6.4.5 |  |\n| IM-26 | 6.6 |  |\n| IM-27 | 6.5 |  |\n| IM-28 | 6.7.12 | 6.7, 6.7.5 |\n| IM-29 | 6.7.6 | 6.7.7, 6.7.12 |\n| IM-30 | 6.7.6 | 6.7.7, 6.7.12 |\n| IM-31 | 6.7 |  |\n| IM-32 | 6.7.6 | 6.7.7 |\n| IM-33 | 6.7.5 |  |\n| IM-34 | 6.7.5 |  |\n| IM-35 | 6.7.7 |  |\n| IM-36 | 7.2.2 |  |\n| IM-37 | 6.7.7 |  |\n| IM-39 | 6.7.7 | 7.2.2 |\n| IM-40 | 6.7.7 | 7.2.2 |\n| IM-41 | 6.7.7 |  |\n| IM-42 | 6.7.15 |  |\n| IM-43 | 6.7.15 |  |\n| IM-44 | 6.7.7 |  |\n| IM-45 | 6.7.8 |  |\n| IM-46 | 6.7.8 |  |\n| IM-47 | 6.7.9 | 6.7.5 |\n| IM-48 | 6.7.10 | 6.7.2 |\n| IM-49 | 7.2.1 |  |\n| IM-50 | 6.6 |  |\n| IM-51 | 7.2.3 | 7.1 |\n| IM-52 | 7.2.3 | 7.2.4 |\n| IM-53 | 7.2.3 |  |\n| IM-54 | 6.3.2 |  |\n| IM-55 | 6.3.2 |  |\n| IM-56 | 6.3 |  |\n| IM-57 | 6.6 |  |\n| IM-60 | 6.7.5 | 6.7.6, 6.7.8 |\n| IM-61 | 6.7.7 |  |\n| IM-62 | 6.7.7 |  |\n| IM-63 | 7.2.4 |  |\n| IM-64 | 7.2.4 |  |\n| IM-65 | 6.7.7 |  |\n| IM-66 | 6.7.7 |  |\n| IM-67 | 7.2.4 |  |\n| IM-68 | 6.6 |  |\n| IM-69 | 6.6 |  |\n| IM-74 | 7.3 |  |\n| IM-75 | 7.3 |  |\n| IM-76 | 7.3 |  |\n| IM-77 | 7.3 |  |\n| IM-78 | 7.3 |  |\n| IM-79 | 7.3 |  |\n| IM-80 | 7.3 |  |\n| IM-81 | 7.3 |  |\n| IM-82 | 7.3 |  |\n| IM-83 | 7.3 |  |\n| IM-84 | 7.3 |  |\n| IM-85 | 7.3 |  |\n| IM-87 | 7.3 |  |\n| IM-90 | 7.5.2 |  |\n| IM-92 | 6.2.4 |  |\n| IM-93 | 6.2.4 |  |\n| IM-94 | 6.2.4 |  |\n| IM-95 | 6.2.4 |  |\n| IM-96 | 6.2.4 |  |\n| IM-97 | 6.2.4 |  |\n| IM-98 | 6.2.4 |  |\n| IM-99 | 6.2.4 |  |\n| IM-100 | 6.2.4 |  |\n| IM-101 | 6.2.4 |"
  },
  {
   "id": "spec-04p:identifiers-that-moved",
   "edition": "SPEC-04P.2",
   "title": "F.1 Identifiers that moved",
   "clauses": "",
   "url": "/specifications/spec-04p/2/#identifiers-that-moved",
   "internal": 0,
   "content": "### F.1 Identifiers that moved\n\nIdentifiers that SPEC-04P.1 or SPEC-01P.1 held, with their place in those editions and in this one. An identifier of those editions that is not in this table or in the index above is stated in SPEC-01P.2 or is not a rule of this edition."
  },
  {
   "id": "spec-04p:identifiers-that-moved-p1",
   "edition": "SPEC-04P.2",
   "title": "F.1 Identifiers that moved (part 2)",
   "clauses": "IM-1 IM-10 IM-100 IM-101 IM-102 IM-103 IM-104 IM-105 IM-106 IM-107 IM-11 IM-111",
   "url": "/specifications/spec-04p/2/#identifiers-that-moved",
   "internal": 0,
   "content": "| Identifier | Earlier place | Place in this edition |\n|---|---|---|\n| IM-1 | SPEC-01P.1 1.2 | 6.1 |\n| IM-4 | SPEC-01P.1 2.1 | 6.3.1 |\n| IM-5 | SPEC-01P.1 2.1 | 6.2.1 |\n| IM-6 | SPEC-01P.1 2.1 | 6.3.1 |\n| IM-7 | SPEC-01P.1 2.2 | 6.3.1 |\n| IM-8 | SPEC-01P.1 2.2 | 6.3.1 |\n| IM-9 | SPEC-01P.1 2.2 | 6.3.1 |\n| IM-10 | SPEC-01P.1 2.3 | 6.3.3 |\n| IM-11 | SPEC-01P.1 2.4 | 6.3.1 |\n| IM-16 | SPEC-01P.1 2.4 | 6.3.1 |\n| IM-19 | SPEC-01P.1 3.1 | 6.4.5 |\n| IM-20 | SPEC-01P.1 3.1 | 6.4.7 |\n| IM-21 | SPEC-01P.1 3.2 | 6.5 |\n| IM-22 | SPEC-01P.1 3.2 | 6.5 |\n| IM-23 | SPEC-01P.1 3.2 | 6.8 |\n| IM-24 | SPEC-01P.1 3.2 | 6.5 |\n| IM-25 | SPEC-01P.1 3.2 | 6.4.5 |\n| IM-26 | SPEC-01P.1 3.2 | 6.6 |\n| IM-27 | SPEC-01P.1 3.2 | 6.5 |\n| IM-28 | SPEC-01P.1 4.1 | 6.7.12 |\n| IM-29 | SPEC-01P.1 4.1 | 6.7.6 |\n| IM-30 | SPEC-01P.1 4.1 | 6.7.6 |\n| IM-31 | SPEC-01P.1 4.1 | 6.7 |\n| IM-32 | SPEC-01P.1 4.2 | 6.7.6 |\n| IM-33 | SPEC-01P.1 4.3 | 6.7.5 |\n| IM-34 | SPEC-01P.1 4.3 | 6.7.5 |\n| IM-35 | SPEC-01P.1 4.4 | 6.7.7 |\n| IM-36 | SPEC-01P.1 4.4 | 7.2.2 |\n| IM-37 | SPEC-01P.1 4.4 | 6.7.7 |\n| IM-39 | SPEC-01P.1 4.4 | 6.7.7 |\n| IM-40 | SPEC-01P.1 4.4 | 6.7.7 |\n| IM-41 | SPEC-01P.1 4.4 | 6.7.7 |\n| IM-42 | SPEC-01P.1 4.5 | 6.7.15 |\n| IM-43 | SPEC-01P.1 4.5 | 6.7.15 |\n| IM-44 | SPEC-01P.1 4.5 | 6.7.7 |\n| IM-45 | SPEC-01P.1 4.6 | 6.7.8 |\n| IM-46 | SPEC-01P.1 4.6 | 6.7.8 |\n| IM-47 | SPEC-01P.1 4.7 | 6.7.9 |\n| IM-48 | SPEC-01P.1 4.8 | 6.7.10 |\n| IM-49 | SPEC-01P.1 4.8 | 7.2.1 |\n| IM-50 | SPEC-01P.1 4.9 | 6.6 |\n| IM-51 | SPEC-01P.1 4.10 | 7.2.3 |\n| IM-52 | SPEC-01P.1 4.10 | 7.2.3 |\n| IM-53 | SPEC-01P.1 4.10 | 7.2.3 |\n| IM-54 | SPEC-01P.1 5.1 | 6.3.2 |\n| IM-55 | SPEC-01P.1 5.1 | 6.3.2 |\n| IM-56 | SPEC-01P.1 5.1 | 6.3 |\n| IM-57 | SPEC-01P.1 5.1 | 6.6 |\n| IM-60 | SPEC-01P.1 5.2 | 6.7.5 |\n| IM-61 | SPEC-01P.1 5.3 | 6.7.7 |\n| IM-62 | SPEC-01P.1 5.3 | 6.7.7 |\n| IM-63 | SPEC-01P.1 5.3 | 7.2.4 |\n| IM-64 | SPEC-01P.1 5.3 | 7.2.4 "
  },
  {
   "id": "spec-06p:spec-06p-1",
   "edition": "SPEC-06P.1",
   "title": "SPEC-06P.1",
   "clauses": "",
   "url": "/specifications/spec-06p/1/",
   "internal": 0,
   "content": "# SPEC-06P.1: The cint tools\n\nSPEC-06P.1, edition 1 of the specification of the cint tools, cint v0.2.0, 2026-10-11.\n\nThis edition specifies the command lines, outputs and exit statuses of the tools of cint 0.2.0. The language they run is specified by SPEC-04P.2, and the byte encodings of the files they read and write by SPEC-01P.2."
  },
  {
   "id": "spec-06p:foreword",
   "edition": "SPEC-06P.1",
   "title": "Foreword",
   "clauses": "LS-234",
   "url": "/specifications/spec-06p/1/#foreword",
   "internal": 0,
   "content": "## Foreword\n\nThis document specifies the cint tools as cint 0.2.0 provides them: the `cint` command and the tools it starts, the interpreter `cint interp`, the workbench `cint workbench`, `cint explain` and `cint debug`.\n\nRules are numbered paragraphs within each section and are cited by section and paragraph, such as 5.4, paragraph 3. A rule that applies a clause of another cint specification ends with that clause's identifier in brackets, after the name of the edition that states the clause, such as [SPEC-04P.2 LS-234]. An identifier names one rule in every edition and document; section numbers belong to this edition only."
  },
  {
   "id": "spec-06p:introduction",
   "edition": "SPEC-06P.1",
   "title": "Introduction",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#introduction",
   "internal": 0,
   "content": "## Introduction\n\ncint is a C-family language whose every value is an integer of a declared type, or is built from such integers, and in which every plain operator is checked. Its tools turn a source file into a running program, and they also explain, record, replay and compare runs, so that a reader can find out why a program did what it did.\n\nThe first tool is `cint`. It compiles a program to C, builds it with the host C compiler, and runs it:\n\n```console\n$ cint run hello.ci\nhello, world\nanswer=42\n$ echo $?\n0\n```\n\nThe other tools work beside it. `cint interp` runs the same program from its intermediate representation without a C compiler, and records runs. `cint workbench` is an interactive session: each line typed at its prompt is compiled and run, and the session can show any value exactly, keep checkpoints and go back to an earlier state by replay. `cint explain` prints what the compiler knows about a function without running it. `cint debug` opens a recording, replays it, compares two executors on it and locates the boundary at which a run faulted.\n\nIn the source tree, `python3 tools/cint_bootstrap.py --leg LEG` builds `cint` with the C compiler `LEG`, one of `gcc`, `clang`, `apple-clang` and `msvc`. `python3 tools/cint_tools.py --leg LEG` then builds `cint-debug`, `cint-explain`, `cint-workbench`, `cint-repl` and `cint-interp` beside it."
  },
  {
   "id": "spec-06p:how-this-document-is-organized",
   "edition": "SPEC-06P.1",
   "title": "How this document is organized",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#how-this-document-is-organized",
   "internal": 0,
   "content": "### How this document is organized\n\nClauses 1 to 4 state the scope, the documents this one relies on, its terms and what conformance means for a tool. Clause 5 specifies the `cint` command, its four subcommands, and how it starts the other tools. Clause 6 lists the identities the tools print, and clause 7 the text and machine forms of diagnostics, fault reports and other messages. Clause 8 covers the interpreter, clause 9 the workbench and `cint explain`, and clause 10 `cint debug`. Clause 11 describes checkpoints, recordings and cases and clause 12 the receipts the tools write. Clause 13 lists directions beyond this edition. Annex A holds longer transcripts.\n\nExamples of programs are written in `cint` blocks, each followed by the exact output of `cint run`. Transcripts of the tools are written in `console` blocks. A line that starts with `$ ` is a command, and the lines after it are what the command wrote to standard output and standard error, in the order a terminal shows them. In a session, the text after a prompt `ci[1]> ` or `..> ` is what was typed. `$ echo $?` prints the exit status of the command before it. A line `...` stands for lines left out.\n\nEvery transcript was produced by the tools of cint 0.2.0. A digest in a transcript, such as a 64-digit revision identity (clause 6), is the value the tools printed for that file with that build; the text says what each digest is. Digests change when the source, the compiler or the runtime changes and timings change from run to run."
  },
  {
   "id": "spec-06p:scope",
   "edition": "SPEC-06P.1",
   "title": "1 Scope",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#scope",
   "internal": 0,
   "content": "## 1 Scope\n\n1. This document specifies, for cint 0.2.0:\n   - the `cint` command, with its subcommands `run`, `build`, `test` and `emit-c`;\n   - the identities that the tools print, and where they print them;\n   - the text and machine forms of diagnostics, fault reports, error results, test results and tool errors;\n   - the interpreter command `cint interp`;\n   - the workbench session `cint workbench`, also started as `cint repl` and the tool `cint explain`;\n   - the tool `cint debug` and its forms `diff`, `replay` and `locate`;\n   - checkpoints, recordings, cases and saved sessions as the tools make and show them;\n   - the receipts that the tools write.\n2. This document does not specify:\n   - the language, its faults, fuel and limits, which SPEC-04P.2 specifies;\n   - the byte encodings of fault records, state, checkpoints, recordings, cases and identities, which SPEC-01P.2 specifies;\n   - how an executor carries out a kernel dispatch, which SPEC-02P.1 specifies;\n   - the C and Python interfaces of a host program, which SPEC-03P.1 specifies;\n   - the intermediate representation, the C that the compiler emits, the toolchain file and the conformance suite, which SPEC-09P.1 specifies;\n   - the layout of the build cache beyond what 5.3 states, timings, and the wording of messages other than those this document quotes."
  },
  {
   "id": "spec-06p:normative-references",
   "edition": "SPEC-06P.1",
   "title": "2 Normative references",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#normative-references",
   "internal": 0,
   "content": "## 2 Normative references\n\nThe following documents are referred to in the text in such a way that some or all of their content constitutes requirements of this document. For dated references, only the edition cited applies.\n\n- SPEC-04P.2, *The cint language*, edition 2, cint v0.2.0.\n- SPEC-01P.2, *Canonical encodings and identity*, edition 2, cint v0.2.0.\n- SPEC-09P.1, *Toolchain and conformance*, edition 1, cint v0.2.0.\n- A. Rundgren, B. Jordan and S. Erdtman. *JSON Canonicalization Scheme (JCS)*. RFC 8785, June 2020. Used for the bytes of a receipt, with the departure in the escaping of strings that 12.1 states.\n- T. Bray, editor. *The JavaScript Object Notation (JSON) Data Interchange Format*. RFC 8259 (STD 90), December 2017.\n- F. Yergeau. *UTF-8, a transformation format of ISO 10646*. RFC 3629 (STD 63), November 2003.\n- G. Klyne and C. Newman. *Date and Time on the Internet: Timestamps*. RFC 3339, July 2002.\n- National Institute of Standards and Technology. *Secure Hash Standard (SHS)*. FIPS PUB 180-4, August 2015. Used for SHA-256."
  },
  {
   "id": "spec-06p:terms-definitions-and-symbols",
   "edition": "SPEC-06P.1",
   "title": "3 Terms, definitions and symbols",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "## 3 Terms, definitions and symbols\n\nFor the purposes of this document, the terms of SPEC-04P.2 clause 3 apply, among them value, fault, fault record, operation identifier, diagnostic, refusal, the reference, executor, entry, fuel, call depth, frame arena, semantic input, module, script and revision. The following terms also apply.\n\n<a id=\"term-tool\"></a>**3.1 tool**: the `cint` command, or one of the commands that it starts: `cint interp`, `cint workbench`, `cint repl`, `cint explain` and `cint debug` (5.1).\n\n<a id=\"term-exit-status\"></a>**3.2 exit status**: the integer a tool returns to the operating system when it ends, from the table of 5.2.\n\n<a id=\"term-tool-error\"></a>**3.3 tool error**: the refusal by a tool of its command line or its environment, such as an unknown option or an unreadable file. A tool error is not an outcome of a program, and a tool that reports one runs no program.\n\n<a id=\"term-machine-form\"></a><a id=\"term-text-form\"></a>**3.4 text form, machine form**: the two forms of a message. The *text form* is written for a person to read. The *machine form* is one JSON object, named by its `schema` key, written when the tool is given `--json`.\n\n<a id=\"term-output-set\"></a>**3.5 output set**: the files that `cint emit-c` writes for a program: the C of each module and of the program, the intermediate representation of each module as text, and a manifest of their digests (5.7).\n\n<a id=\"term-project-directory\"></a>**3.6 project directory**: a directory that holds a program's modules, either directly or in a subdirectory `src`, with the root module `main.ci` (5.5).\n\n<a id=\"term-boundary\"></a>**3.7 boundary**: a point of a run at which the state of its context is defined and its state hash is taken, such as the end of an entry that ran (SPEC-01P.2, 3.16)."
  },
  {
   "id": "spec-06p:terms-definitions-and-symbols-p1",
   "edition": "SPEC-06P.1",
   "title": "3 Terms, definitions and symbols (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "<a id=\"term-recording\"></a>**3.8 recording**: a file that holds a program, a checkpoint (3.10) of a context when recording began and the events that followed, from which the run can be replayed (SPEC-01P.2, 3.14).\n\n<a id=\"term-case\"></a>**3.9 case**: a recording that also holds the source text of every module of its program (SPEC-01P.2, 3.15).\n\n<a id=\"term-checkpoint\"></a>**3.10 checkpoint**: the canonical bytes of a state, taken between entries, from which a context can be restored (SPEC-01P.2, 3.11).\n\n<a id=\"term-replay\"></a>**3.11 replay**: running the entries of a recording again from its initial state with the recorded inputs, and comparing each boundary with the recording.\n\n<a id=\"term-receipt\"></a>**3.12 receipt**: a canonical JSON file that records one run of a tool: its inputs, its outcome and what it observed (SPEC-09P.1, 3.14).\n\n<a id=\"term-session\"></a>**3.13 session**: one run of the workbench: a sequence of entries and commands typed at its prompt, with the state they produce.\n\n<a id=\"term-identity\"></a>**3.14 identity**: a SHA-256 digest, written as 64 lowercase hexadecimal digits, that names a program, a file or a state (clause 6)."
  },
  {
   "id": "spec-06p:conformance",
   "edition": "SPEC-06P.1",
   "title": "4 Conformance",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#conformance",
   "internal": 0,
   "content": "## 4 Conformance\n\n1. In this document, \"shall\" states a requirement on a tool and \"may\" a permission.\n2. A conforming tool accepts the command lines this document specifies, writes the outputs it specifies to the channels it specifies, and ends with the exit status it specifies.\n3. The tools that run programs are implementations in the sense of SPEC-04P.2 clause 4. A program has one outcome for each set of semantic inputs: the same output bytes, the same fault record and the same fuel consumed under `cint run`, `cint test`, `cint interp` and the workbench.\n4. A text form is written for reading, and its wording may change from one release to the next, except for the layouts of diagnostics and fault reports, which 7.1 and 7.3 fix. A machine form names its format and version in its `schema` key, and a reader locates every field by its key, never by its position.\n5. A tool that cannot do what its command line asks reports a tool error, with exit status 4, 5 or 7, and the rules of the other statuses do not apply to it.\n6. Transcripts and Notes are informative. Where a transcript and a rule differ, the rule governs."
  },
  {
   "id": "spec-06p:the-cint-command",
   "edition": "SPEC-06P.1",
   "title": "5 The `cint` command",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#the-cint-command",
   "internal": 0,
   "content": "## 5 The `cint` command"
  },
  {
   "id": "spec-06p:command-line",
   "edition": "SPEC-06P.1",
   "title": "5.1 Command line",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#command-line",
   "internal": 0,
   "content": "### 5.1 Command line\n\n`cint` translates and runs programs, and it starts the other tools. Each use names one subcommand: `run` runs a program, `build` writes an executable or a library, `test` runs the tests of a module, and `emit-c` writes the C and the intermediate representation of a program without compiling them. The other tools are started as `cint NAME`.\n\n```text\ncint [--json] run [--receipt PATH] [--root DIR] [--toolchain FILE] [--cache DIR] FILE.ci\ncint [--json] build [--receipt PATH] [--root DIR] [--out DIR] [--lib] [--toolchain FILE] [--cache DIR] [FILE.ci | DIR]\ncint [--json] test [--receipt PATH] [--root DIR] [--toolchain FILE] [--cache DIR] [FILE.ci | DIR]\ncint [--json] emit-c --root DIR --out DIR [--toolchain FILE] MODULE.ci...\ncint NAME ARGUMENTS...\n```"
  },
  {
   "id": "spec-06p:command-line-p1",
   "edition": "SPEC-06P.1",
   "title": "5.1 Command line (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#command-line",
   "internal": 0,
   "content": "1. `cint --help` and `cint help` write the usage to standard output and exit with status 0. `cint` with no subcommand writes it to standard error and exits with status 4, and so does an unknown subcommand.\n2. `cint NAME` runs the executable `cint-NAME` (`cint-NAME.exe` on Windows) from the directory that holds `cint`, with every other argument in order, a `--json` written before `NAME` included, on the same standard input, standard output and standard error, so that `cint workbench` is interactive in a terminal; `cint` exits with that tool's exit status. A tool finds the `cint` beside it, so `cint` passes it no option of its own. The tools of 0.2.0 are `interp`, `workbench`, `repl`, `explain` and `debug`. A `NAME` is 1 to 64 lowercase letters, digits and `-`, and does not begin with `-`. A `NAME` outside that rule, or one with no executable `cint-NAME` beside `cint`, is an unknown subcommand, exit status 4, and an executable that `cint` cannot start gives exit status 5. Clauses 8 to 10 specify the arguments of each tool, and this document names each tool by its command: `cint debug` is the executable `cint-debug`.\n3. For `run`, `build`, `test` and `emit-c`, `--json` may appear anywhere on the command line. It selects the machine forms of clause 7 for everything the tool writes to standard error.\n4. The options and the file may appear in any order after the subcommand. Each option other than `--json` and `--lib` takes one value, and each may be given at most once; otherwise the exit status is 4, with the message \"an option needs one value and is given at most once\".\n5. An option that the subcommand does not take is a usage error, exit status 4. `--out` belongs to `build` and `emit-c`, `--lib` to `build` and `--receipt` and `--cache` to `run`, `build` and `test`.\n6. A program takes no arguments. `cint run` given more than one file exits with status 4, with the message \""
  },
  {
   "id": "spec-06p:command-line-p2",
   "edition": "SPEC-06P.1",
   "title": "5.1 Command line (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#command-line",
   "internal": 0,
   "content": "The options:\n\n| Option | Meaning |\n| --- | --- |\n| `--json` | Write the machine forms of clause 7 to standard error. |\n| `--receipt PATH` | Write a receipt of the run, the build or the tests to `PATH` (clause 12). |\n| `--root DIR` | The directory that module paths are relative to (5.3). |\n| `--toolchain FILE` | The toolchain file that names the host C compiler and its flags, in place of `cint.toolchain` beside `cint` (SPEC-09P.1). |\n| `--cache DIR` | The directory for the files of each build (5.3), in place of the one the toolchain file names. |\n| `--out DIR` | Where `build` writes its executable or library, or where `emit-c` writes its output set. |\n| `--lib` | `build` writes a shared library in place of an executable. |"
  },
  {
   "id": "spec-06p:exit-statuses",
   "edition": "SPEC-06P.1",
   "title": "5.2 Exit statuses",
   "clauses": "LS-221",
   "url": "/specifications/spec-06p/1/#exit-statuses",
   "internal": 0,
   "content": "### 5.2 Exit statuses\n\nEvery tool ends with one of eight exit statuses. A status says which kind of outcome the tool reached, so that a script can tell a program's fault from a failed check or a tool error.\n\n| Status | Meaning | Written by |\n| --- | --- | --- |\n| 0 | Success: the program ended normally, the build was written, every test passed, or the check found what it looked for. | every tool |\n| 1 | The program stopped with a fault. Standard output holds what it wrote before the fault. | `cint run`, `cint interp run` |\n| 2 | Translation rejected the program with a diagnostic, or refused it. Nothing ran. | `cint run`, `build`, `test`, `emit-c` |\n| 3 | A check failed: a test failed, a replay diverged or was refused, a comparison found a difference, a locate found no target, or a file is not a complete recording or checkpoint. | `cint test`, `cint interp`, `cint debug` |\n| 4 | Usage error: the command line is wrong. | every tool |\n| 5 | Environment error: a file cannot be read or written, or a tool or the host C compiler cannot be found. | every tool |\n| 6 | `main` returned an error. Standard error names the error set, the value and its tag. | `cint run`, `cint interp run` |\n| 7 | Internal error: the compiler faulted, the host C compiler rejected or warned on the emitted C, or the program process ended without a cint status. | every tool |\n\n1. A program that faults ends with status 1 and a program whose `main` returns an error with status 6; neither is a tool error. `main` returning an error is not a fault: the run completed and its result is an error value [SPEC-04P.2 LS-221].\n2. A tool error ends with status 4, 5 or 7, and its message is the only thing the tool writes to standard error."
  },
  {
   "id": "spec-06p:what-every-subcommand-does",
   "edition": "SPEC-06P.1",
   "title": "5.3 What every subcommand does",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#what-every-subcommand-does",
   "internal": 0,
   "content": "### 5.3 What every subcommand does"
  },
  {
   "id": "spec-06p:what-every-subcommand-does-p1",
   "edition": "SPEC-06P.1",
   "title": "5.3 What every subcommand does (part 2)",
   "clauses": "CINTC-12",
   "url": "/specifications/spec-06p/1/#what-every-subcommand-does",
   "internal": 0,
   "content": "1. *Channels.* Standard output carries only the bytes that the program's print statements write, byte for byte, and `cint` flushes it before it reports a fault. Everything else goes to standard error: diagnostics, the fault report, the error result of `main`, the line `built: PATH` of `cint build`, the line `receipt: PATH` when a receipt is written, and tool errors. Under `--json`, the lines `built:` and `receipt:` are not written, and every other line on standard error is one machine-form object (clause 7).\n2. *Module paths.* The root of a program is the directory of `FILE.ci`, or `--root DIR` when it is given; then `FILE.ci` is a path under that root. A module path is relative to the root: it is one or more segments separated by `/`, each made of ASCII letters, digits, `_`, `-` and `.`, with no empty segment and no segment `.` or `..`. Each segment, with `.ci` removed from the last one, is an identifier, so `import util.money;` names the file `util/money.ci` under the root. When the path of `FILE.ci` is outside this grammar, or the file is missing, a symbolic link, unreadable or larger than 4 MiB, `cint` exits with status 5. An imported module that is missing, a symbolic link, unreadable or larger than 4 MiB is the diagnostic C3009, and one whose path breaks the rule of SPEC-09P.1 7.1 is the diagnostic C3030, each with exit status 2 [SPEC-09P.1 CINTC-12].\n3. *The program process.* `cint run` and `cint test` build the program into a fresh directory of the cache, `CACHE/DIGEST/run-N`, where `DIGEST` is the SHA-256 digest of the root path and the source, and `N` counts the runs of that source. A build reuses nothing from earlier runs. The program runs as a child process whose standard input is the null device. Before it starts the host C compiler, `cint` removes the environment variables `CL`, `_CL_`, `LINK`, `_LINK_` and `CCC_OVERRIDE_OPTIONS`, which would change the "
  },
  {
   "id": "spec-06p:what-every-subcommand-does-p2",
   "edition": "SPEC-06P.1",
   "title": "5.3 What every subcommand does (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#what-every-subcommand-does",
   "internal": 0,
   "content": "| Subcommand | Fuel allowance | Call-depth limit | Frame arena | Executor |\n| --- | --- | --- | --- | --- |\n| `cint run` | none | 256 | 2,097,152 elements | `cpu-c17` |\n| `cint test` | 1,000,000,000 per test | 256 | 2,097,152 elements | `cpu-c17` |\n\n5. *Receipts.* With `--receipt PATH`, `cint` writes a receipt to `PATH` after the run, the build or the tests, and, without `--json`, writes the line `receipt: PATH` to standard error. Without `--receipt` no receipt is written; there is no default destination. A receipt is written for the exit statuses 0, 1, 2, 3 and 6.\n\n```console\n$ cint run --receipt hello.json hello.ci\nhello, world\nanswer=42\nreceipt: hello.json\n$ cint run --json --receipt hello.json hello.ci\nhello, world\nanswer=42\n```"
  },
  {
   "id": "spec-06p:cint-run",
   "edition": "SPEC-06P.1",
   "title": "5.4 `cint run`",
   "clauses": "LS-221",
   "url": "/specifications/spec-06p/1/#cint-run",
   "internal": 0,
   "content": "### 5.4 `cint run`\n\n`cint run FILE.ci` translates the program whose root module is `FILE.ci`, with every module it imports, builds it with the host C compiler, and runs it once on the executor `cpu-c17`.\n\n1. The root module shall have a program: top-level statements, which make it a script, or a function `main`. The script's statements, or `main`, run as one entry with the defaults of 5.3.\n2. A root module with neither is an importable module, and it has no program to run. `cint run` translates it, reports a usage error that names `cint test`, and exits with status 4; nothing runs.\n3. When the program ends normally, standard output holds what it printed and the exit status is 0.\n4. When the program faults, standard output holds the bytes it wrote before the fault, with no byte added, standard error holds the fault report of 7.3, and the exit status is 1.\n5. When translation rejects the program, standard error holds the diagnostics of 7.1, nothing runs, standard output is empty, and the exit status is 2.\n6. When `main` returns an error, standard output holds what the program printed, standard error holds one line `error: SET.VALUE (tag N)` (7.5), and the exit status is 6 [SPEC-04P.2 LS-221].\n7. `cint run` takes one file. A project directory is not a program for `cint run`; `cint build` (5.5) builds one.\n\nExamples\n\n8. A program that ends normally:\n\n```cint hello.ci\n\"hello, world\\n\";\nI64 answer = 6 * 7;\n\"answer={answer}\\n\";\n```\n\n```text\nhello, world\nanswer=42\n```\n\n9. A program that faults after it printed one line. Its report names the operation, both operands, the exact result and the bound it crossed:\n\n```cint partial.ci\nI64 big = I64.max;\n\"partial: big={big}\\n\";\nI64 r = big + 1;\n\"{r}\\n\";\n```"
  },
  {
   "id": "spec-06p:cint-run-p1",
   "edition": "SPEC-06P.1",
   "title": "5.4 `cint run` (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-run",
   "internal": 0,
   "content": "```text\npartial: big=9223372036854775807\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> partial.ci:3:13\n   |\n 3 | I64 r = big + 1;\n   |             ^ add.checked.i64\n   |\n   = operation: add.checked.i64\n   = operand-count: 2\n   = operand: I64 9223372036854775807\n   = operand: I64 1\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n   ...\n```\n\n10. The same program as a transcript, with its exit status:\n\n```console\n$ cint run partial.ci\npartial: big=9223372036854775807\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> partial.ci:3:13\n   |\n 3 | I64 r = big + 1;\n   |             ^ add.checked.i64\n   |\n   = operation: add.checked.i64\n   = operand-count: 2\n   = operand: I64 9223372036854775807\n   = operand: I64 1\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n   = revision: 2a5d25c827694f7bef7e0477ec0d760c95a7be976beaf854285a43555aeedef8\n   = source-map: none\n   = address: none\n   = stack-depth: 0\n   = fuel-consumed: 1 (not part of the fault record)\n   = state: the program stopped; stdout holds what it wrote before the fault\n$ echo $?\n1\n```\n\n11. A `main` that returns an error:\n\n```console\n$ cat ledger.ci\nerror LedgerError { overdrawn, frozen }\n\nLedgerError!I64 withdraw(I64 balance, I64 amount) {\n    if (amount > balance) {\n        return .overdrawn;\n    }\n    return balance - amount;\n}\n\nLedgerError!void main() {\n    I64 b = try withdraw(100, 30);\n    \"left: {b}\\n\";\n    I64 c = try withdraw(b, 500);\n    \"left: {c}\\n\";\n}\n$ cint run ledger.ci\nleft: 70\nerror: ledger.LedgerError.overdrawn (tag 1)\n$ echo $?\n6\n```\n\n12. A module without a program, and a command line without a file:"
  },
  {
   "id": "spec-06p:cint-run-p2",
   "edition": "SPEC-06P.1",
   "title": "5.4 `cint run` (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-run",
   "internal": 0,
   "content": "```console\n$ cint run prices.ci\n...\ncint: error: the root module has no main and no script statements, so there is no program; `cint test` runs its tests\n$ echo $?\n4\n$ cint --json run\n{\"category\":\"usage\",\"exit_status\":4,\"message\":\"no FILE.ci given\",\"schema\":\"CINT-TOOL-1\"}\n$ echo $?\n4\n```\n\nNote\n\n13. The fault report after a run of `cint` is written by `cint` from the fault record that the program process hands back; the program process itself writes no report. An executable written by `cint build` (5.5) therefore stops with exit status 1 and writes only what the program printed."
  },
  {
   "id": "spec-06p:cint-build",
   "edition": "SPEC-06P.1",
   "title": "5.5 `cint build`",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-build",
   "internal": 0,
   "content": "### 5.5 `cint build`\n\n`cint build` translates a program and writes it as an executable, or with `--lib` as a shared library, that runs without `cint`.\n\n1. `cint build FILE.ci` writes an executable named after the root module, without `.ci`, into `--out DIR`, by default the directory `build` under the root. On the `msvc` toolchain its name ends in `.exe`. The tool writes `built: PATH` to standard error.\n2. `cint build DIR` builds the project in the directory `DIR`: its root is `DIR/src` when that directory exists, and `DIR` otherwise, and its root module is `main.ci` there. `--out` defaults to `DIR/build`. A project directory takes no `--root`. `cint build` with no file or directory builds the project in the current directory.\n3. With `--lib`, the root module shall be an importable module, with no `main` and no top-level statements, and the tool writes a shared library, `lib<name>.so` on Linux, `lib<name>.dylib` on macOS and `<name>.dll` on Windows. `--lib` on a script or a module with `main` is a usage error, exit status 4. Without `--lib`, a root module with no program is the usage error of 5.4, paragraph 2.\n4. An executable built by `cint build` runs the program as `cint run` does, with the same defaults, and exits with status 0, 1 or 6. It writes no fault report (5.4, paragraph 13).\n5. The exit status of `cint build` is 0 when the file was written, 2 for a diagnostic and 4, 5 or 7 for a tool error.\n\nExample\n\n6. A script, a project with an imported module and a library:\n\n```console\n$ cint build hello.ci\nbuilt: ./build/hello\n$ ./build/hello\nhello, world\nanswer=42\n$ cint build shop\nbuilt: shop/build/main\n$ shop/build/main\n300 cents\n$ cint build --lib --out lib shop/src/util/money.ci\nbuilt: lib/libmoney.so\n```\n\nThe project `shop` holds `src/main.ci`, which imports `util.money` and calls `money.cents(3)`, and `src/util/money.ci`, which exports `cents`."
  },
  {
   "id": "spec-06p:cint-test",
   "edition": "SPEC-06P.1",
   "title": "5.6 `cint test`",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-test",
   "internal": 0,
   "content": "### 5.6 `cint test`\n\n`cint test` runs the `test` blocks of a module and reports which passed. Tests are part of the language, and SPEC-04P.2 specifies what passes and what fails; this section specifies how the tool runs them and what it prints."
  },
  {
   "id": "spec-06p:cint-test-p1",
   "edition": "SPEC-06P.1",
   "title": "5.6 `cint test` (part 2)",
   "clauses": "LS-234 LS-235 LS-236 LS-239 LS-240 LS-315",
   "url": "/specifications/spec-06p/1/#cint-test",
   "internal": 0,
   "content": "1. `cint test FILE.ci` runs the tests of `FILE.ci` and of every module it imports. `cint test DIR` runs those of the project in `DIR`, as 5.5 locates it. Modules are taken in the byte order of their paths, and the tests of a module in source order [SPEC-04P.2 LS-234].\n2. Each test runs in a process of its own, from a fresh context with fresh module state, with a fuel allowance of 1,000,000,000 and the other defaults of 5.3. The top-level statements of a script do not run under `cint test` [SPEC-04P.2 LS-234, LS-239].\n3. A test without `expect_fault` passes when its body completes. It fails on a fault, including a failed `assert`, and when an error leaves it through `try` [SPEC-04P.2 LS-235, LS-315].\n4. A test with the header `expect_fault CODE` passes only when its body faults with the fault code `CODE`. With `expect_fault CODE at LINE`, the fault shall also be on line `LINE`. The test fails when the body completes, when an error leaves it, or when it faults with another code or on another line [SPEC-04P.2 LS-236, LS-240].\n5. For each test, standard output receives one line, `test FILE:LINE \"NAME\" ... ok` or `... FAILED`, where `LINE` is the line of the `test` keyword. After the last test, one line gives the count, `K of N tests passed`.\n6. The reason for each failure goes to standard error after the test's line: the fault report of 7.3, whose `state` line reads \"the test stopped; its output is not shown\"; for an expected fault that did not come, `  expected fault CODE; the test completed`; for a fault with another code or on another line, the report and then `  expected fault CODE at line LINE`; and for an error that left the test, the line of 7.5 [SPEC-04P.2 LS-315]. A test's own prints are not shown.\n7. The exit status is 0 when every test passed, 3 when any failed and 2 when translation rejected a module.\n8. With `--json`, standard output receives one `CINT-TEST-1"
  },
  {
   "id": "spec-06p:cint-test-p2",
   "edition": "SPEC-06P.1",
   "title": "5.6 `cint test` (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-test",
   "internal": 0,
   "content": "Example\n\n9. `prices.ci` holds a function and three tests; the third asserts a wrong total:\n\n```console\n$ cat prices.ci\nexport I64 subtotal[n](in I64[n] c) {\n    return sum(c);\n}\n\ntest \"subtotal of three prices\" {\n    I64[3] cents = [1999, 425, 10];\n    assert(subtotal(cents) == 2434);\n}\n\ntest \"checked add overflows\" expect_fault E_OVERFLOW at 13 {\n    I64 big = 9223372036854775800;\n    I64 more = 12;\n    I64 r = big + more;\n}"
  },
  {
   "id": "spec-06p:cint-test-p3",
   "edition": "SPEC-06P.1",
   "title": "5.6 `cint test` (part 4)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-test",
   "internal": 0,
   "content": "test \"a wrong total\" {\n    I64[2] cents = [1, 2];\n    assert(subtotal(cents) == 4);\n}\n$ cint test prices.ci\ntest prices.ci:5 \"subtotal of three prices\" ... ok\ntest prices.ci:10 \"checked add overflows\" ... ok\ntest prices.ci:16 \"a wrong total\" ... FAILED\nfault[E_ASSERT]: assertion failed\n  --> prices.ci:18:12\n   |\n18 |     assert(subtotal(cents) == 4);\n   |            ^ assert.checked.bool\n   |\n   = operation: assert.checked.bool\n   = operand-count: 2\n   = operand: I64 3\n   = operand: I64 4\n   = exact:   none\n   = limit:   none\n   = revision: cec1064de267a83b4fa100a3396ea2b07101a24b452792c5021254e2d115c791\n   = source-map: none\n   = address: none\n   = stack-depth: 0\n   = fuel-consumed: 3 (not part of the fault record)\n   = state: the test stopped; its output is not shown\n2 of 3 tests passed\n$ echo $?\n3\n$ cint test --json prices.ci\n{\"expect_fault\":null,\"expect_line\":null,\"fault\":null,\"file\":\"prices.ci\",\"fuel_consumed\":\"3\",\"line\":5,\"name\":\"subtotal of three prices\",\"passed\":true,\"schema\":\"CINT-TEST-1\"}\n{\"expect_fault\":\"E_OVERFLOW\",\"expect_line\":13,\"fault\":{\"address\":null,\"code\":\"E_OVERFLOW\",\"column\":17,\"exact\":{\"t\":\"Z\",\"v\":\"9223372036854775812\"},\"file\":\"prices.ci\",\"limit\":{\"t\":\"I64\",\"v\":\"9223372036854775807\"},\"line\":13,\"operands\":[{\"t\":\"I64\",\"v\":\"9223372036854775800\"},{\"t\":\"I64\",\"v\":\"12\"}],\"operation\":\"add.checked.i64\",\"revision\":\"cec1064de267a83b4fa100a3396ea2b07101a24b452792c5021254e2d115c791\",\"schema\":\"CINT-FAULT-1\",\"severity\":\"fault\",\"source_map\":null,\"stack\":[]},\"file\":\"prices.ci\",\"fuel_consumed\":\"1\",\"line\":10,\"name\":\"checked add overflows\",\"passed\":true,\"schema\":\"CINT-TEST-1\"}\n{\"expect_fault\":null,\"expect_line\":null,\"fault\":{\"address\":null,\"code\":\"E_ASSERT\",\"column\":12,\"exact\":null,\"file\":\"prices.ci\",\"limit\":null,\"line\":18,\"operands\":[{\"t\":\"I64\",\"v\":\"3\"},{\"t\":\"I64\",\"v\":\"4\"}],\"operation\":\"assert.checked.bool\",\"revision\":\"cec1064de267a83b4fa100a3396ea2b07101a24b452792"
  },
  {
   "id": "spec-06p:cint-emit-c",
   "edition": "SPEC-06P.1",
   "title": "5.7 `cint emit-c`",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-emit-c",
   "internal": 0,
   "content": "### 5.7 `cint emit-c`\n\n`cint emit-c` writes the output set of a program: the C that `cint run` would compile, and the intermediate representation that `cint interp` runs. It compiles nothing and runs nothing.\n\n1. `cint emit-c --root DIR --out OUT MODULE.ci...` takes the module paths of the program under `DIR`, each module after every module it imports, with the root module last. It does not follow imports itself: a module named before a module it imports is rejected with a diagnostic, exit status 2. `--root` and `--out` are required, and `--receipt` and `--cache` are not taken.\n2. The output set goes into a new directory `OUT.stage-N`, where `N` is 0 for the first output set and goes up by one with each output set after it; the directory of the last output set is then removed. `OUT` itself receives one file, `MANIFEST.ref`, a line with the name of the current output set's directory and the SHA-256 digest of its manifest.\n3. The output set holds, for each module `M.ci`, the C file `M.c` and the text `M.sites`, which is the module's semantic intermediate representation (SIR) as text, with its table of source positions; the program's C, `cint-program.c`, and its list of modules, `cint-program.sites`; and `MANIFEST`. The manifest's first line is `cint-manifest-1`, and each further line gives a file's SHA-256 digest, its size in bytes and its name.\n4. `cint emit-c` writes nothing to standard output. Its exit status is 0, 2 for a diagnostic or 4, 5 or 7.\n\nExample\n\n5. Two output sets of the same program:\n\n```console\n$ cint emit-c --root . --out partial-out partial.ci\n$ ls partial-out partial-out.stage-0\npartial-out:\nMANIFEST.ref"
  },
  {
   "id": "spec-06p:cint-emit-c-p1",
   "edition": "SPEC-06P.1",
   "title": "5.7 `cint emit-c` (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-emit-c",
   "internal": 0,
   "content": "partial-out.stage-0:\nMANIFEST\ncint-program.c\ncint-program.sites\npartial.c\npartial.sites\n$ cat partial-out/MANIFEST.ref\npartial-out.stage-0 11425119e58fec71a9bc56e24d9149748a51404304d39434ea9368b9a7feb048\n$ cat partial-out.stage-0/MANIFEST\ncint-manifest-1\naaa6ca726178734f0106cb4db3a5b7815815a8905b8191847c0ce3a9e3dc254a 1342 cint-program.c\n20e6fd5b36ae765ab532d37eda6e49db797ca2d6991bf986ef97c3dca199f12b 20 cint-program.sites\ndfd5099400ef9f0329b507931706de2dbab83373ab661826e00805e59c70b63a 2223 partial.c\nb6dd6dc4d37dd2d3ac5af2d065a795cab0db8d03b749c7cd949a1eed8af6e81a 748 partial.sites\n$ cint emit-c --root . --out partial-out partial.ci\n$ ls -d partial-out*\npartial-out\npartial-out.stage-1\n```\n\nThe digests in `MANIFEST` are those of the emitted files; the sizes are in bytes."
  },
  {
   "id": "spec-06p:identities-as-the-tools-report-them",
   "edition": "SPEC-06P.1",
   "title": "6 Identities as the tools report them",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#identities-as-the-tools-report-them",
   "internal": 0,
   "content": "## 6 Identities as the tools report them\n\nThe tools name programs, files and states by identities: SHA-256 digests of a defined encoding of what they name. An identity lets two runs, two machines or two executors be compared by comparing 64 hexadecimal digits. SPEC-01P.2 specifies the encoding behind each identity; this clause lists what each one names and where the tools print it."
  },
  {
   "id": "spec-06p:identities-as-the-tools-report-them-p1",
   "edition": "SPEC-06P.1",
   "title": "6 Identities as the tools report them (part 2)",
   "clauses": "IM-157 IM-159 RCPT-08 SIR-17",
   "url": "/specifications/spec-06p/1/#identities-as-the-tools-report-them",
   "internal": 0,
   "content": "1. Every identity is a SHA-256 digest, written as 64 lowercase hexadecimal digits.\n2. The *revision identity* of a program is the digest of its meaning that SPEC-01P.2 9.1 lays out, over the profile, the runtime contract version and the SIR of each module without its source positions (SPEC-09P.1 6.5), so moving code to other lines leaves it unchanged [SPEC-01P.2 IM-157] [SPEC-09P.1 SIR-17].\n3. The *runtime contract version*, `cint-rt-3` in cint 0.2.0, names the interface and the meaning of the runtime that emitted code calls, and it is an input of the revision identity, as SPEC-09P.1 7.10 states [SPEC-09P.1 RCPT-08].\n4. The *source-map identity* is the digest of the table that maps each site of the program, each operation that can fault, to its module, line and position in the line. Two programs with the same revision identity and different layouts have different source-map identities.\n5. The same program has the same revision identity under every executor and every tool. The `revision` line of a fault report from `cint run`, the `revision` printed by `cint interp identity`, and the revision of a recording of that program are equal.\n6. The canonical fault record has a field for the source-map identity, and cint 0.2.0 writes none there: the `source-map` line of a fault report reads `none`, and the `source_map` key of `CINT-FAULT-1` is `null`. The source-map identity of a program is printed by `cint interp identity`, and it is held by its recordings and cases and named in their receipts.\n7. The *execution identity* of an entry is formed from the profile, the fuel model, the revision identity, the source-map identity, the entry, its arguments, the state it starts from, the effects supplied to it, its fuel allowance, its call-depth limit and its frame-arena capacity, as SPEC-04P.2 8.2 states [SPEC-04P.2 IM-159]. No tool of cint 0.2.0 prints it; a recording holds each of i"
  },
  {
   "id": "spec-06p:identities-as-the-tools-report-them-p2",
   "edition": "SPEC-06P.1",
   "title": "6 Identities as the tools report them (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#identities-as-the-tools-report-them",
   "internal": 0,
   "content": "| Identity | What it names | Where it is printed |\n| --- | --- | --- |\n| State hash | The canonical state of a context at a boundary | `state` of `cint debug replay` (10.3); `initial-state`, `state` and `state-hash` of `cint interp show` (11); `outcome.state_sha256` of a replay receipt; its first 8 digits in the workbench's `:effects` |\n| Chain head | Every boundary of a recording, through the digest chain of 11.2 | `chain` of `cint debug replay`; the last line of `cint interp replay`; `outcome.chain_head` of a replay receipt |\n| File digest | The bytes of one file | each line of an output set's `MANIFEST`, and its digest in `MANIFEST.ref` (5.7); `source.files`, `generated.files` and `runtime.files` of a receipt; `case.sha256` and `recording.sha256` of a replay or diff receipt; `outcome.stdout.sha256` of a run receipt |\n| Compiler source identity | The source files of the compiler | `identity.tool.compiler_source_identity` of a run, build or test receipt (12.3) |\n| Receipt identity | The `identity` and `outcome` of a receipt | `observations.receipt_identity_sha256` of every receipt (12.1) |\n\n9. The workbench also shows short forms, which are displays and not identities: `session@r3` names the third revision of the session's own module and `tally@r1` the first revision of a loaded module `tally`, counted within one session, and a build on `cpu-c17` names a revision by the first 8 digits of its identity.\n\nExample\n\n10. The output set of `partial.ci` (5.7), and that of the same program with one blank line added at its top, saved as `moved/partial.ci`. The revision identities are equal and the source-map identities differ:"
  },
  {
   "id": "spec-06p:identities-as-the-tools-report-them-p3",
   "edition": "SPEC-06P.1",
   "title": "6 Identities as the tools report them (part 4)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#identities-as-the-tools-report-them",
   "internal": 0,
   "content": "```console\n$ cint interp identity partial-out.stage-1\nrevision 2a5d25c827694f7bef7e0477ec0d760c95a7be976beaf854285a43555aeedef8\nsource-map be83426b1103002101ac0403acbc26b062cb5b2128a72bd55a423f9911c2a12b\n$ cint emit-c --root moved --out moved-out partial.ci\n$ cint interp identity moved-out.stage-0\nrevision 2a5d25c827694f7bef7e0477ec0d760c95a7be976beaf854285a43555aeedef8\nsource-map 9a20cbc476ac7c7ef8e65149165eca8c74b2ed0287e36b09c732531c0f2b8388\n```\n\nThe revision is the one `cint run partial.ci` printed in 5.4, paragraph 10."
  },
  {
   "id": "spec-06p:diagnostics-fault-reports-and-other-messages",
   "edition": "SPEC-06P.1",
   "title": "7 Diagnostics, fault reports and other messages",
   "clauses": "LS-289",
   "url": "/specifications/spec-06p/1/#diagnostics-fault-reports-and-other-messages",
   "internal": 0,
   "content": "## 7 Diagnostics, fault reports and other messages\n\nEvery tool other than the interpreter reports the same things in the same two forms; the interpreter has no machine form (7.7). The text form is laid out for reading in a terminal. The machine form, selected by `--json`, is one canonical JSON object per line, with the keys sorted, no whitespace and every integer that a program computes written as a typed exact decimal string, `{\"t\":\"I64\",\"v\":\"12\"}`, so that a reader that holds JSON numbers as binary floating point cannot change it [SPEC-04P.2 LS-289]. Each object names its format in its `schema` key."
  },
  {
   "id": "spec-06p:diagnostics-text-form",
   "edition": "SPEC-06P.1",
   "title": "7.1 Diagnostics: text form",
   "clauses": "LS-276 LS-277 LS-278 LS-279 LS-282 LS-283",
   "url": "/specifications/spec-06p/1/#diagnostics-text-form",
   "internal": 0,
   "content": "### 7.1 Diagnostics: text form\n\nA diagnostic reports a program that translation rejects. Its layout is the one fault reports share: a first line with the code and the message, the position and the source line with a caret under the position [SPEC-04P.2 LS-276].\n\n1. The layout is:\n\n```text\nerror[CODE]: MESSAGE\n  --> FILE:LINE:COLUMN\n   |\n N | SOURCE LINE\n   |         ^\n   |\n   = note: TEXT\n```\n\n`CODE` is the letter `C` and four digits; Annex B of SPEC-04P.2 lists every code [SPEC-04P.2 LS-283]. The severity is always `error`: the language has no warnings [SPEC-04P.2 LS-277]. A `note` line is present only where the diagnostic carries a note.\n2. The position is the first character of the offending construct, and the caret marks it. Lines and positions in a line count from 1, and a position in a line counts Unicode scalar values. A tab in the source line is repeated at the same place in the caret line, so the caret stays aligned at any tab width [SPEC-04P.2 LS-278, LS-279].\n3. Diagnostics are reported in the order of file, line, position in the line and code. `cint` stops at the first error it finds and reports the least diagnostic, in that order, among the errors of the earliest phase that finds one [SPEC-04P.2 LS-282].\n4. In the workbench, `FILE` is `entry N` for the text of entry `N`, and `inspect` for the expression of `:inspect` or `:type`.\n\nExamples\n\n5. A translation error:\n\n```cint widen.ci\nI32 a = 1;\nI64 b = a;\n\"{b}\\n\";\n```\n\n```text\nerror[C2001]: type mismatch\n  --> widen.ci:2:9\n   |\n 2 | I64 b = a;\n   |         ^\n```\n\n6. A diagnostic with a note, in both forms:"
  },
  {
   "id": "spec-06p:diagnostics-text-form-p1",
   "edition": "SPEC-06P.1",
   "title": "7.1 Diagnostics: text form (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#diagnostics-text-form",
   "internal": 0,
   "content": "```console\n$ cint run note.ci\nerror[C3004]: script local used in a function or test\n  --> note.ci:3:16\n   |\n 3 |     return x * limit;\n   |                ^\n   |\n   = note: this module is a script because of the top-level statement at note.ci:5:1\n$ cint run --json note.ci\n{\"code\":\"C3004\",\"column\":16,\"file\":\"note.ci\",\"line\":3,\"message\":\"script local used in a function or test\",\"notes\":[{\"column\":1,\"file\":\"note.ci\",\"line\":5,\"text\":\"this module is a script because of the top-level statement at note.ci:5:1\"}],\"schema\":\"CINT-DIAG-1\",\"severity\":\"error\"}\n```"
  },
  {
   "id": "spec-06p:diagnostics-machine-form",
   "edition": "SPEC-06P.1",
   "title": "7.2 Diagnostics: machine form",
   "clauses": "LS-289",
   "url": "/specifications/spec-06p/1/#diagnostics-machine-form",
   "internal": 0,
   "content": "### 7.2 Diagnostics: machine form\n\n1. Under `--json`, each diagnostic is one `CINT-DIAG-1` object on its own line of standard error, in the order of the text form [SPEC-04P.2 LS-289]. Its keys:\n\n| Key | Value |\n| --- | --- |\n| `schema` | `\"CINT-DIAG-1\"` |\n| `severity` | `\"error\"` |\n| `code` | The code, such as `\"C2001\"`. |\n| `message` | The message of the text form. |\n| `file`, `line`, `column` | The position, with `line` and `column` as JSON integers. |\n| `notes` | Present only when the diagnostic has notes: a list of objects with the keys `file`, `line`, `column` and `text`. |\n| `fault` | Present only for `C6001`, a fault during the evaluation of a constant, and `C6002`, the exhaustion of its fuel: the `CINT-FAULT-1` object of that fault. |"
  },
  {
   "id": "spec-06p:fault-reports-text-form",
   "edition": "SPEC-06P.1",
   "title": "7.3 Fault reports: text form",
   "clauses": "LS-276 LS-278 LS-284",
   "url": "/specifications/spec-06p/1/#fault-reports-text-form",
   "internal": 0,
   "content": "### 7.3 Fault reports: text form\n\nA fault report describes a fault: which operation stopped the program, on which operands, with which exact result, and where. Every tool prints it in the same layout [SPEC-04P.2 LS-276, LS-284].\n\n1. The report begins with `fault[CODE]: TITLE`, then the position `  --> FILE:LINE:COLUMN` and the source line, with a caret under the operator token of the faulting operation and the operation identifier beside it [SPEC-04P.2 LS-278]. The titles:\n\n| Code | Title |\n| --- | --- |\n| `E_OVERFLOW` | the exact result is outside the type's range |\n| `E_DIV_ZERO` | division by zero |\n| `E_BOUNDS` | index out of bounds |\n| `E_SHAPE` | shapes do not match |\n| `E_SHIFT` | shift count outside 0..w-1 |\n| `E_NARROW` | the value does not fit the destination type |\n| `E_ALIAS` | views overlap |\n| `E_STALE_HANDLE` | stale handle |\n| `E_FUEL` | fuel allowance exhausted |\n| `E_UNSUPPORTED` | not supported by this backend |\n| `E_DOMAIN` | operand outside the operation's domain |\n| `E_DEPTH` | call depth limit exceeded |\n| `E_ASSERT` | assertion failed |"
  },
  {
   "id": "spec-06p:fault-reports-text-form-p1",
   "edition": "SPEC-06P.1",
   "title": "7.3 Fault reports: text form (part 2)",
   "clauses": "IM-149 LS-280",
   "url": "/specifications/spec-06p/1/#fault-reports-text-form",
   "internal": 0,
   "content": "2. Then come the fields of the fault record, one per line, in this order, as SPEC-01P.2 6.1 encodes them [SPEC-01P.2 IM-149]:\n   - `operation`: the operation identifier;\n   - `operand-count`, then one `operand` line per operand, with its type and its exact value;\n   - `exact`: the exact result, or `none` where the fault has none;\n   - `limit`: the bound that the result crossed, with its type, or `none` [SPEC-04P.2 LS-280];\n   - `revision`: the revision identity of the program (clause 6);\n   - `source-map`: the field of the fault record that holds the program's source-map identity; cint 0.2.0 writes none there, so the line reads `none` (6, paragraph 6);\n   - `address`: for a fault inside a kernel dispatch, the kernel, the dispatch number counted from 0 within the entry, the phase (0 entry, 1 work-item, 2 epilogue), the work-item index and the step ordinal; `none` otherwise;\n   - `stack-depth`, then one `called from: FILE:LINE:COLUMN` line per active call, outermost first.\n3. Two lines follow that are not part of the record: `fuel-consumed: N (not part of the fault record)`, the fuel the entry had consumed and `state:`, a fixed sentence that says what the fault left. After `cint run` it reads \"the program stopped; stdout holds what it wrote before the fault\", and after `cint test` \"the test stopped; its output is not shown\". In the workbench and `cint debug` it says which state the session holds after the fault.\n4. Every value is printed exactly, in decimal, with its type. A value is never abbreviated, rounded or written with an exponent [SPEC-04P.2 LS-280].\n5. The workbench and `cint debug` add lines after `= noncanonical: not part of the fault record`: `stack-source`, the source line of each active call; `workbench-position`, the entry or boundary; `site`, the site identifier that `cint explain` prints (9.9); and `backend`, the executor that found the fault and whethe"
  },
  {
   "id": "spec-06p:fault-reports-text-form-p2",
   "edition": "SPEC-06P.1",
   "title": "7.3 Fault reports: text form (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#fault-reports-text-form",
   "internal": 0,
   "content": "Examples\n\n6. A fault inside a kernel dispatch, with its address and the two calls that led to it:\n\n```cint heat.ci\nkernel advance[n](in I64[n] old, in I64[n] increment, out I64[n] next) {\n    next = old + increment;\n}\n\nI64 run() {\n    I64[3] a = [0, 9223372036854775806, 0];\n    I64[3] d = [1, 5, -1];\n    I64[3] b;\n    advance(a, d, b);\n    return b[0];\n}\n\n\"{run()}\\n\";\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> heat.ci:2:16\n   |\n 2 |     next = old + increment;\n   |                ^ add.checked.i64\n   |\n   = operation: add.checked.i64\n   = operand-count: 2\n   = operand: I64 9223372036854775806\n   = operand: I64 5\n   = exact:   9223372036854775811\n   = limit:   I64 9223372036854775807\n   ...\n   = address: heat.advance, dispatch 0, phase 1, work-item 1, step 3\n   = stack-depth: 2\n   = called from: heat.ci:13:3\n   = called from: heat.ci:9:5\n   ...\n```"
  },
  {
   "id": "spec-06p:fault-reports-machine-form",
   "edition": "SPEC-06P.1",
   "title": "7.4 Fault reports: machine form",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#fault-reports-machine-form",
   "internal": 0,
   "content": "### 7.4 Fault reports: machine form\n\n1. Under `--json`, `cint run` writes the fault as one `CINT-FAULT-1` object on standard error, after the bytes the program wrote to standard output. Its keys:\n\n| Key | Value |\n| --- | --- |\n| `schema` | `\"CINT-FAULT-1\"` |\n| `severity` | `\"fault\"` |\n| `code`, `operation` | The fault code and the operation identifier. |\n| `file`, `line`, `column` | The position. |\n| `operands` | A list of typed values, `{\"t\":TYPE,\"v\":DECIMAL}`. |\n| `exact` | The exact result as a typed value of type `Z`, the integers or `null`. |\n| `limit` | The bound crossed, as a typed value, or `null`. |\n| `revision` | The revision identity. |\n| `source_map` | `null` in cint 0.2.0. |\n| `address` | `null`, or an object with the keys `kernel`, `dispatch`, `phase`, `work_item` and `step`; `phase` is a JSON integer and the others are strings. |\n| `stack` | The active calls, outermost first, each an object with `file`, `line` and `column`. |\n| `noncanonical` | The values that are not part of the record: `fuel_consumed`, a decimal string; from `cint debug`, also `backend`, `site` and `workbench_position`, the lines of 7.3, paragraph 5. |\n\n2. A fault report gives positions, not the extent of the offending expression or the names of functions. The machine form has no `span` key, and the entries of `stack` have no `function` key. In the text form the caret marks one position, and a `called from` line gives a position.\n3. The `fault` of a `CINT-TEST-1` object (7.6) and of a `CINT-DIAG-1` object has the same keys without `noncanonical`.\n\nExample\n\n4. The fault of 5.4, paragraph 9, in machine form. Standard output still holds the line the program printed:"
  },
  {
   "id": "spec-06p:fault-reports-machine-form-p1",
   "edition": "SPEC-06P.1",
   "title": "7.4 Fault reports: machine form (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#fault-reports-machine-form",
   "internal": 0,
   "content": "```console\n$ cint run --json partial.ci\npartial: big=9223372036854775807\n{\"address\":null,\"code\":\"E_OVERFLOW\",\"column\":13,\"exact\":{\"t\":\"Z\",\"v\":\"9223372036854775808\"},\"file\":\"partial.ci\",\"limit\":{\"t\":\"I64\",\"v\":\"9223372036854775807\"},\"line\":3,\"noncanonical\":{\"fuel_consumed\":\"1\"},\"operands\":[{\"t\":\"I64\",\"v\":\"9223372036854775807\"},{\"t\":\"I64\",\"v\":\"1\"}],\"operation\":\"add.checked.i64\",\"revision\":\"2a5d25c827694f7bef7e0477ec0d760c95a7be976beaf854285a43555aeedef8\",\"schema\":\"CINT-FAULT-1\",\"severity\":\"fault\",\"source_map\":null,\"stack\":[]}\n```"
  },
  {
   "id": "spec-06p:error-results",
   "edition": "SPEC-06P.1",
   "title": "7.5 Error results",
   "clauses": "LS-221",
   "url": "/specifications/spec-06p/1/#error-results",
   "internal": 0,
   "content": "### 7.5 Error results\n\n1. When `main` returns an error, `cint run` writes one line to standard error, `error: SET.VALUE (tag N)`. `SET` is the error set of `main`'s result, qualified by the module that declares it, `VALUE` is the name of the value, and `N` is its tag in that set [SPEC-04P.2 LS-221].\n2. Under `--json` the line is one `CINT-ERROR-1` object with the keys `schema` (`\"CINT-ERROR-1\"`), `set`, `value` and `tag`, a typed value of type `U16`.\n3. The same line reports an error that leaves a test (5.6) and the error result of a call made by the workbench's `:run` (9.4).\n\nExample\n\n4. The error result of `ledger.ci` (5.4, paragraph 11) in machine form:\n\n```console\n$ cint run --json ledger.ci\nleft: 70\n{\"schema\":\"CINT-ERROR-1\",\"set\":\"ledger.LedgerError\",\"tag\":{\"t\":\"U16\",\"v\":\"1\"},\"value\":\"overdrawn\"}\n```"
  },
  {
   "id": "spec-06p:test-results",
   "edition": "SPEC-06P.1",
   "title": "7.6 Test results",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#test-results",
   "internal": 0,
   "content": "### 7.6 Test results\n\n1. Under `--json`, `cint test` writes one `CINT-TEST-1` object per test to standard output, in the order the tests ran. Its keys:\n\n| Key | Value |\n| --- | --- |\n| `schema` | `\"CINT-TEST-1\"` |\n| `file`, `line`, `name` | The module, the line of the `test` keyword and the test's name. |\n| `passed` | `true` or `false`. |\n| `expect_fault`, `expect_line` | The code and the line of the test's `expect_fault` header, or `null`. |\n| `fault` | The fault the test raised, as in 7.4 without `noncanonical`, or `null`. |\n| `error` | Present only when an error left the test: its `CINT-ERROR-1` object. |\n| `fuel_consumed` | The fuel the test consumed, a decimal string. |"
  },
  {
   "id": "spec-06p:tool-errors",
   "edition": "SPEC-06P.1",
   "title": "7.7 Tool errors",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#tool-errors",
   "internal": 0,
   "content": "### 7.7 Tool errors\n\n1. The text form of a tool error is one line on standard error: the tool's name, `: error: ` and the message, such as `cint: error: no FILE.ci given` or `cint debug: error: cannot read nofile.rec`. The interpreter writes `cint-interp: ` and the message, and it has no machine form. `cint` writes its usage before the line of a usage error, and for a usage error the interpreter writes its usage alone.\n2. Under `--json`, a tool error is one `CINT-TOOL-1` object on standard error, with the keys `schema` (`\"CINT-TOOL-1\"`), `category` (`\"usage\"`, `\"environment\"` or `\"internal\"`), `exit_status` (4, 5 or 7) and `message`. When the host C compiler failed, the object also has `tool`, the compiler, `tool_exit_status`, its exit status and `log_path`, the log of 5.3, paragraph 3.\n\nExample\n\n3. A tool error from each of three tools:\n\n```console\n$ cint run --json hello.ci prices.ci\n{\"category\":\"usage\",\"exit_status\":4,\"message\":\"program arguments are not supported; give one FILE.ci\",\"schema\":\"CINT-TOOL-1\"}\n$ cint explain --json money.ci:nothing\n{\"category\":\"usage\",\"exit_status\":4,\"message\":\"money.ci has no function nothing\",\"schema\":\"CINT-TOOL-1\"}\n$ cint debug --json replay nofile.rec\n{\"category\":\"environment\",\"exit_status\":5,\"message\":\"cannot read nofile.rec\",\"schema\":\"CINT-TOOL-1\"}\n$ echo $?\n5\n```"
  },
  {
   "id": "spec-06p:the-interpreter",
   "edition": "SPEC-06P.1",
   "title": "8 The interpreter",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#the-interpreter",
   "internal": 0,
   "content": "## 8 The interpreter\n\nThe interpreter `cint interp` runs a program on the executor `cpu-sir-interp`: it reads the SIR text of the program's output set (5.7) and runs it, with no C compiler. It gives every program the outcome `cint run` gives it: the same output bytes, the same fault record and the same fuel consumed. It also records runs, replays recordings and shows checkpoints and recordings as text."
  },
  {
   "id": "spec-06p:command-line-2",
   "edition": "SPEC-06P.1",
   "title": "8.1 Command line",
   "clauses": "BACK-01a",
   "url": "/specifications/spec-06p/1/#command-line-2",
   "internal": 0,
   "content": "### 8.1 Command line\n\n```text\ncint interp [--trace PATH] run DIR [FAULT [FUEL [STATE]]]\ncint interp [--trace PATH] run --record [--boundary entry|dispatch] PATH DIR\ncint interp [--trace PATH] run --case [--boundary entry|dispatch] PATH --source SRC DIR\ncint interp replay [--stop K] [--echo] [--checkpoint PATH] [--receipt PATH] [--source-identity HEX] FILE\ncint interp show FILE\ncint interp identity DIR\ncint interp [--trace PATH] observe DIR OPTIONS\n```\n\n1. `DIR` is the directory of an output set that `cint emit-c` wrote, the one that `MANIFEST.ref` names. Before it runs anything, the interpreter reads the program's SIR text, checks the rules it relies on (each temporary is defined once and before it is used, every operand has the type its operation takes, and every operation that can fault has a site), and computes the program's revision identity. A text that breaks a rule is reported with its position and is not run, with exit status 3. A directory that cannot be read gives exit status 5 [SPEC-09P.1 BACK-01a].\n2. A command line that matches none of these forms gives the usage and exit status 4."
  },
  {
   "id": "spec-06p:running",
   "edition": "SPEC-06P.1",
   "title": "8.2 Running",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#running",
   "internal": 0,
   "content": "### 8.2 Running\n\n1. `run DIR` runs the program's entry, its script statements or `main`, with no fuel allowance, a call-depth limit of 256 and the frame arena of 5.3. Standard output receives the program's bytes. The exit status is that of `cint run`: 0, 1 for a fault, 6 when `main` returns an error. The interpreter writes no fault report and no error line.\n2. With `FAULT`, the interpreter writes the fault record, in the encoding of SPEC-01P.2, to the file `FAULT` when the program faults. With `FUEL`, it writes the fuel consumed, as a record whose domain is `cint-core-1/fuel-consumed/v1`. With `STATE`, it writes one line per module variable at the end of the run, `state.global MODULE NAME TYPE VALUE`; a program without module variables takes no `STATE`, exit status 4.\n3. `run --record PATH DIR` runs the program as `run` does and writes a recording of the run to `PATH` (11.2). The recording holds the SIR text of each module but not its source. Its exit status is that of `run`.\n4. `run --case PATH --source SRC DIR` writes a case in place of a recording: each module's source is read from the directory `SRC` under the module's path and kept in the case. A source that cannot be read gives exit status 5, and nothing is written.\n5. `--boundary` sets the density of a recording or a case: `entry`, the default, puts one boundary at the end of each entry; `dispatch` also puts one after each kernel dispatch publishes its outputs.\n6. `--trace PATH` writes one line per counted operation, call and return to the file `PATH`: the kind (`op`, `call` or `return`), the step ordinal, the site as module number and site number, the operation and each operand as 16 hexadecimal digits of its two's-complement bits, followed by `-> ` and the result when there is one."
  },
  {
   "id": "spec-06p:replaying-showing-and-identifying",
   "edition": "SPEC-06P.1",
   "title": "8.3 Replaying, showing and identifying",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#replaying-showing-and-identifying",
   "internal": 0,
   "content": "### 8.3 Replaying, showing and identifying"
  },
  {
   "id": "spec-06p:replaying-showing-and-identifying-p1",
   "edition": "SPEC-06P.1",
   "title": "8.3 Replaying, showing and identifying (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#replaying-showing-and-identifying",
   "internal": 0,
   "content": "1. `replay FILE` replays a recording or a case. It loads the code the file carries, checks that the code has the recorded revision identity, and runs each recorded entry again from the recorded initial state with the recorded inputs, comparing the digest of the state at each boundary with the recording's digest chain.\n2. It writes one line to standard error. When every boundary agrees, the line is `replay: ok, boundaries N, chain HEX`, where `HEX` is the chain head (6, paragraph 8), and the exit status is 0. When replay diverges, or meets an entry it cannot replay, the line names the status, the event and the boundaries replayed, and the exit status is 3. A file that is not a complete recording, or whose code does not have the recorded revision identity, gives exit status 3 with a line that says so.\n3. `--stop K` stops after boundary `K`. `--echo` writes the recorded print bytes to standard output, so that replay shows what the run printed; the interpreter prints nothing of its own while it replays. `--checkpoint PATH` writes a checkpoint of the state where replay stopped. `--receipt PATH` writes a replay receipt (12.4), and `--source-identity HEX`, 64 lowercase hexadecimal digits, gives the interpreter's source identity for it.\n4. `show FILE` prints a checkpoint, a recording or a case as text (clause 11). It reads the file through the decoders that a restore uses, so it shows no file that a restore would reject; such a file gives exit status 3.\n5. `identity DIR` prints two lines, `revision HEX` and `source-map HEX`, the identities of clause 6, with `absent` for a source-map identity that the text does not give. A text that does not load gives exit status 3.\n6. `observe DIR OPTIONS` is the observation interface through which the conformance suite runs a program on the interpreter. `OPTIONS` are the options of the conformance harness `cint-harness`, and SPEC-09P.1 9.6 "
  },
  {
   "id": "spec-06p:replaying-showing-and-identifying-p2",
   "edition": "SPEC-06P.1",
   "title": "8.3 Replaying, showing and identifying (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#replaying-showing-and-identifying",
   "internal": 0,
   "content": "Example\n\n7. Running, recording and replaying the output set of 5.7:\n\n```console\n$ cint interp run partial-out.stage-1\npartial: big=9223372036854775807\n$ echo $?\n1\n$ cint interp run --record partial.rec partial-out.stage-1\npartial: big=9223372036854775807\n$ cint interp replay partial.rec\nreplay: ok, boundaries 1, chain 49942e33499538df87f7e49b392c1c5aad6c557471959c567107f56b46ac400a\n$ cint interp replay --echo --checkpoint partial.ckpt partial.rec\npartial: big=9223372036854775807\nreplay: ok, boundaries 1, chain 49942e33499538df87f7e49b392c1c5aad6c557471959c567107f56b46ac400a\n$ cint interp run --case partial.cicase --source . partial-out.stage-1\npartial: big=9223372036854775807\n$ cint interp --trace partial.trace run partial-out.stage-1\npartial: big=9223372036854775807\n$ cat partial.trace\nop 0 0.3 add.checked.i64 0x7fffffffffffffff 0x0000000000000001\n```\n\nThe trace has one line: the faulting addition, step 0, at site 3 of module 0, with no result."
  },
  {
   "id": "spec-06p:the-workbench",
   "edition": "SPEC-06P.1",
   "title": "9 The workbench",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#the-workbench",
   "internal": 0,
   "content": "## 9 The workbench\n\nThe workbench is an interactive session on the language. Each line typed at its prompt is compiled by the compiler that `cint run` uses and run on the interpreter's executor, `cpu-sir-interp`, so an entry means what the same text means in a program. Between entries the session can show any value exactly, keep checkpoints of its state, go back to an earlier state, and replay what it ran."
  },
  {
   "id": "spec-06p:starting-a-session",
   "edition": "SPEC-06P.1",
   "title": "9.1 Starting a session",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#starting-a-session",
   "internal": 0,
   "content": "### 9.1 Starting a session\n\n```text\ncint workbench [--json] [--root DIR] [--cint PATH] [--out DIR] [--echo] [FILE.ci | DIR]\ncint repl [--json] [--root DIR] [--cint PATH] [--out DIR] [--echo] [FILE.ci | DIR]\n```\n\n1. `cint repl` is another name for `cint workbench`: it takes the same options and runs the same session.\n2. The session's root is `DIR`, the directory of `FILE.ci`, `--root DIR`, or the current directory, in that order of preference; with `--root`, `FILE.ci` is a path under the root. `--root` together with a directory is a usage error, exit status 4.\n3. A session started with `FILE.ci` loads that module first, as `:load` does (9.6), and its first prompt is `ci[2]>`.\n4. The session needs the `cint` executable, for the compiler and for builds on `cpu-c17`: `--cint PATH`, by default the `cint` in the directory that holds the `cint-workbench` executable. When it cannot be found the session does not start, and the exit status is 5. `--out DIR` is the directory for the session's build files, by default `build/workbench` under the root.\n5. The session writes one banner line, `cint workbench   profile cint-core-1   backend cpu-sir-interp   new session`, and then a prompt `ci[N]> `, where `N` is the ordinal the next entry takes. An entry whose braces are not closed continues on the next line after the prompt `..> `.\n6. `--echo` writes each line read after its prompt, so that the output of a session that reads from a file reads as a terminal shows it. `--json` selects the machine form of the tool errors that stop a session from starting (7.7).\n7. A line that starts with `:` is a command (9.8). Any other line is an entry (9.2).\n8. The session ends at `:quit`, or at the end of its input, with exit status 0. An interrupt (Ctrl+C) stops the running entry with the fault `E_FUEL`, or stops a compilation, which then changes nothing.\n\nExample\n\n9. Tool errors at the start:"
  },
  {
   "id": "spec-06p:starting-a-session-p1",
   "edition": "SPEC-06P.1",
   "title": "9.1 Starting a session (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#starting-a-session",
   "internal": 0,
   "content": "```console\n$ cint workbench --json --root . shop\n{\"category\":\"usage\",\"exit_status\":4,\"message\":\"--root and a root DIR exclude each other\",\"schema\":\"CINT-TOOL-1\"}\n$ echo $?\n4\n```"
  },
  {
   "id": "spec-06p:entries",
   "edition": "SPEC-06P.1",
   "title": "9.2 Entries",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#entries",
   "internal": 0,
   "content": "### 9.2 Entries\n\nAn entry is a declaration, a statement or an expression, typed as it would be written in a module. Every entry is one entry in the sense of SPEC-04P.2: it runs from its start to its boundary, with its own fuel and call depth."
  },
  {
   "id": "spec-06p:entries-p1",
   "edition": "SPEC-06P.1",
   "title": "9.2 Entries (part 2)",
   "clauses": "IM-121",
   "url": "/specifications/spec-06p/1/#entries",
   "internal": 0,
   "content": "1. A declaration adds a declaration to the session module, a module that belongs to the session, or replaces the declaration of the same name, and so makes a new revision of that module. A variable declared at the prompt is a module variable: it keeps its value from entry to entry, it is part of the state that checkpoints hold, and functions declared after it can use it.\n2. After a declaration the session prints what it declared: `NAME = VALUE : TYPE` for a variable; `NAME : SIGNATURE   revision session@rN` for a function, with `(replaces rM)` when it replaced revision `M`; `NAME   revision session@rN` for an error set; and for an array its type, its element count and its first elements.\n3. A statement runs and prints only what its print statements write. An expression prints `= VALUE : TYPE`.\n4. A value computed by `div_round` that discarded a nonzero remainder is followed by `inexact: div_round MODE (exact quotient Q)`, with the exact quotient in decimal.\n5. An entry that translation rejects prints its diagnostics (7.1), with the position `entry N:LINE:COLUMN`, and changes nothing but the entry ordinal.\n6. An entry that faults prints the fault report of 7.3 with the lines of 7.3, paragraph 5. The state it leaves is the state after a fault that SPEC-04P.2 defines: the stores of the statements that completed before the faulting one remain, and the faulting statement's own store does not happen [SPEC-04P.2 IM-121]. The session then clears the fault, which changes nothing else, so that the next entry can run; the report's `state` line says so with \"context reset\".\n7. Every entry takes the next ordinal, and so do `:run` (one per call), `:load` and `:reload`, whether they succeed or not. Other commands take none. The ordinal names the entry in positions, in `:log`, `:goto` and `:trace`.\n8. In a signature, a result of an error union type is shown as `U16!T`, the tag type o"
  },
  {
   "id": "spec-06p:entries-p2",
   "edition": "SPEC-06P.1",
   "title": "9.2 Entries (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#entries",
   "internal": 0,
   "content": "Example\n\n9. Entries of each kind, a fault, a translation error and the log:"
  },
  {
   "id": "spec-06p:entries-p3",
   "edition": "SPEC-06P.1",
   "title": "9.2 Entries (part 4)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#entries",
   "internal": 0,
   "content": "```console\n$ cint workbench\ncint workbench   profile cint-core-1   backend cpu-sir-interp   new session\nci[1]> \"hello, world\\n\";\nhello, world\nci[2]> I64 answer = 6 * 7;\nanswer = 42 : I64\nci[3]> answer * 2\n= 84 : I64\nci[4]> I64[3] cents = [1999, 425, 10];\ncents : I64[3]   3 elements   host\n  [0] = 1999\n  [1] = 425\n  [2] = 10\nci[5]> I64 subtotal = sum(cents);\nsubtotal = 2434 : I64\nci[6]> I64 tax = div_round(subtotal * 825, 10000, half_even);\ntax = 201 : I64   inexact: div_round half_even (exact quotient 200.805)\nci[7]> I64 big = 9223372036854775800;\nbig = 9223372036854775800 : I64\nci[8]> big + 12\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> entry 8:1:5\n   |\n 1 | big + 12\n   |     ^ add.checked.i64\n   |\n   = operation: add.checked.i64\n   = operand-count: 2\n   = operand: I64 9223372036854775800\n   = operand: I64 12\n   = exact:   9223372036854775812\n   = limit:   I64 9223372036854775807\n   = revision: 12ee022b9117fd23e4126c3214f104e3a7f56b3da489030dabcae5f8232cbf47\n   = source-map: none\n   = address: none\n   = stack-depth: 0\n   = fuel-consumed: 1 (not part of the fault record)\n   = state: no store completed in this entry; context reset\n   = noncanonical: not part of the fault record\n   = workbench-position: entry 8\n   = site: wb_entry#2\n   = backend: cpu-sir-interp\nci[9]> big +| 12\n= 9223372036854775807 : I64\nci[10]> I64 twice(I64 x) {\n..>     return x * 2;\n..> }\ntwice : (I64) -> I64   revision session@r6\nci[11]> twice(answer)\n= 84 : I64\nci[12]> I64 twice(I64 x) {\n..>     return x + x;\n..> }\ntwice : (I64) -> I64   revision session@r7 (replaces r6)\nci[13]> answer = answer + 1;\nci[14]> answer\n= 43 : I64\nci[15]> I64 oops = answer +;\nerror[C1050]: syntax error\n  --> entry 15:1:20\n   |\n 1 | I64 oops = answer +;\n   |                    ^\n   |\nci[16]> :log\nentry 1     done           \"hello, world\\n\";\nentry 2     declared       I64 answer = 6 * 7;\nentry 3 "
  },
  {
   "id": "spec-06p:entries-p4",
   "edition": "SPEC-06P.1",
   "title": "9.2 Entries (part 5)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#entries",
   "internal": 0,
   "content": "The site `wb_entry#2` is the addition in the function that the session made of entry 8."
  },
  {
   "id": "spec-06p:the-inspector",
   "edition": "SPEC-06P.1",
   "title": "9.3 The inspector",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#the-inspector",
   "internal": 0,
   "content": "### 9.3 The inspector\n\n`:inspect` shows a value exactly, in the formats a reader asks for, and `:type` shows the type of an expression without evaluating it. Neither is an entry.\n\n1. `:inspect EXPR [/FORMAT ...]` evaluates `EXPR` in a scratch copy of the current state and prints `EXPR : TYPE`, then the value. The expression shall be pure: one that prints, or calls a function that prints, is refused. A fault in the expression prints its report, whose `state` line reads \"nothing is kept: the session is as it was; context reset\" and whose `workbench-position` is `:inspect, not an entry`; the session's state does not change.\n2. `:type EXPR` prints `EXPR : TYPE` and evaluates nothing.\n3. An integer is shown in full decimal, with no exponent and no digit left out, whatever its width. A `Bool` is shown as `true` or `false`.\n4. The formats:"
  },
  {
   "id": "spec-06p:the-inspector-p1",
   "edition": "SPEC-06P.1",
   "title": "9.3 The inspector (part 2)",
   "clauses": "IM-80",
   "url": "/specifications/spec-06p/1/#the-inspector",
   "internal": 0,
   "content": "| Format | Shows |\n| --- | --- |\n| (none) | `exact`, the value in decimal. |\n| `/raw` | `raw`, the stored integer. |\n| `/hex` | `hex`, the two's-complement bits in hexadecimal, at the full width of the type. |\n| `/bin` | `bin`, the same in binary, in groups of 8 bits joined by `_` when the type is wider than 8 bits. |\n| `/bytes` | `bytes`, the storage bytes in memory order, least significant first, after their offset `+0:`. |\n| `/group` | `exact` with its digits in groups of three joined by `_`, which is also a valid literal. |\n| `/scale N` | `exact`, the value divided by `N` as an exact decimal, and `raw`; for example amounts in cents with `/scale 100`. The type does not change. |\n| `/all` | Every format above that applies, under a header that gives the type's kind and width, such as `(signed, 8 bits)`, `(unsigned, 32 bits)` or `(1 byte, 0 or 1)`. |\n| `/grid [R0..R1, C0..C1]` | For a rank-2 array, the rows `R0` up to but not including `R1` and the array positions `C0` up to but not including `C1`, with their indices. |\n| `/stats` | For an array: the element count; the exact sum, with the width of the accumulator that holds it without overflow, `w + ceil(log2 n)` bits for `n` elements of width `w`; the least and the greatest element with the index of its first occurrence; and the count of nonzero elements [SPEC-04P.2 IM-80]. |\n| `/view` | For an array: its element type, rank, shape, lower bounds, origin, strides in elements, permission and placement. |\n\n5. An array is shown with a summary line, `NAME : TYPE   N elements   PLACEMENT`, and its first 8 elements in index order, followed by a count of the elements not shown.\n6. `/stats` computes its sum with an accumulator of its own and never faults; it is a display, not an evaluation of the program's `sum`.\n\nExample\n\n7. Formats of three scalars, a fault in an inspected expression and an array:"
  },
  {
   "id": "spec-06p:the-inspector-p2",
   "edition": "SPEC-06P.1",
   "title": "9.3 The inspector (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#the-inspector",
   "internal": 0,
   "content": "```console\n$ cint workbench\ncint workbench   profile cint-core-1   backend cpu-sir-interp   new session\nci[1]> I8 x = -5;\nx = -5 : I8\nci[2]> :inspect x\nx : I8\n  exact   -5\nci[2]> :inspect x /all\nx : I8   (signed, 8 bits)\n  exact   -5\n  raw     -5\n  hex     0xfb\n  bin     0b11111011\n  bytes   +0: fb\nci[2]> U32 n = 4000000000;\nn = 4000000000 : U32\nci[3]> :inspect n /group\nn : U32\n  exact   4_000_000_000\nci[3]> :inspect n /all\nn : U32   (unsigned, 32 bits)\n  exact   4000000000\n  raw     4000000000\n  hex     0xee6b2800\n  bin     0b11101110_01101011_00101000_00000000\n  bytes   +0: 00 28 6b ee\nci[3]> Bool ok = n > 5;\nok = true : Bool\nci[4]> :inspect ok /all\nok : Bool   (1 byte, 0 or 1)\n  exact   true\n  raw     1\n  hex     0x01\n  bin     0b00000001\n  bytes   +0: 01\nci[4]> I64 cents = 2434;\ncents = 2434 : I64\nci[5]> :inspect cents /scale 100\ncents : I64   shown with scale 100\n  exact   24.34\n  raw     2434\nci[5]> :type n + 1\nn + 1 : U32\nci[5]> :inspect n + 1000000000\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> inspect:1:3\n   |\n 1 | n + 1000000000\n   |   ^ add.checked.u32\n   |\n   = operation: add.checked.u32\n   = operand-count: 2\n   = operand: U32 4000000000\n   = operand: U32 1000000000\n   = exact:   5000000000\n   = limit:   U32 4294967295\n   ...\n   = state: nothing is kept: the session is as it was; context reset\n   = noncanonical: not part of the fault record\n   = workbench-position: :inspect, not an entry\n   = site: wb_entry#2\n   = backend: cpu-sir-interp\nci[5]> I64[2, 3] g;\ng : I64[2, 3]   6 elements   host\n  [0, 0] = 0\n  [0, 1] = 0\n  [0, 2] = 0\n  [1, 0] = 0\n  [1, 1] = 0\n  [1, 2] = 0\nci[6]> g[1, 2] = 7;\nci[7]> g[0, 1] = -3;\nci[8]> :inspect g /grid [0..2, 1..3]\ng : I64[2, 3]   6 elements   host\n  grid   rows 0 to 1 of 0 to 1, columns 1 to 2 of 0 to 2\n      1  2\n  0  -3  0\n  1   0  7\nci[8]> :inspect g /stats\ng : I64[2, 3]   6 elements   host\n  count"
  },
  {
   "id": "spec-06p:the-inspector-p3",
   "edition": "SPEC-06P.1",
   "title": "9.3 The inspector (part 4)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#the-inspector",
   "internal": 0,
   "content": "The `sum` line left out of `/stats` gives the sum, 4, and the accumulator, `I67`: 64 bits and 3 more for 6 elements. The line left out of `/view` says that the array's buffer has no identity of its own."
  },
  {
   "id": "spec-06p:calls-fuel-and-call-depth",
   "edition": "SPEC-06P.1",
   "title": "9.4 Calls, fuel and call depth",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#calls-fuel-and-call-depth",
   "internal": 0,
   "content": "### 9.4 Calls, fuel and call depth\n\n`:run` calls an exported function of the session as an entry of its own, as a host program would call it. `:fuel` and `:depth` set the limits that each entry runs under, and `:fault` and `:trace` look back at the last fault.\n\n1. `:run F(ARGS) [N]` calls the function `F` `N` times, by default once. `F` shall be an export of the session module, declared at the prompt with `export`; a function that is not exported is refused, and so is an export of a loaded module. Each argument shall be an integer literal or `true` or `false`, a value of its parameter's type.\n2. Each call is one entry, with the function as the entry, so the function's calls start the stack of a fault report. A call that returns a value prints it as an expression does; one that returns an error prints the line of 7.5.\n3. A call that faults prints its report, with the position `entry E, call K of N`, then `K of N calls made`; the calls after it are not made.\n4. `:fault` prints the report of the last fault again, or the line of the last error result. `:fault /path` replays the entry of the last error result and prints the path the error took: the function that returned it, then each function that passed it on with `try`, innermost first, with the position of each call.\n5. `:fuel N` gives each entry that follows a fuel allowance of `N`, and `:fuel none` removes the allowance, which is the default. `:depth N` sets the call-depth limit of each entry that follows, 256 by default. An entry that exceeds either faults with `E_FUEL` or `E_DEPTH`, whose `limit` is the allowance or the limit.\n6. `:trace [N | fault]` replays entry `N`, by default the entry of the last fault, and prints its counted operations in order: the ordinal from 0, the position, the operation, the operands and the result or the fault code for the operation that faulted.\n\nExample"
  },
  {
   "id": "spec-06p:calls-fuel-and-call-depth-p1",
   "edition": "SPEC-06P.1",
   "title": "9.4 Calls, fuel and call depth (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#calls-fuel-and-call-depth",
   "internal": 0,
   "content": "7. An error result and its path, a function that `:run` refuses, the fuel and depth limits and a trace:"
  },
  {
   "id": "spec-06p:calls-fuel-and-call-depth-p2",
   "edition": "SPEC-06P.1",
   "title": "9.4 Calls, fuel and call depth (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#calls-fuel-and-call-depth",
   "internal": 0,
   "content": "```console\n$ cint workbench\ncint workbench   profile cint-core-1   backend cpu-sir-interp   new session\nci[1]> error Parse { empty, bad_digit }\nParse   revision session@r1\nci[2]> Parse!I64 digit(I64 c) {\n..>     if (c < 48 || c > 57) {\n..>         return .bad_digit;\n..>     }\n..>     return c - 48;\n..> }\ndigit : (I64) -> U16!I64   revision session@r2\nci[3]> export Parse!I64 two(I64 a, I64 b) {\n..>     I64 x = try digit(a);\n..>     I64 y = try digit(b);\n..>     return x * 10 + y;\n..> }\ntwo : (I64, I64) -> U16!I64 error E1   revision session@r3\nci[4]> :run two(52, 50)\n= 42 : I64\nci[5]> :run two(52, 120)\nerror: session.Parse.bad_digit (tag 2)\nci[6]> :fault /path\nentry 5   error: session.Parse.bad_digit (tag 2)   evaluator cpu-sir-interp, by replay\nthe path, innermost first, from the calls and returns of the replay:\n  digit returned the error (tag 2)\n  two passed it on with try (tag 2), from its call of digit at entry 3:3:17\nci[6]> I64 level = 10;\nlevel = 10 : I64\nci[7]> export void step() {\n..>     level = level * 3 - 7;\n..> }\nstep : () -> void   revision session@r5\nci[8]> :run step() 3\nci[11]> level\n= 179 : I64\nci[12]> :run digit(48)\n:run: digit is not an export of the session module (declare it with export)\nci[13]> :fuel 1\nfuel: 1 units per entry\nci[13]> export I64 count_to(I64 n) {\n..>     I64 t = 0;\n..>     for i in 0..n {\n..>         t += i;\n..>     }\n..>     return t;\n..> }\ncount_to : (I64) -> I64   revision session@r6\nci[14]> :run count_to(10)\nfault[E_FUEL]: fuel allowance exhausted\n  --> entry 13:3:5\n   |\n 3 |     for i in 0..n {\n   |     ^ fuel.charge\n   |\n   = operation: fuel.charge\n   = operand-count: 0\n   = exact:   none\n   = limit:   I64 1\n...\n   = workbench-position: entry 14\n   = site: count_to#11\n   = backend: cpu-sir-interp\nci[15]> :fuel none\nfuel: no allowance per entry\nci[15]> :run count_to(10)\n= 45 : I64\nci[16]> export I64 down(I64 n) {\n..>     if (n "
  },
  {
   "id": "spec-06p:calls-fuel-and-call-depth-p3",
   "edition": "SPEC-06P.1",
   "title": "9.4 Calls, fuel and call depth (part 4)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#calls-fuel-and-call-depth",
   "internal": 0,
   "content": "The call of `down` with depth limit 3 faults at the call that would make the fourth active call; the report lists the two calls made inside the entry.\n\n8. A fault in the second of three calls. The first call's store remains, and the third call is not made:\n\n```console\n$ cint workbench\ncint workbench   profile cint-core-1   backend cpu-sir-interp   new session\nci[1]> I64 cap = 100;\ncap = 100 : I64\nci[2]> export void grow() {\n..>     cap = cap * 1000000000;\n..> }\ngrow : () -> void   revision session@r2\nci[3]> :run grow() 3\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> entry 2:2:15\n   |\n 2 |     cap = cap * 1000000000;\n   |               ^ mul.checked.i64\n   |\n   = operation: mul.checked.i64\n   = operand-count: 2\n   = operand: I64 100000000000\n   = operand: I64 1000000000\n   = exact:   100000000000000000000\n   = limit:   I64 9223372036854775807\n...\n   = workbench-position: entry 4, call 2 of 3\n   = site: grow#2\n   = backend: cpu-sir-interp\n2 of 3 calls made\nci[5]> cap\n= 100000000000 : I64\nci[6]> :trace fault\nentry 4   :run grow() 3   evaluator cpu-sir-interp, by replay\n  ord  position           operation              operands                 value\n    0  entry 2:2:15       mul.checked.i64        100000000000, 1000000000 E_OVERFLOW\nci[6]> :quit --yes\n```"
  },
  {
   "id": "spec-06p:watches-checkpoints-and-history",
   "edition": "SPEC-06P.1",
   "title": "9.5 Watches, checkpoints and history",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#watches-checkpoints-and-history",
   "internal": 0,
   "content": "### 9.5 Watches, checkpoints and history\n\nA session keeps every state it reached. A *watch* reports when a value changes; a *checkpoint* names a state so that the session can come back to it; and the session reaches any earlier boundary again by replaying the entries that led to it."
  },
  {
   "id": "spec-06p:watches-checkpoints-and-history-p1",
   "edition": "SPEC-06P.1",
   "title": "9.5 Watches, checkpoints and history (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#watches-checkpoints-and-history",
   "internal": 0,
   "content": "1. `:watch EXPR [when COND] [stop]` adds a watch, numbers it and prints `watch K   EXPR = VALUE : TYPE`. After each following entry that changes the value of the pure expression `EXPR`, while the pure condition `COND`, when given, holds, the session prints `watch K   entry E   EXPR = VALUE`. With `stop`, a change that is reported ends the `:run` that made it after the current call, as if fewer calls had been asked for, and the session prints `a watch stops :run: K of N calls made`. A watch observes the state and changes nothing in it.\n2. At most 20 changes of one watch are printed for one command, followed by a count of the rest; `:watch log K` prints every change watch `K` recorded. `:watches` lists the watches, and `:unwatch K` removes watch `K`.\n3. `:checkpoint NAME` keeps the current state, the revisions of the session's modules and the per-entry settings under `NAME`, and prints the checkpoint's number, its module variables and its revisions. A checkpoint holds the code of its revisions, so a change of a file on disk after the checkpoint does not change what it means.\n4. `:diff NAME [BINDING]` compares the current state with checkpoint `NAME`, binding by binding in declaration order, and prints for each binding whether it differs, the count of differing elements and the first difference, with both values exactly.\n5. `:restore NAME` makes checkpoint `NAME` current: its state, its revisions and its settings. Before it does, it keeps the current state as an automatic checkpoint `auto-K`, unless an existing checkpoint holds the same state. When a loaded module's file differs from the restored revision, the session says so; `:reload` reads it. A restore does not undo what earlier entries printed.\n6. `:undo` goes back to the state before the last entry, after keeping the current state as an automatic checkpoint.\n7. `:goto N` makes the state at the end of entry `N` curr"
  },
  {
   "id": "spec-06p:watches-checkpoints-and-history-p2",
   "edition": "SPEC-06P.1",
   "title": "9.5 Watches, checkpoints and history (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#watches-checkpoints-and-history",
   "internal": 0,
   "content": "Example\n\n11. A watch that stops a `:run`, two checkpoints, a case of the entries since the second (9.6), and the commands that go back:"
  },
  {
   "id": "spec-06p:watches-checkpoints-and-history-p3",
   "edition": "SPEC-06P.1",
   "title": "9.5 Watches, checkpoints and history (part 4)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#watches-checkpoints-and-history",
   "internal": 0,
   "content": "```console\n$ cint workbench\ncint workbench   profile cint-core-1   backend cpu-sir-interp   new session\nci[1]> I64 level = 10;\nlevel = 10 : I64\nci[2]> I64 rate = 3;\nrate = 3 : I64\nci[3]> export void step() {\n..>     level = level * rate - 7;\n..> }\nstep : () -> void   revision session@r3\nci[4]> :checkpoint start\ncheckpoint start   #1   bindings 2   revisions: session@r3\nci[4]> :watch level\nwatch 1   level = 10 : I64\nci[4]> :watch level when level > 100 stop\nwatch 2   level = 10 : I64   when level > 100   stop\nci[4]> :run step() 6\nwatch 1   entry 4   level = 23\nwatch 1   entry 5   level = 62\nwatch 1   entry 6   level = 179\nwatch 2   entry 6   level = 179\na watch stops :run: 3 of 6 calls made\nci[7]> :watches\nwatch 1   level : I64\nwatch 2   level : I64   when level > 100   stop\nci[7]> :unwatch 2\nwatch 2 removed\nci[7]> :checkpoint after\ncheckpoint after   #2   bindings 2   revisions: session@r3\nci[7]> rate = 2;\nci[8]> :run step() 2\nwatch 1   entry 8   level = 351\nwatch 1   entry 9   level = 695\nci[10]> :diff after\nbinding   status      differing   first canonical difference\nlevel     differs     1           695 here, 179 in after\nrate      differs     1           2 here, 3 in after\nci[10]> :save-case grow.cicase\nnote: the case includes every recorded observe result verbatim; this case has none\ncase grow.cicase   checkpoint after   entries 7..9   effects 0   density entry\nci[10]> :undo\nsaved current state as auto-1\nback to the state before entry 9\nci[10]> :replay start --changed level\nsession.level last changed at entry 8, from 179 to 351\n...\nci[10]> :replay start --when level > 100\nlevel > 100 first holds at entry 6\n...\nci[10]> :replay after\nreplaying 2 entries from after to the current state (entry 7 to entry 8), comparing prints and outcomes with the recording\nwatch 1   entry 8   level = 351\nreplay matches the recording at 2 boundaries\nci[10]> :goto 5\nsaved current state"
  },
  {
   "id": "spec-06p:watches-checkpoints-and-history-p4",
   "edition": "SPEC-06P.1",
   "title": "9.5 Watches, checkpoints and history (part 5)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#watches-checkpoints-and-history",
   "internal": 0,
   "content": "The lines left out after `--changed` and `--when` give the number of boundaries replayed and the number of bisection probes."
  },
  {
   "id": "spec-06p:modules-saving-and-opening",
   "edition": "SPEC-06P.1",
   "title": "9.6 Modules, saving and opening",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#modules-saving-and-opening",
   "internal": 0,
   "content": "### 9.6 Modules, saving and opening"
  },
  {
   "id": "spec-06p:modules-saving-and-opening-p1",
   "edition": "SPEC-06P.1",
   "title": "9.6 Modules, saving and opening (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#modules-saving-and-opening",
   "internal": 0,
   "content": "1. `:load FILE.ci` loads a module under the root. A module with only declarations becomes a loaded module: the session prints `loaded NAME (FILE.ci)`, its exports are in scope as `NAME.X`, and an exported module variable may be assigned. A module with top-level statements is a script: its statements run as one entry, which prints what they print, and its declarations join the session module as one declaration named by the script's path; its variables stay local to that entry.\n2. `:reload` reads every loaded module again, makes a new revision of each one that changed, and prints `reloaded NAME (FILE.ci)`.\n3. `:save DIR` writes the session to the directory `DIR`: an `objects` directory, which holds the sources, states and records of the session by their digests, and the session manifest `session.manifest`, a text file from the line `CINT-SESSION-1` to the line `end`. The manifest is written last, so a save that stops early leaves no manifest, and such a directory is not opened. The session prints `saved session to DIR   entries N   checkpoints C   objects O`.\n4. `:open DIR` opens a saved session: its entries, checkpoints, branches and current state. It prints `opened DIR   entries N   checkpoints C   branch B`, and the next entry takes the ordinal after the saved ones. A saved session is data: opening it runs the code it holds only through replay of what it recorded.\n5. `:save-case PATH` writes a case (11.2) of the entries since the last checkpoint, from that checkpoint's state, and prints a note that the case holds every recorded input verbatim, then `case PATH   checkpoint NAME   entries A..B   effects K   density entry`. When no entry ran since the last checkpoint, no case is written and the session says so.\n6. `:quit` ends the session. When the session has changes since it was last saved, the first `:quit` says so and the session goes on; a second `:quit`, or `:quit"
  },
  {
   "id": "spec-06p:modules-saving-and-opening-p2",
   "edition": "SPEC-06P.1",
   "title": "9.6 Modules, saving and opening (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#modules-saving-and-opening",
   "internal": 0,
   "content": "Example\n\n12. A session started on a module, saved and opened again:\n\n```console\n$ cint workbench tally.ci\ncint workbench   profile cint-core-1   backend cpu-sir-interp   new session\nloaded tally (tally.ci)\nci[2]> tally.total\n= 0 : I64\nci[3]> tally.add(250);\nci[4]> tally.total = tally.total + 5;\nci[5]> export void deposit(I64 n) {\n..>     tally.add(n);\n..> }\ndeposit : (I64) -> void   revision session@r1\nci[6]> :checkpoint opened\ncheckpoint opened   #1   revisions: session@r1, tally@r1\nci[6]> :run deposit(100) 3\nci[9]> :reload\nreloaded tally (tally.ci)\nci[10]> :save-case deposits.cicase\nnote: the case includes every recorded observe result verbatim; this case has none\ncase deposits.cicase   checkpoint opened   entries 6..8   effects 0   density entry\nci[10]> :save saved\nsaved session to saved   entries 9   checkpoints 1   objects 39\nci[10]> :quit\n$ ls saved\nobjects\nsession.manifest\n$ head -1 saved/session.manifest\nCINT-SESSION-1\n$ tail -1 saved/session.manifest\nend\n$ cint workbench\ncint workbench   profile cint-core-1   backend cpu-sir-interp   new session\nci[1]> :open saved\nopened saved   entries 9   checkpoints 1   branch main\nci[10]> tally.total\n= 555 : I64\nci[11]> :quit --yes\n```\n\n`tally.ci` exports a variable `total` and a function `add` that adds its argument to it."
  },
  {
   "id": "spec-06p:executors",
   "edition": "SPEC-06P.1",
   "title": "9.7 Executors",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#executors",
   "internal": 0,
   "content": "### 9.7 Executors\n\n1. Entries run on `cpu-sir-interp` unless `:backend cpu-c17` selects the executor that `cint run` uses. On `cpu-c17`, each revision of the session's code is built as a library with `cint build --lib` the first time an entry needs it, and the session prints the time the build took; entries on `cpu-c17` are not recorded, and `:inspect` and the watches still run on `cpu-sir-interp`. `:backend` alone prints the executor in force.\n2. `:run F(ARGS) [N] --check B` runs each call on the executor in force and on `B` too, compares the two at each boundary, and stops at the first boundary where they differ; when they agree it prints `check: A and B agree at N boundaries`.\n3. `:backend gpu-cuda` and the commands `:place` and `:faults`, which place data on a device and list the work-items of a device fault, are refused: cint 0.2.0 builds no `gpu-cuda` library for a session.\n\nExample\n\n4. Two calls on `cpu-c17`, and two more checked against it:\n\n```console\n$ cint workbench\ncint workbench   profile cint-core-1   backend cpu-sir-interp   new session\nci[1]> I64 level = 10;\nlevel = 10 : I64\nci[2]> export void step() {\n..>     level = level * 3 - 7;\n..> }\nstep : () -> void   revision session@r2\nci[3]> :backend cpu-c17\nbackend: cpu-c17; each revision is built as a library, entries on it are not recorded, and :inspect and the watches stay on cpu-sir-interp\nci[3]> :run step() 2\ncpu-c17: revision 876902c8 built as a library in 6844 ms\nci[5]> level\ncpu-c17: revision b6bc2b52 built as a library in 504 ms\n= 62 : I64\nci[6]> :backend cpu-sir-interp\nbackend: cpu-sir-interp\nci[6]> :run step() 2 --check cpu-c17\ncheck: cpu-sir-interp and cpu-c17 agree at 2 boundaries\nci[8]> :quit --yes\n```\n\nThe expression entry `level` is compiled as code of its own, so it builds a second library."
  },
  {
   "id": "spec-06p:commands",
   "edition": "SPEC-06P.1",
   "title": "9.8 Commands",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#commands",
   "internal": 0,
   "content": "### 9.8 Commands\n\n1. Every command of a session:\n\n| Command | Does | Section |\n| --- | --- | --- |\n| `:load FILE.ci` | Load a module or run a script. | 9.6 |\n| `:reload` | Read the loaded modules again. | 9.6 |\n| `:run F(ARGS) [N] [--check B]` | Call an export of the session `N` times, each call an entry. | 9.4, 9.7 |\n| `:inspect EXPR [/FORMAT ...]` | Show a value exactly. | 9.3 |\n| `:type EXPR` | Show a type without evaluating. | 9.3 |\n| `:explain [NAME]` | What the compiler knows about the session's functions, as `cint explain` prints it. | 9.9 |\n| `:fault [/path]` | The last fault report or error result; the path of the error. | 9.4 |\n| `:fuel N`, `:fuel none` | The fuel allowance of each entry. | 9.4 |\n| `:depth N` | The call-depth limit of each entry. | 9.4 |\n| `:backend [ID]` | The executor of entries. | 9.7 |\n| `:trace [N \\| fault]` | The counted operations of an entry. | 9.4 |\n| `:watch EXPR [when COND] [stop]`, `:watch log K`, `:watches`, `:unwatch K` | Watches. | 9.5 |\n| `:checkpoint NAME`, `:restore NAME`, `:undo` | Keep and restore states. | 9.5 |\n| `:goto N`, `:goto fault` | Reach an earlier boundary by replay. | 9.5 |\n| `:branch NAME`, `:branches` | Branches and checkpoints. | 9.5 |\n| `:diff NAME [BINDING]` | Compare with a checkpoint. | 9.5 |\n| `:replay NAME [--changed BINDING \\| --when PRED]` | Replay since a checkpoint, or search it. | 9.5 |\n| `:history NAME`, `:log`, `:effects` | The history of a declaration, the entries, the recorded effects. | 9.5 |\n| `:save DIR`, `:open DIR`, `:save-case PATH` | Save, open and write a case. | 9.6 |\n| `:help` | A summary of the commands. | |\n| `:quit [--yes]`, `:q` | End the session. | 9.6 |\n\n2. An unknown command, or a known one with arguments it does not take, prints a line that says what it takes and changes nothing."
  },
  {
   "id": "spec-06p:cint-explain",
   "edition": "SPEC-06P.1",
   "title": "9.9 `cint explain`",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-explain",
   "internal": 0,
   "content": "### 9.9 `cint explain`\n\n`cint explain` prints what the compiler knows about a function without running it: its signature, every operation that can fault, its reductions, where it is charged fuel, which executors run it, and its SIR text.\n\n```text\ncint explain [--json] [--root DIR] [--cint PATH] [--out DIR | --sir DIR] FILE.ci[:NAME]\n```"
  },
  {
   "id": "spec-06p:cint-explain-p1",
   "edition": "SPEC-06P.1",
   "title": "9.9 `cint explain` (part 2)",
   "clauses": "CINTC-09 IM-80 SIR-07 SIR-09",
   "url": "/specifications/spec-06p/1/#cint-explain",
   "internal": 0,
   "content": "1. `cint explain` translates `FILE.ci` with `cint emit-c`, into `--out DIR`, by default `build/explain` under the root, or reads an output set that is already written from `--sir DIR`. `--out` and `--sir` exclude each other.\n2. The first line is `module FILE.ci   revision HEX`. With `:NAME`, one section follows for the function `NAME`; without it, a summary of the program and of the compiler's budget, then a section for each function. A `NAME` that the module does not define is a usage error, exit status 4.\n3. A function's section has these parts:\n   - `function NAME   MODULE.sites:LINE   EFFECTS`: the line at which the function begins in the module's SIR text, the file `MODULE.sites` of the output set (5.7), which is not a position in the source; and whether the function is `pure`;\n   - `signature`: each parameter with its direction, `in` or `view`, its name and its type and the result;\n   - `fault sites`: the count of sites that can fault and of those excluded, then one line per site with its identifier `NAME#N`, its position, its operation and the fault codes it can raise. A site identifier is the site number of the program in node order; fault reports of the workbench name it in their `site` line. In cint 0.2.0 no site is excluded, and every site is reported as `possible`;\n   - `reductions`: for each reduction, its operation, its result type and the accumulator width, `w + ceil(log2 n)` bits for `n` terms of width `w`, which holds every partial sum exactly [SPEC-04P.2 IM-80];\n   - `fuel`: each charge point, a `fuel.charge` node of the SIR, with its amount and where it is charged; fuel is charged at these nodes and at no other point, so every executor charges it alike [SPEC-09P.1 SIR-07];\n   - `lowering`: each executor, `cpu-sir-interp` and `cpu-c17`, and whether it runs the function;\n   - `sir`: the function's SIR text, byte for byte as the compiler wrote it [SPEC"
  },
  {
   "id": "spec-06p:cint-explain-p2",
   "edition": "SPEC-06P.1",
   "title": "9.9 `cint explain` (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-explain",
   "internal": 0,
   "content": "Example\n\n5. The section of one function, and the same in machine form:\n\n```console\n$ cint explain money.ci:tax\nmodule money.ci   revision 602173cd38defe996814e3298bd2a45c715a1cea53e3b5f8f84f6d073777ebde"
  },
  {
   "id": "spec-06p:cint-explain-p3",
   "edition": "SPEC-06P.1",
   "title": "9.9 `cint explain` (part 4)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-explain",
   "internal": 0,
   "content": "function tax   money.sites:16   pure\n  signature  (in subtotal: I64, in rate_bp: I64) -> I64\n  fault sites (3): 3 possible, 0 statically excluded\n    tax#6  money.ci:8:12  fuel.charge                      E_FUEL possible\n    tax#7  money.ci:9:31  mul.checked.i64                  E_OVERFLOW possible\n    tax#8  money.ci:9:12  div_round.checked.i64.half_even  E_OVERFLOW E_DIV_ZERO possible\n...\n    tax#6  fuel.charge 1   at the start of the body\n  lowering\n...\n  sir\nexport func @money.tax(%subtotal: I64, %rate_bp: I64) -> I64 {\n  fuel.charge 1                                  #6 @money.ci:8:12\n  %t0 = mul.checked.i64 %subtotal, %rate_bp      #7 @money.ci:9:31\n  %t1 = const I64 10000\n  %t2 = div_round.checked.i64.half_even %t0, %t1 #8 @money.ci:9:12\n  return %t2\n}\n$ cint explain --json money.ci:tax\n{\"functions\":[{\"effects\":\"pure\",\"fault_sites\":[{\"codes\":[\"E_FUEL\"],\"id\":\"tax#6\",\"operation\":\"fuel.charge\",\"position\":{\"column\":12,\"file\":\"money.ci\",\"line\":8},\"reason\":\"not analyzed\",\"status\":\"possible\"},{\"codes\":[\"E_OVERFLOW\"],\"id\":\"tax#7\",\"operation\":\"mul.checked.i64\",\"position\":{\"column\":31,\"file\":\"money.ci\",\"line\":9},\"reason\":\"not analyzed\",\"status\":\"possible\"},{\"codes\":[\"E_OVERFLOW\",\"E_DIV_ZERO\"],\"id\":\"tax#8\",\"operation\":\"div_round.checked.i64.half_even\",\"position\":{\"column\":12,\"file\":\"money.ci\",\"line\":9},\"reason\":\"not analyzed\",\"status\":\"possible\"}],\"fuel\":[{\"amount\":1,\"charge\":\"start\",\"id\":\"tax#6\"}],\"kind\":\"function\",\"lowering\":[{\"backend\":\"cpu-c17\",\"profile\":\"ref-c\",\"status\":\"supported\"},{\"backend\":\"cpu-sir-interp\",\"status\":\"supported\"}],\"name\":\"tax\",\"parameters\":[{\"direction\":\"in\",\"name\":\"subtotal\",\"type\":\"I64\"},{\"direction\":\"in\",\"name\":\"rate_bp\",\"type\":\"I64\"}],\"prints\":[],\"result\":\"I64\",\"sir\":\"export func @money.tax(%subtotal: I64, %rate_bp: I64) -> I64 {\\n  fuel.charge 1                                  #6 @money.ci:8:12\\n  %t0 = mul.checked.i64 %subtotal, %rate_bp    "
  },
  {
   "id": "spec-06p:cint-explain-p4",
   "edition": "SPEC-06P.1",
   "title": "9.9 `cint explain` (part 5)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-explain",
   "internal": 0,
   "content": "The lines left out of the text form are the reason no site is excluded, the heading of the fuel part and the two lines of the lowering part, which say that `cpu-sir-interp` runs this text and that `cpu-c17` compiles C from it. `money.ci` is listed in Annex A.1."
  },
  {
   "id": "spec-06p:debugging-with-cint-debug",
   "edition": "SPEC-06P.1",
   "title": "10 Debugging with `cint debug`",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#debugging-with-cint-debug",
   "internal": 0,
   "content": "## 10 Debugging with `cint debug`\n\n`cint debug` answers questions about a run after it happened. It works on a recording or a case (clause 11), never on the live program: it replays the run to show any boundary of it, compares two executors on it, and locates the boundary where it went wrong. Because replay supplies every input from the file, the answers are the same on every machine that has the file."
  },
  {
   "id": "spec-06p:command-line-3",
   "edition": "SPEC-06P.1",
   "title": "10.1 Command line",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#command-line-3",
   "internal": 0,
   "content": "### 10.1 Command line\n\n```text\ncint debug [--json] [--out DIR] [--echo] RECORDING | CASE\ncint debug replay [--json] RECORDING | CASE [--to N] [--receipt PATH] [--source-identity HEX]\ncint debug diff [--json] CASE [--ref EXECUTOR] [--cand EXECUTOR] [--receipt PATH] [--cint PATH] [--out DIR]\n                [--compiler-identity HEX] [--interpreter-identity HEX] [--workbench-identity HEX]\ncint debug locate [--json] PROGRAM.ci | RECORDING | CASE [--entry NAME [--args TYPED...]]\n                  [--depth N] [--fuel N] [--changed BINDING | --when PREDICATE] [--save-case PATH]\n                  [--receipt PATH] [--source-identity HEX] [--root DIR] [--cint PATH] [--out DIR | --sir DIR]\n```"
  },
  {
   "id": "spec-06p:command-line-3-p1",
   "edition": "SPEC-06P.1",
   "title": "10.1 Command line (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#command-line-3",
   "internal": 0,
   "content": "1. With a recording or a case and no other word, `cint debug` opens it in a read-only session (10.2). `replay` (10.3), `diff` (10.4) and `locate` (10.5) print their answer and end.\n2. Every form replays on `cpu-sir-interp`, and `diff` also runs the case on the executor named by `--ref`. Replay takes every input of an entry from the file, and it performs no print: what the run printed is compared with the recording, not written again.\n3. A command line that matches no form is a usage error, exit status 4. A file that cannot be read gives exit status 5, and a file that is not a complete recording or case gives exit status 3.\n4. Under `--json`, tool errors are `CINT-TOOL-1` objects (7.7). `replay` and `diff` then print their receipt (12.4, 12.5) on standard output in place of the text, and `locate` prints the target in place of its report: a fault as a `CINT-FAULT-1` object, an error result as a `CINT-ERROR-1` object, or the change that `--changed` found as a `CINT-CHANGE-1` object; with no target it writes its text (10.5, paragraph 7).\n5. `--source-identity HEX`, `--compiler-identity HEX`, `--interpreter-identity HEX` and `--workbench-identity HEX` give the source identities of the tools, 64 lowercase hexadecimal digits each, for a receipt to record. They change nothing else."
  },
  {
   "id": "spec-06p:opening-a-recording-or-a-case",
   "edition": "SPEC-06P.1",
   "title": "10.2 Opening a recording or a case",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#opening-a-recording-or-a-case",
   "internal": 0,
   "content": "### 10.2 Opening a recording or a case\n\n1. `cint debug FILE` starts a workbench session (clause 9) on the run that `FILE` holds and replays it to its end. It prints the banner with `debug FILE (read-only)` in place of `new session`, then `case:` or `recording:` with `entries N   boundaries B`, then `at the end of entry N, reached by replay`. The entries of the session are the recorded ones, numbered from 1, and the prompt shows the ordinal after the last.\n2. The session is read-only. The commands that look at the run work: `:inspect`, `:type`, `:goto`, `:trace`, `:fault`, `:log`, `:effects`, `:replay NAME`, where the name `start` stands for the recording's start, and `:save-case`, which writes a case of the run from its start. An entry typed at the prompt, and every command that would change the session (`:checkpoint`, `:restore`, `:undo`, `:branch`, `:branches`, `:diff`, `:history`, `:watch`, `:run`, `:load`, `:open`, `:save`, `:fuel`, `:depth`, `:explain`, and `:backend` with an executor other than `cpu-sir-interp`), is refused with one line that says so, and the session goes on.\n3. The session names each module variable with its module: a variable typed in a workbench session is `session.NAME`. An expression may use the plain name.\n4. `--out DIR` is the directory the session works in, by default `build/debug` beside `FILE`. `--echo` writes each entry after its prompt, as the workbench does (9.1).\n5. A fault report in a debug session has no source excerpt, and each of its `stack-source` lines ends with `(source not loaded)`, for a recording, which holds no source, and for a case alike.\n\nExamples\n\n6. The case `grow.cicase` that the workbench wrote in 9.5. It holds three entries: `rate = 2;` and two calls of `step()`:"
  },
  {
   "id": "spec-06p:opening-a-recording-or-a-case-p1",
   "edition": "SPEC-06P.1",
   "title": "10.2 Opening a recording or a case (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#opening-a-recording-or-a-case",
   "internal": 0,
   "content": "```console\n$ cint debug grow.cicase\ncint workbench   profile cint-core-1   backend cpu-sir-interp   debug grow.cicase (read-only)\ncase: entries 3   boundaries 3\nat the end of entry 3, reached by replay\nci[4]> :inspect level\nsession.level : I64\n  exact   695\nci[4]> :goto 2\nat the end of entry 2, reached by replay\nci[4]> :inspect level\nsession.level : I64\n  exact   351\nci[4]> :trace 3\nentry 3   session.ci: step()   evaluator cpu-sir-interp, by replay\n  ord  position           operation              operands                 value\n    0  session.ci:4:19    mul.checked.i64        351, 2                   702\n    1  session.ci:4:26    sub.checked.i64        702, 7                   695\nci[4]> :replay start\nreplaying 2 entries from the recording's start to the current state (entry 1 to entry 2), comparing prints and outcomes with the recording\nreplay matches the recording at 2 boundaries\nci[4]> :backend cpu-c17\n:backend cpu-c17 is not available in a debug session, which replays on cpu-sir-interp\nci[4]> :quit\n```\n\n7. The recording `partial.rec` of 8.3, which holds no source:"
  },
  {
   "id": "spec-06p:opening-a-recording-or-a-case-p2",
   "edition": "SPEC-06P.1",
   "title": "10.2 Opening a recording or a case (part 3)",
   "clauses": "IM-121",
   "url": "/specifications/spec-06p/1/#opening-a-recording-or-a-case",
   "internal": 0,
   "content": "```console\n$ cint debug partial.rec\ncint workbench   profile cint-core-1   backend cpu-sir-interp   debug partial.rec (read-only)\nrecording: entries 1   boundaries 1\nat the end of entry 1, reached by replay\nci[2]> :fault\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> partial.ci:3:13\n   = operation: add.checked.i64\n   = operand-count: 2\n   = operand: I64 9223372036854775807\n   = operand: I64 1\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n   = revision: 2a5d25c827694f7bef7e0477ec0d760c95a7be976beaf854285a43555aeedef8\n   = source-map: none\n   = address: none\n   = stack-depth: 0\n   = state: the state the fault left, reached by replay (SPEC-01 IM-121)\n   = noncanonical: not part of the fault record\n   = workbench-position: entry 1\n   = site: script#3\n   = backend: cpu-sir-interp\nci[2]> :effects\nnew context\nentry 1   the program entry\n  print \"partial: big=9223372036854775807\\n\"\n  fault E_OVERFLOW   fuel 1   state cff0bda8\nentries 1   prints 1   context resets 0   changes of revision set 0\nci[2]> :quit\n```"
  },
  {
   "id": "spec-06p:cint-debug-replay",
   "edition": "SPEC-06P.1",
   "title": "10.3 `cint debug replay`",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-debug-replay",
   "internal": 0,
   "content": "### 10.3 `cint debug replay`\n\n1. `cint debug replay FILE` replays a recording or a case on `cpu-sir-interp` from its initial state, compares the state at each boundary with the recording's digest chain (11.2), and lists the boundaries.\n2. It prints the file's header line (`case` or `recording`, the file, its boundaries and events, its mode and its density), the `revision` and `source-map` identities, then one line per boundary with its number, the index of its event, the entry, written as its function and arguments, the outcome and the fuel consumed. A statement typed in a workbench session is recorded as a call of a function `wb_entry`, and the program entry of a script or of `main` is shown as `the program entry`.\n3. When every boundary agrees, it prints `replay     ok, K of B boundaries compared with the recording`, then `chain`, the head of the digest chain up to the last boundary replayed, and `state`, the state hash there; the exit status is 0. When a boundary differs, replay stops there, prints the boundary and what differed, and the exit status is 3.\n4. `--to K` stops after boundary `K`, which shall be one of the file's boundaries; otherwise the exit status is 4. `--receipt PATH` writes a replay receipt (12.4).\n\nExample\n\n5. Replaying the case of 10.2 to its end and to its second boundary, and the recording of 8.3, whose one entry faulted:"
  },
  {
   "id": "spec-06p:cint-debug-replay-p1",
   "edition": "SPEC-06P.1",
   "title": "10.3 `cint debug replay` (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-debug-replay",
   "internal": 0,
   "content": "```console\n$ cint debug replay grow.cicase\ncase       grow.cicase   3 boundaries   9 events   mode full   density entry\nrevision   8d9f23f0901330065b452c169e537a3a180f567a17297b8616ca45a7f1e9f14e\nsource-map 8acd6e8377e85eac2e71a120316073bd03d172a3e8a022a2e89c1ce69cb1acd4\nboundary  event  entry                          outcome                  fuel\n       1      2  wb_entry()                     done                     1\n       2      5  step()                         done                     1\n       3      8  step()                         done                     1\nreplay     ok, 3 of 3 boundaries compared with the recording\nchain      f0b2f70fff960186500385ef87eed8d3906da27071125e5476abc25211915c29\nstate      42592ed8fb48eb6500af5d9e59e08e9f4b50685614b26db21f97eb00daa2e0e0\n$ cint debug replay grow.cicase --to 2\ncase       grow.cicase   3 boundaries   9 events   mode full   density entry\nrevision   8d9f23f0901330065b452c169e537a3a180f567a17297b8616ca45a7f1e9f14e\nsource-map 8acd6e8377e85eac2e71a120316073bd03d172a3e8a022a2e89c1ce69cb1acd4\nboundary  event  entry                          outcome                  fuel\n       1      2  wb_entry()                     done                     1\n       2      5  step()                         done                     1\nreplay     ok, 2 of 3 boundaries compared with the recording\nchain      9ff9df65ed047bbf27222afeff00b77b39cf0f927ffc98c22a9269595541a057\nstate      fe6985626d8d2e1fee13bb500442c2c9b97ecd0dfc9cdeecb1dd17536f6b0f7f\n$ cint debug replay partial.rec\nrecording  partial.rec   1 boundary   3 events   mode full   density entry\nrevision   2a5d25c827694f7bef7e0477ec0d760c95a7be976beaf854285a43555aeedef8\nsource-map be83426b1103002101ac0403acbc26b062cb5b2128a72bd55a423f9911c2a12b\nboundary  event  entry                          outcome                  fuel\n       1      2  the program entry              faulted E_OVERFLOW"
  },
  {
   "id": "spec-06p:cint-debug-diff",
   "edition": "SPEC-06P.1",
   "title": "10.4 `cint debug diff`",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-debug-diff",
   "internal": 0,
   "content": "### 10.4 `cint debug diff`\n\n`cint debug diff` shows whether two executors give a case the same meaning. It runs the case on a reference executor and on a candidate from the same initial state with the same inputs, and reports agreement or the first difference.\n\n1. `--ref` names the reference and `--cand` the candidate, each `cpu-c17` or `cpu-sir-interp`; the defaults are `cpu-c17` and `cpu-sir-interp`. Any other name is a usage error, exit status 4.\n2. On `cpu-c17`, the case's sources are built into a library with `cint build --lib` (5.5), in `--out DIR`, by default `build/debug` beside the case; `--cint PATH` names the `cint` to use, by default the one in the directory that holds the `cint-debug` executable. A library has no program entry, so a case whose entries call the program entry of a script or of `main` cannot run on `cpu-c17`: the exit status is 5, and the message names `--ref cpu-sir-interp`. A case that the workbench wrote calls exported functions and runs on both.\n3. The procedure:\n   - The case is checked first: its digests, the order and the count of its events. A case that fails is the outcome `invalid-case`.\n   - Both executors run each entry from the case's initial state with the case's inputs, and the digest of the state at each boundary is compared.\n   - At the first boundary whose digests differ, or at which one run faulted and the other did not, or both faulted with different fault records, the state is compared binding by binding in declaration order, and within an array element by element, and the first difference is reported with both values exactly.\n   - The candidate runs that boundary once more. A difference that does not happen again is reported as `unreproduced`, never as a difference.\n4. The outcome is the first of these that applies:"
  },
  {
   "id": "spec-06p:cint-debug-diff-p1",
   "edition": "SPEC-06P.1",
   "title": "10.4 `cint debug diff` (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-debug-diff",
   "internal": 0,
   "content": "| Outcome | Meaning |\n| --- | --- |\n| `invalid-case` | The case failed the check of paragraph 3. |\n| `refused` | The candidate refused the case with `E_UNSUPPORTED`. |\n| `unreproduced` | The candidate's difference did not happen again when it ran the boundary once more. |\n| `fault-difference` | One run faulted and the other did not, or the two fault records differ. |\n| `value-difference` | The state differs: the boundary, the binding, the element and both values. |\n| `agree` | Every boundary's state is equal, and so are the results and the fault records. |\n\n5. The text form gives the case, its boundaries and density, the `reference` and the `candidate`, the boundaries compared and the `outcome`, followed by the details of a difference. The exit status is 0 for `agree` and 3 for every other outcome. `--receipt PATH` writes a diff receipt (12.5).\n6. Agreement is checked at boundaries only. Two runs that differ inside an entry and agree again at its end are not told apart.\n\nExample\n\n7. The workbench's case compared on the two executors, and the case that the interpreter wrote in 8.3, which calls the program entry:\n\n```console\n$ cint debug diff grow.cicase\ncase       grow.cicase   3 boundaries   density entry\nreference  cpu-c17\ncandidate  cpu-sir-interp\nboundaries 3 of 3 compared\noutcome    agree\n$ echo $?\n0\n$ cint debug diff partial.cicase\ncint debug: error: the case calls the program entry, which a cpu-c17 library does not have; compare it with --ref cpu-sir-interp\n$ echo $?\n5\n$ cint debug diff --ref cpu-sir-interp partial.cicase\ncase       partial.cicase   1 boundary   density entry\nreference  cpu-sir-interp\ncandidate  cpu-sir-interp\nboundaries 1 of 1 compared\noutcome    agree\n```"
  },
  {
   "id": "spec-06p:cint-debug-locate",
   "edition": "SPEC-06P.1",
   "title": "10.5 `cint debug locate`",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-debug-locate",
   "internal": 0,
   "content": "### 10.5 `cint debug locate`\n\n`cint debug locate` finds the boundary where a run went wrong and shows how the run got there: the fault report, the boundary before it and the last operations counted before the fault."
  },
  {
   "id": "spec-06p:cint-debug-locate-p1",
   "edition": "SPEC-06P.1",
   "title": "10.5 `cint debug locate` (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-debug-locate",
   "internal": 0,
   "content": "1. Given a program, `locate` translates it with `cint emit-c` into `--out DIR`, by default `build/debug` under the root, or reads an output set already written from `--sir DIR`, and runs it on `cpu-sir-interp` under a recording. It runs the program entry, or, with `--entry NAME`, the exported function `NAME` of the root module, a usage error when the module exports none, called with the typed values of `--args`, written `I64 9` or `Bool true`. The entry runs with no fuel allowance and a call-depth limit of 256, as the workbench's entries do; `--fuel N` and `--depth N` set them. `--cint PATH` names the `cint` to translate with, by default the one in the directory that holds the `cint-debug` executable.\n2. Given a recording or a case, `locate` replays it.\n3. The target is the first boundary that ends in a fault or with an error result. `locate` prints `program`, `recording` or `case` with what it ran, `target` with the boundary and how it was found, and `bracket`, the boundary before the target and the target. For a fault, the fault report of 7.3 follows, with the lines of 7.3, paragraph 5, and then the last 20 counted operations of the entry, with each one's position, operation, operands and value. For an error result, the error line of 7.5 follows, with the path the error took: where it was returned and each call that passed it on with `try`, innermost first.\n4. `--changed BINDING` makes the target the last boundary at which the module variable `BINDING` changed, found by replaying backward from the end. `target` then gives the binding's value before and after. Under `--json` the answer is one `CINT-CHANGE-1` object with the keys `schema`, `binding` (qualified by its module), `boundary` (a decimal string) and `from` and `to` (typed values, as in `CINT-FAULT-1`). A `BINDING` that the recording's state does not have is a usage error, exit status 4.\n5. `cint debug locate"
  },
  {
   "id": "spec-06p:cint-debug-locate-p2",
   "edition": "SPEC-06P.1",
   "title": "10.5 `cint debug locate` (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-debug-locate",
   "internal": 0,
   "content": "Examples\n\n8. A fault inside a call, an error result and a run with no target, in the modules `money.ci` (Annex A.1) and `ledger.ci` (5.4):"
  },
  {
   "id": "spec-06p:cint-debug-locate-p3",
   "edition": "SPEC-06P.1",
   "title": "10.5 `cint debug locate` (part 4)",
   "clauses": "IM-121",
   "url": "/specifications/spec-06p/1/#cint-debug-locate",
   "internal": 0,
   "content": "```console\n$ cint debug locate money.ci --entry overflow\nprogram    money.ci   evaluator cpu-sir-interp, under a recording\ntarget     boundary 1 of 1, overflow(): the first fault, reproduced by replay\nbracket    the initial state; then boundary 1\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> money.ci:13:14\n   |\n13 |     return a + b;\n   |              ^ add.checked.i64\n   |\n   = operation: add.checked.i64\n   = operand-count: 2\n   = operand: I64 9223372036854775800\n   = operand: I64 12\n   = exact:   9223372036854775812\n   = limit:   I64 9223372036854775807\n   = revision: 602173cd38defe996814e3298bd2a45c715a1cea53e3b5f8f84f6d073777ebde\n   = source-map: none\n   = address: none\n   = stack-depth: 1\n   = called from: money.ci:23:12\n   = fuel-consumed: 2 (not part of the fault record)\n   = state: the post-fault state of SPEC-01 IM-121, reached by replay\n   = noncanonical: not part of the fault record\n   = stack-source: money.ci:23:12\n   |\n23 |     return add_cents(big, 12);\n   |            ^\n   |\n   = workbench-position: boundary 1\n   = site: add_cents#10\n   = backend: cpu-sir-interp, by replay\nthe last 2 counted operations of boundary 1, of 2 trace events (:trace shows them all)\n  ord  position           operation              operands                 value\n    0  money.ci:23:12     call                   9223372036854775800, 12\n    1  money.ci:13:14     add.checked.i64        9223372036854775800, 12  E_OVERFLOW\n$ cint debug locate ledger.ci\nprogram    ledger.ci   evaluator cpu-sir-interp, under a recording\ntarget     boundary 1 of 1, the program entry: the first error result, reproduced by replay\nbracket    the initial state; then boundary 1\nerror: ledger.LedgerError.overdrawn (tag 1)\nthe path, innermost first, from the calls and returns of the replay:\n  withdraw returned the error (tag 1)\n  main passed it on with try (tag 1), from its call of withd"
  },
  {
   "id": "spec-06p:cint-debug-locate-p4",
   "edition": "SPEC-06P.1",
   "title": "10.5 `cint debug locate` (part 5)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-debug-locate",
   "internal": 0,
   "content": "9. A call-depth fault, located with arguments and a depth limit, and saved as a case with a receipt:\n\n```console\n$ cint debug locate deep.ci --entry down --args 'I64 10' --depth 4 --save-case down.cicase --receipt down.json\nprogram    deep.ci   evaluator cpu-sir-interp, recorded as the case down.cicase\ntarget     boundary 1 of 1, down(I64 10): the first fault, reproduced by replay\nbracket    the initial state; then boundary 1\nfault[E_DEPTH]: call depth limit exceeded\n  --> deep.ci:5:16\n   |\n 5 |     return 1 + down(n - 1);\n   |                ^ call.enter\n   |\n   = operation: call.enter\n   = operand-count: 0\n   = exact:   none\n   = limit:   I64 4\n...\nthe last 8 counted operations of boundary 1, of 8 trace events (:trace shows them all)\n  ord  position           operation              operands                 value\n    0  deep.ci:5:23       sub.checked.i64        10, 1                    9\n    1  deep.ci:5:16       call                   9\n    2  deep.ci:5:23       sub.checked.i64        9, 1                     8\n    3  deep.ci:5:16       call                   8\n    4  deep.ci:5:23       sub.checked.i64        8, 1                     7\n    5  deep.ci:5:16       call                   7\n    6  deep.ci:5:23       sub.checked.i64        7, 1                     6\n    7  deep.ci:5:16       call                   6                        E_DEPTH\n```\n\nThe lines left out are the rest of the fault report: its three `called from` lines, each with its `stack-source` excerpt.\n\n10. The last change of a module variable in the case of 10.2, in both forms:"
  },
  {
   "id": "spec-06p:cint-debug-locate-p5",
   "edition": "SPEC-06P.1",
   "title": "10.5 `cint debug locate` (part 6)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#cint-debug-locate",
   "internal": 0,
   "content": "```console\n$ cint debug locate grow.cicase --changed level\ncase       grow.cicase   3 boundaries\ntarget     boundary 3 of 3, step(): the last change of session.level, from 351 to 695\nbracket    boundary 2, step(): done; then boundary 3\nthe last 2 counted operations of boundary 3, of 2 trace events (:trace shows them all)\n  ord  position           operation              operands                 value\n    0  session.ci:4:19    mul.checked.i64        351, 2                   702\n    1  session.ci:4:26    sub.checked.i64        702, 7                   695\n$ cint debug locate --json grow.cicase --changed rate\n{\"binding\":\"session.rate\",\"boundary\":\"1\",\"from\":{\"t\":\"I64\",\"v\":\"3\"},\"schema\":\"CINT-CHANGE-1\",\"to\":{\"t\":\"I64\",\"v\":\"2\"}}\n$ cint debug locate grow.cicase --changed nosuch\ncint debug: error: no global nosuch in the recording's state\n$ echo $?\n4\n```"
  },
  {
   "id": "spec-06p:checkpoints-recordings-and-cases",
   "edition": "SPEC-06P.1",
   "title": "11 Checkpoints, recordings and cases",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#checkpoints-recordings-and-cases",
   "internal": 0,
   "content": "## 11 Checkpoints, recordings and cases\n\nThe tools keep runs in three kinds of file. A *checkpoint* holds one state. A *recording* holds a whole run: the code, the state it started from and every entry with its inputs, its effects and its outcome, so that the run can be replayed. A *case* is a recording that also holds the source, so that it can be compared and shown on another machine. SPEC-01P.2 specifies the bytes of each; this clause says what they hold and how the tools use them."
  },
  {
   "id": "spec-06p:checkpoints",
   "edition": "SPEC-06P.1",
   "title": "11.1 Checkpoints",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#checkpoints",
   "internal": 0,
   "content": "### 11.1 Checkpoints\n\n1. A checkpoint holds the canonical state of a context at one boundary: its module variables, its buffers and arenas and the fault record when the context faulted. It names the revision identity of the program whose state it is, and it can be restored only into a program with that revision identity. The locals of a running function are not canonical state, so a checkpoint is taken only at a boundary, never inside an entry.\n2. `cint interp replay --checkpoint PATH` writes the state where the replay stopped as a checkpoint file. A workbench checkpoint (9.5) is kept in the session; it also holds the code of the session's revisions and the per-entry settings.\n3. A checkpoint file begins with its format, `cint-core-1/checkpoint/v1`. `cint interp show` prints it as text: the format, the runtime contract, the canonical state with its revision, profile and fuel model, the identifier counters, the fault record when there is one, the count of effects and `state-hash`, the state hash of clause 6."
  },
  {
   "id": "spec-06p:recordings-and-cases",
   "edition": "SPEC-06P.1",
   "title": "11.2 Recordings and cases",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#recordings-and-cases",
   "internal": 0,
   "content": "### 11.2 Recordings and cases"
  },
  {
   "id": "spec-06p:recordings-and-cases-p1",
   "edition": "SPEC-06P.1",
   "title": "11.2 Recordings and cases (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#recordings-and-cases",
   "internal": 0,
   "content": "1. A recording holds:\n   - a header: its format, `cint-core-1/recording/v1`, the runtime contract, the revision identity and the source-map identity of the code, the mode (`full`), how often the state is hashed (`every entry`) and the density (11.3);\n   - the code: for each module, its path, its SIR text with its table of sites, and, in a case, its source;\n   - the state the run began from, as a checkpoint, with its state hash as `initial-state`;\n   - the events of the run, in order: for each entry an `entry` event, with the function or the program entry, its arguments, its fuel allowance, its call-depth limit and its frame-arena capacity; an `effect` event for each print, with its site and its bytes; and an `outcome` event, with the outcome, the fault record when the entry faulted, the fuel consumed and the state hash at the boundary;\n   - last, an `end` event with the head of the digest chain and the count of events.\n2. The *digest chain* links the boundaries. Its first digest covers the initial state, and each boundary's digest covers the digest before it, the boundary's event, the state hash there and the fault record when the entry faulted. The head of the chain thus depends on every boundary of the run, and replay recomputes the chain as it goes and stops at the first boundary whose digest differs.\n3. A case is a recording in the format `cint-core-1/case/v1` that holds the source of every module. Its source is used for displays and for building it on `cpu-c17`; what replay runs is its SIR text, whose revision identity is checked first.\n4. The interpreter writes a recording with `cint interp run --record` and a case with `cint interp run --case` (8.2). The workbench records every entry of a session and writes a case with `:save-case` (9.6), and `cint debug locate --save-case` writes the run it located (10.5).\n5. A recording is written in order, and its `end` even"
  },
  {
   "id": "spec-06p:recordings-and-cases-p2",
   "edition": "SPEC-06P.1",
   "title": "11.2 Recordings and cases (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#recordings-and-cases",
   "internal": 0,
   "content": "Example\n\n7. The recording, the checkpoint and the case that 8.3 wrote, shown as text:"
  },
  {
   "id": "spec-06p:recordings-and-cases-p3",
   "edition": "SPEC-06P.1",
   "title": "11.2 Recordings and cases (part 4)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#recordings-and-cases",
   "internal": 0,
   "content": "```console\n$ cint interp show partial.rec\nrecording cint-core-1/recording/v1\ncontract cint-rt-3\nrevision 2a5d25c827694f7bef7e0477ec0d760c95a7be976beaf854285a43555aeedef8\nsource-map be83426b1103002101ac0403acbc26b062cb5b2128a72bd55a423f9911c2a12b\nmode full\nstate-hash every entry\ndensity entry\nmodule partial.ci sir 748 sha256 b6dd6dc4d37dd2d3ac5af2d065a795cab0db8d03b749c7cd949a1eed8af6e81a source absent\ninitial-state 55c236bfbae5a4346437db7a1c7cb6095cb0ab7d3ee2b480924b9ceb500f48df\nevent 0 entry 1 program fuel -1 depth 256 frame-arena 16777216\nevent 1 effect 0 site 0.2 print status 0 \"partial: big=9223372036854775807\\x0a\"\nevent 2 outcome fault fuel 1 allowance -1 state cff0bda8706611d5a578aadb44ae46f13e6047e63020326774cb32e69f8b1dfa\nfault E_OVERFLOW add.checked.i64\nfault-operand I64 9223372036854775807\nfault-operand I64 1\nfault-exact Z 9223372036854775808\nfault-limit I64 9223372036854775807\nfault-position partial.ci:3:13\nfault-revision 2a5d25c827694f7bef7e0477ec0d760c95a7be976beaf854285a43555aeedef8\nfault-source-map absent\nevent 3 end host chain 49942e33499538df87f7e49b392c1c5aad6c557471959c567107f56b46ac400a events 3\n$ cint interp show partial.ckpt\ncheckpoint cint-core-1/checkpoint/v1\ncontract cint-rt-3\npayload-digest absent\nbuild-record-digest absent\nbuild-identity absent\nstate cint-core-1/state/v1\nrevision 2a5d25c827694f7bef7e0477ec0d760c95a7be976beaf854285a43555aeedef8\nprofile cint-core-1\nfuel-model fuel-v1\narena-block 0\npool-block 0\ncounters next-buffer 1 next-arena 1 next-pool 1 entries 1\nfault E_OVERFLOW add.checked.i64\nfault-operand I64 9223372036854775807\nfault-operand I64 1\nfault-exact Z 9223372036854775808\nfault-limit I64 9223372036854775807\nfault-position partial.ci:3:13\nfault-revision 2a5d25c827694f7bef7e0477ec0d760c95a7be976beaf854285a43555aeedef8\nfault-source-map absent\neffects 1\nstate-hash cff0bda8706611d5a578aadb44ae46f13e6047e63020326774cb32e69f8b1dfa\n$"
  },
  {
   "id": "spec-06p:recordings-and-cases-p4",
   "edition": "SPEC-06P.1",
   "title": "11.2 Recordings and cases (part 5)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#recordings-and-cases",
   "internal": 0,
   "content": "The `fuel -1` and `allowance -1` of the recording stand for no fuel allowance, and `frame-arena 16777216` is the frame arena of 2,097,152 elements, in bytes. The state hash of the `outcome` event equals the checkpoint's `state-hash`, since the replay that wrote the checkpoint stopped at that boundary, and the case differs from the recording only in its format and in holding the 69 bytes of `partial.ci`."
  },
  {
   "id": "spec-06p:boundaries-and-density",
   "edition": "SPEC-06P.1",
   "title": "11.3 Boundaries and density",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#boundaries-and-density",
   "internal": 0,
   "content": "### 11.3 Boundaries and density\n\n1. A boundary is where a recording digests the state. At the density `entry`, the default, there is one boundary at the end of each entry, including an entry that faulted, whose boundary holds the state the fault left and the fault record.\n2. At the density `dispatch`, chosen with `cint interp run --boundary dispatch`, each kernel dispatch inside an entry also has a boundary after it publishes its outputs. The end of an entry whose last action is such a publication is one boundary, not two.\n3. Replay can reach every boundary, and the interpreter can trace every counted operation of an entry by replaying it. A point inside an entry is reached by replaying that entry, never by restoring a checkpoint taken there. A program that runs all its work in one entry, such as one `main`, has one boundary; a program meant to be inspected step by step runs one entry per step, as the workbench's `:run step() N` does."
  },
  {
   "id": "spec-06p:what-replay-does-not-do",
   "edition": "SPEC-06P.1",
   "title": "11.4 What replay does not do",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#what-replay-does-not-do",
   "internal": 0,
   "content": "### 11.4 What replay does not do\n\n1. Replay reaches only what was recorded. `cint run` makes no recording, and a run under it cannot be replayed; `cint interp run --record` and the workbench make recordings.\n2. Replay does not rewind the outside world. A restore or a replay does not take back what the run printed or wrote.\n3. Replay runs the recorded code. A recording replays under the revisions it holds, never under code edited since.\n4. Reaching a boundary costs the replay of every entry before it, from the start of the recording or from the checkpoint the replay starts at."
  },
  {
   "id": "spec-06p:receipts",
   "edition": "SPEC-06P.1",
   "title": "12 Receipts",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#receipts",
   "internal": 0,
   "content": "## 12 Receipts\n\nA receipt is a canonical JSON file that records a run of a tool: what went in, what came out, and what the machine was. Two receipts that agree on the first two parts show the same result on different machines, whatever the machines were. SPEC-09P.1 11.2 specifies the format and the receipt identity that every receipt shares; this clause specifies the receipts that the tools of this document write."
  },
  {
   "id": "spec-06p:format",
   "edition": "SPEC-06P.1",
   "title": "12.1 Format",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#format",
   "internal": 0,
   "content": "### 12.1 Format\n\n1. A receipt is one JSON object written as the bytes of the JSON Canonicalization Scheme (RFC 8785) with one exception, followed by one LF: keys sorted, no space outside strings and integers only, with a value outside plus or minus 2^53 - 1 written as a decimal string. It has three parts. `identity` records the inputs, `outcome` the result and `observations` the machine, the timings and the paths, which can differ between two runs with the same result. `observations.receipt_identity_sha256` is the receipt identity, the SHA-256 digest of the canonical bytes of the object `{\"identity\": ..., \"outcome\": ...}`.\n2. The exception is the escaping of strings. A receipt holds only ASCII characters: every character outside ASCII is written `\\u` with four lowercase hexadecimal digits, a character above U+FFFF as its UTF-16 surrogate pair, where RFC 8785 writes the character itself. The other escapes are those of RFC 8785: `\\\"`, `\\\\`, `\\b`, `\\t`, `\\n`, `\\f` and `\\r` and `\\u00XX`, in lowercase, for the other control characters; `/` and U+007F are written as themselves. The receipts of SPEC-09P.1 11.2, which the Python tools of the source tree write, differ in one more character: they write U+007F as `\\u007f`.\n3. A receipt written this way is not the output of RFC 8785 when a string holds a character outside ASCII. When no string holds U+007F, the bytes are those that Python's `json.dumps(receipt, sort_keys=True, separators=(\",\", \":\"))` writes, which escapes the other characters the same way; `json.dumps` writes U+007F as `\\u007f`.\n4. Some integers of a receipt are JSON numbers, such as an exit status, a line, a call-depth limit and the size of standard output. Others are decimal strings, such as fuel, boundary numbers, timings and the size of a recording or a case. The form of each key is fixed and does not depend on its value."
  },
  {
   "id": "spec-06p:what-every-receipt-records",
   "edition": "SPEC-06P.1",
   "title": "12.2 What every receipt records",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#what-every-receipt-records",
   "internal": 0,
   "content": "### 12.2 What every receipt records\n\n1. `identity.schema` is `cint-receipt-1/KIND`, and `identity.kind` is `KIND`: `run`, `build` and `test` (12.3) for the `cint` command, `replay` (12.4) and `diff` (12.5) for the interpreter and `cint debug`.\n2. `identity.profile` is `cint-core-1`. `observations.machine` or `observations.host` names the operating system, and `observations.timings` holds durations in nanoseconds, under keys that end in `_ns`.\n3. `observations.limits` is a sentence that says what the receipt does not show."
  },
  {
   "id": "spec-06p:run-build-and-test-receipts",
   "edition": "SPEC-06P.1",
   "title": "12.3 Run, build and test receipts",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#run-build-and-test-receipts",
   "internal": 0,
   "content": "### 12.3 Run, build and test receipts\n\n1. `cint run`, `cint build` and `cint test` write these keys:"
  },
  {
   "id": "spec-06p:run-build-and-test-receipts-p1",
   "edition": "SPEC-06P.1",
   "title": "12.3 Run, build and test receipts (part 2)",
   "clauses": "RCPT-07",
   "url": "/specifications/spec-06p/1/#run-build-and-test-receipts",
   "internal": 0,
   "content": "| Key | Content |\n| --- | --- |\n| `identity.tool` | `name` (`cint`), `version`, and `compiler_source_identity`, the digest of the source manifest of the compiler (SPEC-09P.1 11.2). |\n| `identity.source` | `root_module`; `files`, the SHA-256 of each module read, by module path; `revision` and `dirty`, the version-control revision of the source and whether it had changes, or `null` when there is no repository. |\n| `identity.generated` | `files`, the SHA-256 of each file of the output set, and `manifest`, the digest of its `MANIFEST` (5.7). |\n| `identity.runtime` | `contract` (`cint-rt-3`) and `files`, the SHA-256 of each runtime source compiled with the program. |\n| `identity.backend` | `id`: `cpu-c17`. |\n| `identity.encodings` | `fault`: the version of the fault record, `cint-core-1/fault/v2`. |\n| `identity.method` | The semantic inputs of 5.3: `fuel_model` (`fuel-v1`), `fuel_budget` (`none`, or the allowance as a decimal string), `depth_limit`, `frame_arena_bytes` (the frame arena in bytes, eight per element) and `stdin` (`\"null\"`, the null device). `null` in a build receipt. |\n| `identity.identities` | `build`, `execution`, `meaning`, `revision` and `source_map`, each `null` in cint 0.2.0. |\n| `identity.lookups` | In build and test receipts: each module path that an import looked up under the root, with `true` when the file was there [RCPT-07]. |\n| `outcome.kind` | `run`: `value` (the program ended normally), `fault`, `error` or `compile-error`. `build`: `built`. `test`: `pass` or `fail`. |\n| `outcome.exit_status` | The exit status of 5.2. |\n| `outcome.diagnostics` | The diagnostics, each with `code`, `file`, `line` and `column`; `diagnostics_not_retained` counts those left out. |\n| `outcome.fault`, `outcome.error` | `run`: the `CINT-FAULT-1` object without `noncanonical`, or `null`; the `CINT-ERROR-1` object when `main` returned an error. |\n| `outcome.fuel_consumed`"
  },
  {
   "id": "spec-06p:run-build-and-test-receipts-p2",
   "edition": "SPEC-06P.1",
   "title": "12.3 Run, build and test receipts (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#run-build-and-test-receipts",
   "internal": 0,
   "content": "2. Nothing that depends on the machine, the C compiler or the path of the cache is in `identity` or `outcome`, so one program run with the same inputs on two machines gives one receipt identity.\n3. `observations.cache` records the cache directory as it was given, by `--cache` or by the toolchain file, so it can hold a path of the machine, such as one under a home directory.\n\nNote\n\n4. A receipt of a run with a relative `--cache` path holds no path of the machine there, and can be shared as it is."
  },
  {
   "id": "spec-06p:replay-receipts",
   "edition": "SPEC-06P.1",
   "title": "12.4 Replay receipts",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#replay-receipts",
   "internal": 0,
   "content": "### 12.4 Replay receipts\n\n1. `cint interp replay --receipt`, `cint debug replay --receipt` and `cint debug locate --receipt` write a replay receipt:\n\n| Key | Content |\n| --- | --- |\n| `identity.backend` | `id`: `cpu-sir-interp`. |\n| `identity.recording`, `identity.case` | For a recording or a case, its size in bytes and its SHA-256. |\n| `identity.identities` | `revision` and `source_map`, the identities of the code replayed. |\n| `identity.method` | `density`, `fuel_model`, `mode`, `state_hash_interval` and `stop`, the boundary replay stopped after or `0` for the end. |\n| `identity.runtime_contract` | `cint-rt-3`. |\n| `identity.tool` | `interpreter_source_identity`, from `--source-identity`, or `null`. |\n| `outcome.status`, `outcome.event`, `outcome.what` | `ok` when replay agreed with the recording to its end, or the status that stopped it; the index of the event at which replay ended; and what differed, or `null`. |\n| `outcome.boundaries`, `outcome.chain_head`, `outcome.state_sha256` | The boundaries replayed, the head of the digest chain and the state hash at the last of them. |\n| `outcome.fault_sha256` | The SHA-256 of the last fault record, or `null`. |\n| `outcome.fuel_consumed` | The fuel consumed at each boundary. |\n| `observations.checkpoints` | `cint debug` only: for each boundary, the elements a checkpoint of the state there holds (a variable counts one, an array its elements) and the time replay took to reach it. |\n\n2. A file replayed on two machines gives one receipt identity."
  },
  {
   "id": "spec-06p:diff-receipts",
   "edition": "SPEC-06P.1",
   "title": "12.5 Diff receipts",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#diff-receipts",
   "internal": 0,
   "content": "### 12.5 Diff receipts\n\n1. `cint debug diff --receipt` writes a diff receipt:\n\n| Key | Content |\n| --- | --- |\n| `identity.backend` | `reference` and `candidate`, each with its `id`. |\n| `identity.case`, `identity.identities`, `identity.runtime_contract` | As in a replay receipt. |\n| `identity.method` | `density` and `fuel_model`. |\n| `identity.tool` | `compiler_source_identity`, `interpreter_source_identity` and `workbench_source_identity`, from the options of 10.1, paragraph 5, or `null`. |\n| `outcome.outcome` | The outcome of 10.4. |\n| `outcome.boundaries`, `outcome.compared` | The case's boundaries and those compared. |\n| `outcome.boundary`, `binding`, `element`, `reference`, `candidate`, `differs`, `rerun`, `why` | The details of a difference, `null` or empty for `agree`. |\n| `observations.backend` | The build configuration of each executor: for `cpu-c17`, the C compiler, its version and its flags. |\n\n2. The configuration of the C compiler is an observation, so one comparison has one receipt identity with every toolchain."
  },
  {
   "id": "spec-06p:reading-a-receipt",
   "edition": "SPEC-06P.1",
   "title": "12.6 Reading a receipt",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#reading-a-receipt",
   "internal": 0,
   "content": "### 12.6 Reading a receipt\n\nExample\n\n1. The parts of the receipt of 5.3, its method and outcome, its identity computed again from its bytes, and a cache path outside ASCII as a receipt writes it:"
  },
  {
   "id": "spec-06p:reading-a-receipt-p1",
   "edition": "SPEC-06P.1",
   "title": "12.6 Reading a receipt (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#reading-a-receipt",
   "internal": 0,
   "content": "```console\n$ python3 -c 'import json; r = json.load(open(\"hello.json\")); [print(p + \":\", \" \".join(sorted(r[p]))) for p in (\"identity\", \"outcome\", \"observations\")]'\nidentity: backend encodings generated identities kind method profile runtime schema source tool\noutcome: diagnostics diagnostics_not_retained exit_status fault fuel_consumed kind stdout\nobservations: cache cc executables finished_utc host limits receipt_identity_sha256 started_utc timings\n$ python3 -c 'import json; r = json.load(open(\"hello.json\")); print(json.dumps(r[\"identity\"][\"method\"])); print(json.dumps(r[\"outcome\"]))'\n{\"depth_limit\": 256, \"frame_arena_bytes\": 16777216, \"fuel_budget\": \"none\", \"fuel_model\": \"fuel-v1\", \"stdin\": \"null\"}\n{\"diagnostics\": [], \"diagnostics_not_retained\": 0, \"exit_status\": 0, \"fault\": null, \"fuel_consumed\": \"1\", \"kind\": \"value\", \"stdout\": {\"bytes\": 23, \"sha256\": \"0d3f756a0f6c68f4cee819726e6ddf3f969bb5b63c827eb66a1166eba9104b57\"}}\n$ python3 -c 'import hashlib, json; r = json.load(open(\"hello.json\")); b = json.dumps({\"identity\": r[\"identity\"], \"outcome\": r[\"outcome\"]}, sort_keys=True, separators=(\",\", \":\")).encode(); print(hashlib.sha256(b).hexdigest()); print(r[\"observations\"][\"receipt_identity_sha256\"])'\nbfba045301d788cc9bd64ff0055520ce74fe031bcb5c93a07b02f109ae7eb275\nbfba045301d788cc9bd64ff0055520ce74fe031bcb5c93a07b02f109ae7eb275\n$ python3 -c 'import json; r = json.load(open(\"hello.json\")); print(json.dumps(r, sort_keys=True, separators=(\",\", \":\")) + \"\\n\" == open(\"hello.json\").read())'\nTrue\n$ cint run --cache cach\u00e9e --receipt r2.json hello.ci\nhello, world\nanswer=42\nreceipt: r2.json\n$ grep -o '\"cache\":\"[^\"]*\"' r2.json\n\"cache\":\"cach\\u00e9e/6d8cb55c098d7a0d2ef3dc1a852e416b04a06fc851142c6a608cbbf1f50b9806/run-0\"\n```"
  },
  {
   "id": "spec-06p:reading-a-receipt-p2",
   "edition": "SPEC-06P.1",
   "title": "12.6 Reading a receipt (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#reading-a-receipt",
   "internal": 0,
   "content": "The two digests are equal: the receipt identity is the digest of the canonical bytes of `identity` and `outcome`. `stdin` is the string `\"null\"`, which names the null device of 5.3."
  },
  {
   "id": "spec-06p:future-directions",
   "edition": "SPEC-06P.1",
   "title": "13 Future directions",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#future-directions",
   "internal": 0,
   "content": "## 13 Future directions\n\nThis clause is informative. It names tools and features that cint 0.2.0 does not include.\n\n1. *A project manifest.* A declarative file, with no conditionals or loops, that gives a project its name, version, targets, embedded data and foreign libraries, each value an input of the build.\n2. *`cint fmt`.* A formatter with one style and no options that rewrites source without changing its revision identity, so that checkpoints still restore after formatting, and refuses to write a file whose meaning changes.\n3. *`cint doc`.* A documentation generator that describes every export with its signature and the faults it can raise, from what `cint explain` knows, and runs the examples in its comments as tests.\n4. *A build cache.* A cache that keys each build action by the digests of its inputs, so that an unchanged module is not translated again. A file taken from the cache is byte-identical to a fresh one.\n5. *`cint bench`.* A benchmark runner that times blocks of code by a declared method, with warm-up runs, samples and nearest-rank percentiles in integer nanoseconds, and rejects a run whose samples do not end in the same state.\n6. *A language server.* A server for the Language Server Protocol that gives an editor the compiler's diagnostics, the exact value of a constant and the operation, rounding and faults of each operator.\n7. *Device steps in the workbench.* Workbench commands that run kernels on a `gpu-cuda` library, place a module's buffers on a device and back with an explicit command, and compare such a run with `cpu-c17` in `cint debug diff`."
  },
  {
   "id": "spec-06p:transcripts",
   "edition": "SPEC-06P.1",
   "title": "Annex A (informative) Transcripts",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#transcripts",
   "internal": 0,
   "content": "## Annex A (informative) Transcripts\n\nThe transcripts of this annex were produced by the tools of cint 0.2.0, as the others in this document were. They continue the transcripts before them in the same directory."
  },
  {
   "id": "spec-06p:exact-money-in-the-workbench",
   "edition": "SPEC-06P.1",
   "title": "A.1 Exact money in the workbench",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#exact-money-in-the-workbench",
   "internal": 0,
   "content": "### A.1 Exact money in the workbench\n\nA session that prints, sums prices held in whole cents, shows a sum as dollars, compares two rounding modes on a tie, replaces a function and goes back to the earlier revision:"
  },
  {
   "id": "spec-06p:exact-money-in-the-workbench-p1",
   "edition": "SPEC-06P.1",
   "title": "A.1 Exact money in the workbench (part 2)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#exact-money-in-the-workbench",
   "internal": 0,
   "content": "```console\n$ cint workbench\ncint workbench   profile cint-core-1   backend cpu-sir-interp   new session\nci[1]> \"hello, world\\n\";\nhello, world\nci[2]> I64[3] cents = [1999, 425, 10];\ncents : I64[3]   3 elements   host\n  [0] = 1999\n  [1] = 425\n  [2] = 10\nci[3]> I64 subtotal = sum(cents);\nsubtotal = 2434 : I64\nci[4]> :inspect subtotal /scale 100\nsubtotal : I64   shown with scale 100\n  exact   24.34\n  raw     2434\nci[4]> div_round(200 * 825, 10000, half_even)\n= 16 : I64   inexact: div_round half_even (exact quotient 16.5)\nci[5]> div_round(200 * 825, 10000, half_up)\n= 17 : I64   inexact: div_round half_up (exact quotient 16.5)\nci[6]> I64 total_with_tax[n](in I64[n] c, I64 rate_bp) {\n..>     I64 s = sum(c);\n..>     return s + div_round(s * rate_bp, 10000, half_even);\n..> }\ntotal_with_tax : (I64, view I64[%n], I64) -> I64   revision session@r3\nci[7]> total_with_tax(cents, 825)\n= 2635 : I64\nci[8]> :checkpoint priced\ncheckpoint priced   #1   bindings 2   revisions: session@r3\nci[8]> I64 total_with_tax[n](in I64[n] c, I64 rate_bp) {\n..>     I64 s = sum(c);\n..>     return s + div_round(s * rate_bp, 10000, half_up);\n..> }\ntotal_with_tax : (I64, view I64[%n], I64) -> I64   revision session@r4 (replaces r3)\nci[9]> total_with_tax([200], 825)\n= 217 : I64\nci[10]> :restore priced\nsaved current state as auto-1\nrestored priced   #1   total_with_tax is revision session@r3\nci[10]> total_with_tax([200], 825)\n= 216 : I64\nci[11]> :history total_with_tax\nr3  entry 6   in checkpoints: priced\nr4  entry 8   in checkpoints: auto-1\nci[11]> :save-case priced.cicase\nnote: the case includes every recorded observe result verbatim; this case has none\ncase priced.cicase   checkpoint priced   entry 10   effects 0   density entry\nci[11]> :save session-a\nsaved session to session-a   entries 10   checkpoints 2   objects 54\nci[11]> :quit\n```"
  },
  {
   "id": "spec-06p:exact-money-in-the-workbench-p2",
   "edition": "SPEC-06P.1",
   "title": "A.1 Exact money in the workbench (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#exact-money-in-the-workbench",
   "internal": 0,
   "content": "`half_even` rounds the exact quotient 16.5 to its even neighbor, 16, and `half_up` rounds it up, to 17; the session says that each result is inexact and gives the exact quotient. The module `money.ci` holds the same function with others, and `cint explain` (9.9) and `cint debug locate` (10.5) use it:\n\n```console\n$ cat money.ci\n// money.ci: amounts in whole cents, summed exactly and rounded once.\n\nexport I64 total_with_tax[n](in I64[n] c, I64 rate_bp) {\n    I64 s = sum(c);\n    return s + div_round(s * rate_bp, 10000, half_even);\n}\n\nexport I64 tax(I64 subtotal, I64 rate_bp) {\n    return div_round(subtotal * rate_bp, 10000, half_even);\n}\n\nexport I64 add_cents(I64 a, I64 b) {\n    return a + b;\n}\n\nexport I64 priced() {\n    I64[3] cents = [1999, 425, 10];\n    return total_with_tax(cents, 825);\n}\n\nexport I64 overflow() {\n    I64 big = 9223372036854775800;\n    return add_cents(big, 12);\n}\n\ntest \"the tie at 16.5 cents rounds to even\" {\n    assert(tax(200, 825) == 16);\n}\n```"
  },
  {
   "id": "spec-06p:from-a-test-to-a-located-fault",
   "edition": "SPEC-06P.1",
   "title": "A.2 From a test to a located fault",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#from-a-test-to-a-located-fault",
   "internal": 0,
   "content": "### A.2 From a test to a located fault\n\nThe tests of `money.ci` pass, and its function `overflow` faults. `cint debug locate` finds the fault and saves the run as a case, `cint debug diff` shows that both executors give the case the same fault, and a session on the case shows the fault, the operations that led to it and what the run recorded:"
  },
  {
   "id": "spec-06p:from-a-test-to-a-located-fault-p1",
   "edition": "SPEC-06P.1",
   "title": "A.2 From a test to a located fault (part 2)",
   "clauses": "IM-121",
   "url": "/specifications/spec-06p/1/#from-a-test-to-a-located-fault",
   "internal": 0,
   "content": "```console\n$ cint test money.ci\ntest money.ci:26 \"the tie at 16.5 cents rounds to even\" ... ok\n1 of 1 tests passed\n$ cint debug locate money.ci --entry overflow --save-case overflow.cicase\nprogram    money.ci   evaluator cpu-sir-interp, recorded as the case overflow.cicase\ntarget     boundary 1 of 1, overflow(): the first fault, reproduced by replay\nbracket    the initial state; then boundary 1\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> money.ci:13:14\n...\n$ cint debug diff overflow.cicase\ncase       overflow.cicase   1 boundary   density entry\nreference  cpu-c17\ncandidate  cpu-sir-interp\nboundaries 1 of 1 compared\noutcome    agree\n$ cint debug overflow.cicase\ncint workbench   profile cint-core-1   backend cpu-sir-interp   debug overflow.cicase (read-only)\ncase: entries 1   boundaries 1\nat the end of entry 1, reached by replay\nci[2]> :fault\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> money.ci:13:14\n   = operation: add.checked.i64\n   = operand-count: 2\n   = operand: I64 9223372036854775800\n   = operand: I64 12\n   = exact:   9223372036854775812\n   = limit:   I64 9223372036854775807\n   = revision: 602173cd38defe996814e3298bd2a45c715a1cea53e3b5f8f84f6d073777ebde\n   = source-map: none\n   = address: none\n   = stack-depth: 1\n   = called from: money.ci:23:12\n   = state: the state the fault left, reached by replay (SPEC-01 IM-121)\n   = noncanonical: not part of the fault record\n   = stack-source: money.ci:23:12 (source not loaded)\n   = workbench-position: entry 1\n   = site: add_cents#10\n   = backend: cpu-sir-interp\nci[2]> :trace fault\nentry 1   money.ci: overflow()   evaluator cpu-sir-interp, by replay\n  ord  position           operation              operands                 value\n    0  money.ci:23:12     call                   9223372036854775800, 12\n    1  money.ci:13:14     add.checked.i64        9223372036854775800, 12  "
  },
  {
   "id": "spec-06p:from-a-test-to-a-located-fault-p2",
   "edition": "SPEC-06P.1",
   "title": "A.2 From a test to a located fault (part 3)",
   "clauses": "",
   "url": "/specifications/spec-06p/1/#from-a-test-to-a-located-fault",
   "internal": 0,
   "content": "The rest of the `locate` report is that of 10.5, paragraph 8. The diff agrees because both executors raise the same fault, with the same operands, at the same operation. The session's fault report has no source excerpt even though the case holds the source."
  },
  {
   "id": "spec-09p:spec-09p-1",
   "edition": "SPEC-09P.1",
   "title": "SPEC-09P.1",
   "clauses": "",
   "url": "/specifications/spec-09p/1/",
   "internal": 0,
   "content": "# SPEC-09P.1: Toolchain and conformance\n\nSPEC-09P.1, edition 1 of the toolchain and conformance specification, cint v0.2.0, 2026-10-11."
  },
  {
   "id": "spec-09p:foreword",
   "edition": "SPEC-09P.1",
   "title": "Foreword",
   "clauses": "EMIT-03 SIR-09",
   "url": "/specifications/spec-09p/1/#foreword",
   "internal": 0,
   "content": "## Foreword\n\nThis document specifies how the cint toolchain of cint 0.2.0 is built and checked: the intermediate representation that its compiler produces, the C that the compiler emits and the runtime that C calls, what two implementations of cint must agree on, the conformance suite that measures that agreement, the bootstrap of the compiler from a hand-written C program, and the receipts from which a reader reruns a published figure.\n\nEach rule ends with one or more clause identifiers in brackets, such as [SIR-09] or [EMIT-03]. An identifier names one rule across editions: a rule keeps its identifier when its text moves to another section or another document, and an identifier is not reused. Code comments, test files and receipts cite rules by these identifiers. Section numbers belong to this edition only."
  },
  {
   "id": "spec-09p:introduction",
   "edition": "SPEC-09P.1",
   "title": "Introduction",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#introduction",
   "internal": 0,
   "content": "## Introduction\n\ncint has one specification of meaning, SPEC-04P.2, and several implementations of it. A program compiled to C, the same program run by the interpreter, and a program whose kernels run on a GPU must give the same output bytes, the same fault record and the same count of fuel. A separate implementation written in Python, the reference, runs each program from its source text and gives the expected results. This document says how these implementations are built, what they must agree on, and how that agreement is measured and recorded.\n\nA small program shows what agreement means. It prints a sum of squares and then narrows the sum to a type too small for it.\n\n```cint agree.ci\nI64 total = 0;\nfor i in 1..=10 {\n    total += i * i;\n}\n\"{total}\\n\";\nI8 small = total as I8;\n\"{small}\\n\";\n```\n\n```text\n385\nfault[E_NARROW]: the value does not fit the destination type\n  --> agree.ci:6:18\n   |\n 6 | I8 small = total as I8;\n   |                  ^ as.checked.i64.i8\n   |\n   = operation: as.checked.i64.i8\n   = operand-count: 1\n   = operand: I64 385\n   = exact:   385\n   = limit:   I8 127\n...\n```\n\n`cint run` compiled the program to C, built it and ran it. The reference shares no code with the compiler (5.4). It reads the same source and prints the outcome as the text that the conformance suite stores (9.3):\n\n```console\n$ python3 -m cint_ref run agree.ci\ncase agree\nsource reference\noutcome fault\nstdout-bytes 4\nstdout-sha256 5476dba1f4bd59f1444ca1fd0770c1db808311b772f7685b3ff60ad7956418a8\nfuel-consumed 11\nfault.code E_NARROW\nfault.operation as.checked.i64.i8\nfault.operand I64 385\nfault.exact 385\nfault.limit I8 127\nfault.position agree.ci:6:18\nfault.revision self\nfault.address none\nfault.stack-depth 0\n```"
  },
  {
   "id": "spec-09p:introduction-p1",
   "edition": "SPEC-09P.1",
   "title": "Introduction (part 2)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#introduction",
   "internal": 0,
   "content": "The two agree. Both wrote the same 4 bytes, `385` and a line feed, whose SHA-256 digest is the `stdout-sha256` line. Both stopped at the conversion at `agree.ci:6:18`, with the same operation, operand, exact result and limit. Both consumed 11 units of fuel: 1 for the entry and 1 for each of the 10 loop iterations. The line `fault.revision self` stands for the revision of the program under test, which the reference does not compute (6.5)."
  },
  {
   "id": "spec-09p:how-this-document-is-organized",
   "edition": "SPEC-09P.1",
   "title": "How this document is organized",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#how-this-document-is-organized",
   "internal": 0,
   "content": "### How this document is organized\n\nClauses 1 to 4 state what the document covers, the documents it relies on, its terms and what conformance means. Clause 5 describes the architecture: one front end, one intermediate representation, three executors and the reference. Clause 6 defines that intermediate representation, SIR, and its text form. Clause 7 defines the C that the compiler emits and the runtime contract it relies on. Clause 8 says what two implementations must agree on and how a case that is not compared is reported. Clause 9 describes the conformance suite and how to run one case. Clause 10 describes the bootstrap of the compiler and what its self-hosting fixpoint shows and does not show. Clause 11 describes receipts and how a reader reruns a published figure. Clause 12 lists the constructs that the tools of cint 0.2.0 refuse. Clause 13 names two future directions. Annex A gives the measured figures of the release, and the Bibliography lists the works cited for information.\n\nEvery example in this document was run with the tools of cint 0.2.0. A `cint` block is a complete program, and the `text` block after it is its output exactly as `cint run` prints it. A `console` block is a tool session: a line that begins `$ ` is a command, the lines after it are its output exactly as printed, and a line `...` stands for lines left out. Commands that name a file of the source tree, such as `tools/cint_check.py`, are run from the root of the tree. The others are run from a directory that holds the example's files. In every session the tree's `ref/` directory is on `PYTHONPATH`, so that `python3 -m cint_ref` runs the reference, and the `cint` command is on `PATH`. Digests in the output change when the sources change, so the text says what each digest is, not its value."
  },
  {
   "id": "spec-09p:scope",
   "edition": "SPEC-09P.1",
   "title": "1 Scope",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#scope",
   "internal": 0,
   "content": "## 1 Scope\n\n1. This document specifies, for cint 0.2.0:\n   - the architecture of the toolchain: its front end, its intermediate representation, its executors and the reference;\n   - the semantic intermediate representation (SIR), its text form and the revision identity computed from it;\n   - the C that the compiler emits, and the runtime contract that this C relies on;\n   - what two implementations must agree on, and how a refusal or a disagreement is reported;\n   - the conformance suite: case files, the `.expect` format, operation fixtures, required case lists, and how one case is run;\n   - the bootstrap of the compiler and its self-hosting fixpoint;\n   - receipts, and how a reader reruns a published figure;\n   - the constructs that the tools of cint 0.2.0 refuse.\n2. This document does not specify:\n   - the language, which SPEC-04P.2 specifies;\n   - the byte encodings of fault records and program state, which SPEC-01P.2 specifies;\n   - how an executor carries out a kernel dispatch, which SPEC-02P.1 specifies;\n   - the C and Python interfaces through which a host program calls cint code, which SPEC-03P.1 specifies;\n   - the commands of the cint tools, which SPEC-06P.1 specifies."
  },
  {
   "id": "spec-09p:normative-references",
   "edition": "SPEC-09P.1",
   "title": "2 Normative references",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#normative-references",
   "internal": 0,
   "content": "## 2 Normative references\n\nThe following documents are referred to in the text in such a way that some or all of their content constitutes requirements of this document. For dated references, only the edition cited applies.\n\n- ISO/IEC 9899:2018, *Information technology: Programming languages: C* (C17). Used for the language of emitted C and for the behaviors that clause 7 avoids.\n- D. Crocker, editor and P. Overell. *Augmented BNF for Syntax Specifications: ABNF*. RFC 5234 (STD 68), January 2008. Used for the grammar of 9.3.\n- P. Kyzivat. *Case-Sensitive String Support in ABNF*. RFC 7405, December 2014. Used for the `%s\"...\"` strings of 9.3.\n- A. Rundgren, B. Jordan and S. Erdtman. *JSON Canonicalization Scheme (JCS)*. RFC 8785, June 2020. Used for the bytes of a receipt, with the departure in the escaping of strings that 11.2 states.\n- T. Bray, editor. *The I-JSON Message Format*. RFC 7493, March 2015. Used for the integer range of a receipt.\n- National Institute of Standards and Technology. *Secure Hash Standard (SHS)*. FIPS PUB 180-4, August 2015. Used for SHA-256.\n- F. Yergeau. *UTF-8, a transformation format of ISO 10646*. RFC 3629 (STD 63), November 2003.\n- The Unicode Consortium. *The Unicode Standard, Version 17.0.0*, 2025. Used for the term Unicode scalar value (8.1)."
  },
  {
   "id": "spec-09p:terms-definitions-and-symbols",
   "edition": "SPEC-09P.1",
   "title": "3 Terms, definitions and symbols",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "## 3 Terms, definitions and symbols\n\nThe terms of SPEC-04P.2 clause 3 apply, among them diagnostic, refusal, implementation, the reference, executor, entry, fuel, semantic input and revision. The following terms are added. Other terms are defined where they first appear, in italic type.\n\n<a id=\"term-toolchain\"></a>**3.1 toolchain**: the programs of cint 0.2.0 that translate, run and check cint programs: the compiler `cintc`, the `cint` command and its subcommands, the interpreter `cint-interp`, the runtime and the conformance tools under `tools/` and `conformance/tools/`.\n\n<a id=\"term-front-end\"></a>**3.2 front end**: the part of the compiler that reads source text, checks it and produces SIR.\n\n<a id=\"term-sir\"></a>**3.3 SIR**: the semantic intermediate representation, the form of a checked program that every executor of the toolchain runs (clause 6).\n\n<a id=\"term-node\"></a>**3.4 node**: one operation of SIR, such as one checked addition or one call.\n\n<a id=\"term-site\"></a>**3.5 site**: a node that can fault, identified by its module and its ordinal within the module, with the source position and the operation identifier that a fault record reports for it.\n\n<a id=\"term-emitted-c\"></a>**3.6 emitted C**: the C17 source text that the compiler writes for a program.\n\n<a id=\"term-runtime\"></a>**3.7 runtime**: the C code declared in `rt/cint_rt.h` and `rt/cint_rt_host.h` and built as the library `cint_rt`, which emitted C and the interpreter `cint-interp` call for checked arithmetic, fuel, call depth and fault records (SPEC-03P.1, 3.3). Its interface is the runtime contract of 7.10.\n\n<a id=\"term-helper\"></a>**3.8 helper**: a function of the runtime that performs one operation of one type and reports its fault, such as `cint_add_i64`."
  },
  {
   "id": "spec-09p:terms-definitions-and-symbols-p1",
   "edition": "SPEC-09P.1",
   "title": "3 Terms, definitions and symbols (part 2)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "<a id=\"term-capability\"></a>**3.9 capability**: a set of SIR node families, forms and types that an executor carries out with their exact meaning. An executor's *capability table* lists, for every family, form and type, whether it is supported.\n\n<a id=\"term-conformance-case\"></a>**3.10 conformance case**: a program, or one operation, together with its expected outcome.\n\n<a id=\"term-expectation\"></a>**3.11 expectation**: the expected outcome of a conformance case, written in the `.expect` format of 9.3. A *frozen* expectation is one that is part of the suite and is not edited in place (9.1).\n\n<a id=\"term-canonical-outcome\"></a>**3.12 canonical outcome**: what implementations compare for one entry: the output bytes, the kind of outcome, the returned value, the fuel consumed and the fault record, or, for a rejected program, the diagnostic code and position.\n\n<a id=\"term-agreement\"></a>**3.13 agreement**: the relation between two implementations whose canonical outcomes for a program and the same semantic inputs are equal in the sense of 8.1.\n\n<a id=\"term-receipt\"></a>**3.14 receipt**: a canonical JSON file (11.2) that records one run of a tool: its inputs, its outcome and what it observed. A bootstrap, a fixpoint run and a conformance run each write one, and so do the tools of SPEC-06P.1 that take `--receipt` (SPEC-06P.1 12).\n\n<a id=\"term-receipt-identity\"></a>**3.15 receipt identity**: the SHA-256 digest of the canonical bytes of a receipt's inputs and outcome (11.2). Two runs with the same receipt identity had the same inputs and the same outcome.\n\n<a id=\"term-configuration\"></a>**3.16 configuration**: one choice of C toolchain, optimization level, helper mode (7.3) and sanitizers under which the toolchain and the programs it compiles are built."
  },
  {
   "id": "spec-09p:terms-definitions-and-symbols-p2",
   "edition": "SPEC-09P.1",
   "title": "3 Terms, definitions and symbols (part 3)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#terms-definitions-and-symbols",
   "internal": 0,
   "content": "<a id=\"term-compiler-source-identity\"></a>**3.17 compiler source identity**: the SHA-256 digest of the source manifest of the compiler's source files (11.2).\n\n<a id=\"term-bootstrap\"></a>**3.18 bootstrap**: the building of the compiler from its source text and a C toolchain, with no cint compiler built earlier.\n\n<a id=\"term-fixpoint\"></a>**3.19 fixpoint**: the state in which the compiler, built from the C that it emitted for its own source, emits that same C again."
  },
  {
   "id": "spec-09p:conformance",
   "edition": "SPEC-09P.1",
   "title": "4 Conformance",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#conformance",
   "internal": 0,
   "content": "## 4 Conformance\n\n1. In this document, a rule is stated in the present tense, as a fact about a conforming implementation or tool, and ends with its clause identifiers (Foreword). \"May\" states a permission.\n2. Clauses 6 and 7 apply to the toolchain and to any other implementation that produces SIR or emits C for the runtime of 7.10. Clauses 8 to 11 apply to every implementation that claims agreement with the reference.\n3. A conformance run is evidence of agreement for the cases it runs, in the configurations it runs. It does not define the language: where an implementation and SPEC-04P.2 differ, SPEC-04P.2 governs, and the difference is a defect of the implementation or an ambiguity in the text.\n4. Clause 12, Annex A, the examples and the notes are informative."
  },
  {
   "id": "spec-09p:architecture",
   "edition": "SPEC-09P.1",
   "title": "5 Architecture",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#architecture",
   "internal": 0,
   "content": "## 5 Architecture\n\nThe toolchain turns a program's source text into one checked representation and runs that representation in several ways. Each way of running it is held to the same expected results, which a separately written implementation computes from the source text alone."
  },
  {
   "id": "spec-09p:overview",
   "edition": "SPEC-09P.1",
   "title": "5.1 Overview",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#overview",
   "internal": 0,
   "content": "### 5.1 Overview\n\n1. The figure shows the parts and how outcomes are compared.\n\n```text\n                     source text (.ci)\n                            |\n             +--------------+---------------+\n             |                              |\n     cintc front end                 the reference\n             |                       (cint_ref, Python,\n            SIR                       reads the source itself)\n             |                              |\n   +---------+-----------+                  |\n   |         |           |                  |\n cpu-c17  cpu-sir-interp gpu-cuda           |\n emitted  cint-interp    cpu-c17 plus       |\n C and    runs the SIR   PTX for the        |\n runtime  text           work-item bodies   |\n   |         |           |                  |\n   +---------+-----------+--------+---------+\n                                  |\n                 canonical outcomes, compared (clause 8)\n```"
  },
  {
   "id": "spec-09p:one-front-end",
   "edition": "SPEC-09P.1",
   "title": "5.2 One front end",
   "clauses": "ARCH-01",
   "url": "/specifications/spec-09p/1/#one-front-end",
   "internal": 0,
   "content": "### 5.2 One front end\n\nThe compiler `cintc` is written in cint and is the only front end of the toolchain.\n\n**Semantics**\n\n1. <a id=\"ARCH-01\"></a>One front end produces the SIR of a program, and every path that runs or describes the program takes that SIR: `cint run`, `cint build`, `cint test`, `cint emit-c`, the interpreter and the debugging tools `cint-explain` and `cint-workbench`. Arithmetic is carried out in these places only, each held to the conformance suite: the helpers of the runtime (7.10), the constant evaluation of the front end (held by the constant and run-time category of 9.4), each executor on its capability table, and the reference. The interpreter calls the runtime helper for every arithmetic, conversion and built-in node, the same helper that emitted C calls for that node, so it adds no arithmetic of its own [ARCH-01]."
  },
  {
   "id": "spec-09p:executors",
   "edition": "SPEC-09P.1",
   "title": "5.3 Executors",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#executors",
   "internal": 0,
   "content": "### 5.3 Executors\n\nAn executor runs the SIR of a program. cint 0.2.0 has three: `cpu-c17`, `cpu-sir-interp` and `gpu-cuda`.\n\n**Semantics**"
  },
  {
   "id": "spec-09p:executors-p1",
   "edition": "SPEC-09P.1",
   "title": "5.3 Executors (part 2)",
   "clauses": "BACK-01 BACK-01a BACK-03 BACK-15 BACK-16",
   "url": "/specifications/spec-09p/1/#executors",
   "internal": 0,
   "content": "1. The executor `cpu-c17` runs a program as C17 that the compiler emits (clause 7), compiled by a C toolchain and linked with the runtime. It runs the work-items of a kernel dispatch one at a time, in canonical order, stages the outputs and publishes them only when the dispatch ends without a fault.\n2. <a id=\"BACK-03\"></a>`cpu-c17` is the reference implementation of the language on a CPU and the oracle against which other executors are compared. Where it and SPEC-04P.2 differ, SPEC-04P.2 governs (clause 4, paragraph 3). Every other executor is admitted by comparing its outcomes with those of `cpu-c17` and of the reference on the conformance suite [BACK-03].\n3. <a id=\"BACK-01\"></a>An executor that writes files is a module of `cintc`, compiled into it. The compiler loads no executor code when it runs, because such code would lie outside the compiler source identity [BACK-01].\n4. <a id=\"BACK-01a\"></a>The executor `cpu-sir-interp` is the interpreter `cint-interp`, a C17 program outside `cintc`. It reads the SIR text that `cintc` writes for each module (6.2) and the program file `cint-program.sites` that lists the modules. Before it runs a program it checks the verifier rules it relies on (each temporary defined once and before it is used, the operand types, and a site on every node that can fault) and recomputes the revision identity (6.5); a text that fails these checks is reported with its position and is not run. It needs neither `cintc` nor a C compiler at run time. It calls the runtime helper for each arithmetic, conversion and built-in node and uses the `cint_rt` library for contexts, fault records and output. It executes the structured control flow of SIR as written, keeps frames under the depth limit, counts local arrays against the frame-arena capacity in elements, charges fuel only where SIR charges it (6.1), and runs the work-items of a dispatch one at a time i"
  },
  {
   "id": "spec-09p:executors-p2",
   "edition": "SPEC-09P.1",
   "title": "5.3 Executors (part 3)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#executors",
   "internal": 0,
   "content": "**Notes**\n\n7. SPEC-02P.1 specifies how each executor carries out a dispatch so that its outcome is the sequential one."
  },
  {
   "id": "spec-09p:the-reference",
   "edition": "SPEC-09P.1",
   "title": "5.4 The reference",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-reference",
   "internal": 0,
   "content": "### 5.4 The reference\n\nThe reference `cint_ref` is a Python program that runs cint source directly. Its results are the expected results of the conformance suite.\n\n**Semantics**"
  },
  {
   "id": "spec-09p:the-reference-p1",
   "edition": "SPEC-09P.1",
   "title": "5.4 The reference (part 2)",
   "clauses": "ARCH-02",
   "url": "/specifications/spec-09p/1/#the-reference",
   "internal": 0,
   "content": "1. <a id=\"ARCH-02\"></a><a id=\"REF-01\"></a>The reference is written in Python with the standard library only. It reads `.ci` source, parses it with its own parser, and executes it on Python integers, which have no fixed width, with an explicit range check after every operation that can overflow. It shares no code, tables, grammar files or generated files with the compiler or the runtime: it does not import, generate from or read any file of `cintc`, of the bootstrap compiler (10.2) or of `rt/cint_rt.h`. It enforces the call-depth limit itself, faulting `E_DEPTH`, so the recursion limit of Python is not reached first [ARCH-02, REF-01].\n2. <a id=\"REF-02\"></a>The reference shares no code with the compiler, but it is not independent of it in a stronger sense. Both were written from the same specification text, so an ambiguity in the text can reach both. The check on such shared errors is the set of anchor cases (9.2), each derived by hand with its derivation written beside it [REF-02].\n3. <a id=\"REF-03\"></a>The reference runs the work-items of a kernel dispatch one at a time in canonical order, stages the outputs and publishes them only on success. It reports each fault with the full fault record except the revision, which it does not compute [REF-03].\n4. <a id=\"REF-04\"></a>Speed is not a requirement of the reference [REF-04].\n5. <a id=\"REF-08\"></a>Anyone may run the reference directly on a program in its scope, from its command line or inside another Python runtime. A direct run is not a conformance run and writes no receipt. The reference does not define the meaning of a program: this specification does, and the reference is held to it [REF-08].\n6. <a id=\"REF-07\"></a>The reference runs one `test` block of a module as its entry, in a fresh context, with `python3 -m cint_ref run FILE.ci --test NAME`, where `NAME` is the test's name. The outcome of the test body gives the v"
  },
  {
   "id": "spec-09p:capabilities-and-refusal",
   "edition": "SPEC-09P.1",
   "title": "5.5 Capabilities and refusal",
   "clauses": "ARCH-03 BACK-04 BACK-05 BACK-06",
   "url": "/specifications/spec-09p/1/#capabilities-and-refusal",
   "internal": 0,
   "content": "### 5.5 Capabilities and refusal\n\nAn executor that cannot carry out a node with its exact meaning refuses the program before it runs. It does not run the program with another meaning.\n\n**Semantics**\n\n1. <a id=\"ARCH-03\"></a>The executor is chosen per build. An executor that cannot carry out a SIR node with its exact meaning refuses the program at translation with `E_UNSUPPORTED`, naming the node, its source position and the missing capability. No executor narrows, wraps or reorders an operation to fit what it supports [ARCH-03].\n2. <a id=\"BACK-04\"></a>Each executor has a capability table: for every SIR node family, form and type, one of `native`, `lowered:<strategy>` or `unsupported`. The table is part of the compiler source. The table of `gpu-cuda` is the comment at the head of `compiler/back_ptx.ci` [BACK-04].\n3. <a id=\"BACK-05\"></a>A program that needs an `unsupported` entry of the selected executor fails to build with `E_UNSUPPORTED`, naming the node, its site and the capability. A device that lacks, when a program is loaded, a capability that translation assumed fails the load with `E_UNSUPPORTED` before any kernel is prepared. Execution does not fall back to a narrower type [BACK-05].\n4. <a id=\"BACK-06\"></a>A `lowered:<strategy>` entry names a lowering, such as carrying out a 64-bit operation in two 32-bit words, that has conformance cases of its own. A lowering is admitted only when those cases pass [BACK-06].\n\n**Examples**\n\n5. The kernel below doubles each element with the saturating `+|`. The executor `cpu-c17` runs it.\n\n```cint sat.ci\nkernel k[n](in I64[n] a, out I64[n] b) over [i: n] {\n    b[i] = a[i] +| a[i];\n}\n\nexport I64 run() {\n    I64[4] a;\n    I64[4] b;\n    for j in 0..4 { a[j] = (j + 1) as I64; }\n    k(a, b);\n    return b[3] as I64;\n}\n\"{run()}\\n\";\n```\n\n```text\n8\n```"
  },
  {
   "id": "spec-09p:capabilities-and-refusal-p1",
   "edition": "SPEC-09P.1",
   "title": "5.5 Capabilities and refusal (part 2)",
   "clauses": "BACK-05",
   "url": "/specifications/spec-09p/1/#capabilities-and-refusal",
   "internal": 0,
   "content": "The capability table of `gpu-cuda` lists saturating arithmetic as `unsupported`. The emitted C carries the refusal inside the block that only a `gpu-cuda` build compiles:\n\n```console\n$ cint emit-c --root . --out out sat.ci\n$ grep '#error' out.stage-0/sat.c\n#error \"gpu-cuda: E_UNSUPPORTED: kernel sat.k needs capability sat, node 35, at 2:17 (SPEC-09 BACK-05)\"\n```\n\nA `gpu-cuda` build compiles this file with the macro `CINT_GPU_CUDA` defined, so it stops at the `#error`, which names the kernel, the capability, the SIR node and the position `2:17` of the `+|`. A `cpu-c17` build of the same file does not define the macro and runs the program."
  },
  {
   "id": "spec-09p:the-compiler",
   "edition": "SPEC-09P.1",
   "title": "5.6 The compiler",
   "clauses": "CINTC-01 CINTC-02",
   "url": "/specifications/spec-09p/1/#the-compiler",
   "internal": 0,
   "content": "### 5.6 The compiler\n\nThe compiler is a checked cint program. It keeps all its state in tables whose sizes it computes before it starts, and a host program drives it.\n\n**Semantics**\n\n1. The source of the compiler is the import closure of `compiler/main.ci`. In cint 0.2.0 it is 14 modules: `back_c`, `back_ptx`, `check`, `decl`, `emit`, `fold`, `limits`, `lowering`, `main`, `parse`, `resolve`, `scan`, `sha256` and `verify`, each a file `compiler/<name>.ci`.\n2. <a id=\"CINTC-01\"></a>All compiler state lives in tables of fixed capacity. The capacity of each table is a formula of the sizes of the inputs, capped by a hard limit. An input that exceeds a capacity is reported with the diagnostic C9001, naming the table, the limit and the source position; it does not crash the compiler and is not cut short silently [CINTC-01].\n3. <a id=\"CINTC-02\"></a>Blocks nest at most 256 deep, not counting the body of a function or a test, and the `{` of a block 257 deep is the diagnostic C9004; the arms of an `else if` chain or a `switch` do not nest (paragraph 4). An expression nests as deep as the parser's stack holds, and beyond that is also C9004. The `cint` command reads at most 2,048 modules for one program, and stops a program of more with a tool error and exit status 5; 12 states what it does with a source file beyond the limit below. For a module of `n` source bytes, whose number of tokens, `tokens`, is at most `n + 1`, the tables have these capacities and hard limits; each division rounds down [CINTC-02]:"
  },
  {
   "id": "spec-09p:the-compiler-p1",
   "edition": "SPEC-09P.1",
   "title": "5.6 The compiler (part 2)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-compiler",
   "internal": 0,
   "content": "| Table | Capacity | Hard limit |\n|---|---|---|\n| Source | `n` bytes | 4,194,304 bytes per module, 67,108,864 bytes per program |\n| Modules | the modules of the build | 4,096 per program |\n| Syntax nodes | `2 * tokens + 16` | set by the source limit |\n| Symbols | `tokens / 2 + 64` | 1,048,576 per module |\n| Functions | `tokens / 4 + 1` | 65,536 per module |\n| Types | `256 + tokens / 8` | 65,536 per module |\n| SIR nodes | `4 * tokens + 16` | set by the source limit |\n| Parser stack | `512 + tokens / 32` frames | 131,072 frames |\n| Declarations seen across modules | 1, plus `n / 4 + n / 32 + 1` for each module | 1,048,576 per program |\n| Output | the bytes that `measure` counts | 268,435,456 bytes per module |\n| Retained diagnostics | 100 per module | 100 per module |"
  },
  {
   "id": "spec-09p:the-compiler-p2",
   "edition": "SPEC-09P.1",
   "title": "5.6 The compiler (part 3)",
   "clauses": "CINTC-03 CINTC-04 CINTC-05 CINTC-10",
   "url": "/specifications/spec-09p/1/#the-compiler",
   "internal": 0,
   "content": "4. <a id=\"CINTC-03\"></a>A chain of `else if` arms, and the arms of a `switch`, are one node with an ordered list of arms, and every pass of the compiler walks the list iteratively. A chain of 1,000 arms therefore uses the same stack depth as a chain of 2 [CINTC-03].\n5. <a id=\"CINTC-05\"></a>The compiler uses no heap allocator and requests no memory during a call. A host program, the bridge (`rt/cint_bridge.c` and `rt/cint_build.c`), drives it through four exported calls: `plan`, which computes the size of every table from the sizes of the inputs; `compile`, which reads the source of a module into the tables and produces its SIR or its diagnostics; `measure`, which counts the bytes of each output file of a module; and `emit`, which writes them. The bridge allocates the tables after `plan` and the output buffers after `measure` [CINTC-05].\n6. <a id=\"CINTC-04\"></a>`measure` and `emit` run over the same SIR in separate calls. The bridge allocates exactly the number of bytes `measure` counted, and `emit` writes exactly that many; a different count is an internal compiler error [CINTC-04].\n7. The compiler performs no input or output of its own. 7.1 describes how the bridge reads its inputs and commits its outputs.\n8. <a id=\"CINTC-10\"></a>A fault inside the compiler, such as an index outside a table, is reported as an internal compiler error with the full fault record, the compiler source identity and the identity of the compiler's inputs [CINTC-10].\n\n**Notes**\n\n9. Because the compiler is a checked program, a fault inside it stops it instead of corrupting memory. A logic error that produces wrong output without a fault, such as lowering `+` to `+%`, is found only by the conformance suite and the fixpoint (10.4)."
  },
  {
   "id": "spec-09p:sir",
   "edition": "SPEC-09P.1",
   "title": "6 SIR",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#sir",
   "internal": 0,
   "content": "## 6 SIR\n\nSIR is the program after it has been checked: every value has its type, every intermediate value has a name, control flow is structured, and every point where the program can fault is marked with its source position. Every executor of the toolchain runs SIR, and `cint-explain` prints it."
  },
  {
   "id": "spec-09p:design-rules",
   "edition": "SPEC-09P.1",
   "title": "6.1 Design rules",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#design-rules",
   "internal": 0,
   "content": "### 6.1 Design rules\n\n**Semantics**"
  },
  {
   "id": "spec-09p:design-rules-p1",
   "edition": "SPEC-09P.1",
   "title": "6.1 Design rules (part 2)",
   "clauses": "SIR-01 SIR-02 SIR-03 SIR-04 SIR-05 SIR-06 SIR-07 SIR-15 SIR-16",
   "url": "/specifications/spec-09p/1/#design-rules",
   "internal": 0,
   "content": "1. <a id=\"SIR-01\"></a>SIR is typed. Every temporary, local, parameter and result has exactly one cint type, `Bool` for comparisons and conditions. There is no implicit conversion: every change of width or signedness is an `as` node [SIR-01].\n2. <a id=\"SIR-02\"></a>Every node that produces a value defines a new temporary, `%t0`, `%t1` and so on, exactly once. A variable of the source is a *slot*, read by `load.local` and written by `store.local`. Nodes are evaluated in the order they are written; nothing in SIR is unordered [SIR-02].\n3. <a id=\"SIR-03\"></a>A checked operation is one node, such as `add.checked.i64`, not an addition followed by a test. An executor lowers the node as a unit and cannot separate the check from the operation [SIR-03].\n4. <a id=\"SIR-04\"></a>Every node that can fault, including a fuel charge and a call, is a site: it carries its module, line, column and operation identifier. Sites are numbered from 1 in each module, in node order; the number 0 means no site [SIR-04].\n5. <a id=\"SIR-05\"></a>Control flow is structured: blocks, `if`, `loop`, `switch`, `break`, `continue`, `return` and the fault exit. There is no arbitrary jump. `&&` and `||` become an `if` that evaluates the right operand only when it is needed. A chain of `else if` arms is one `if` node with an ordered list of arms. The interpreter runs this structure as it is written and lowers nothing itself [SIR-05].\n6. <a id=\"SIR-06\"></a>The front end resolves every default of the language before it writes SIR. A fixed-point multiplication carries its intermediate width and its rounding mode even when the source used the default, and a reduction carries the width of its accumulator. An executor does not supply a default [SIR-06].\n7. <a id=\"SIR-07\"></a>Every fuel charge is explicit in SIR, so every executor charges at the same points. An entry's charge and a loop iteration's charge are `fuel.cha"
  },
  {
   "id": "spec-09p:the-text-form",
   "edition": "SPEC-09P.1",
   "title": "6.2 The text form",
   "clauses": "SIR-09 SIR-09a",
   "url": "/specifications/spec-09p/1/#the-text-form",
   "internal": 0,
   "content": "### 6.2 The text form\n\nSIR has one text form. The compiler writes it for every module, the interpreter reads it, and `cint-explain` prints it.\n\n**Semantics**\n\n1. <a id=\"SIR-09\"></a>The text form is ASCII with LF line endings and one node per line. Temporaries are numbered from `%t0` in each function, in the order they are defined. A node that is a site ends with its ordinal and position, `#<ordinal> @<path>:<line>:<column>`, where `<path>` is the module-relative path. A node is indented two spaces for each level of structure that encloses it, up to 16 levels and 32 spaces at any deeper level, so the size of the text stays linear in the number of nodes; braces carry the structure [SIR-09].\n2. <a id=\"SIR-09a\"></a>The text of a module is, in order: a line `module <name>` with the module's dotted name; the `sites` line, `sites <path>` followed by one item `<ordinal>:<line>:<column>:<operation>` for each site in node order; one `struct` line for each struct type of the module, in declaration order; one `global` line for each module-level variable, in declaration order; and the functions, kernels, script body and test blocks of the module. In the `sites` line, the operation of a call's site is `call.enter`, that of a print statement's site is `print`, and that of any other site is the node's own operation identifier. On a node line, a site's annotation begins at the 50th character, or after it when the node text is longer, with at least one space before it. A parameter is written `%<name>`, a slot `$<name>.<k>`, a module-level variable `@<name>` and a structure that `break` or `continue` names `L<k>`; these numbers count from 0, and site ordinals from 1. Values are decimal, and printed text is written in double quotes with `\\\"`, `\\\\`, `\\n`, `\\t` and `\\x<hh>` for other bytes outside printable ASCII [SIR-09a].\n3. The main forms are these."
  },
  {
   "id": "spec-09p:the-text-form-p1",
   "edition": "SPEC-09P.1",
   "title": "6.2 The text form (part 2)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-text-form",
   "internal": 0,
   "content": "| Form | Meaning |\n| --- | --- |\n| `func @<module>.<name>(%<p>: <T>, ...) -> <T> {` | A function; `-> <T>` is absent when it has no result, and the line begins `export ` for an exported function. |\n| `kernel @<module>.<name>(%<p>: <T>, ...) {` | A kernel. |\n| `script @<module> {` | The top-level statements of a script, its implicit entry. |\n| `test @<module> <k> {` | Test block `k` of the module. |\n| `local $<x>.<k>: <T>` | A slot comes into scope. |\n| `%t<N> = const <T> <value>` | A typed literal. |\n| `%t<N> = <operation> %<a>, %<b>` | An arithmetic, bitwise or comparison node, spelled as its operation identifier. A conversion and a unary node take one operand. |\n| `%t<N> = load.local $<x>.<k>`, `store.local $<x>.<k>, %<v>` | A slot is read or written. |\n| `%t<N> = call @<module>.<name>(<argument>, ...)` | A call, with `%t<N> =` when the function returns a scalar. |\n| `dispatch @<module>.<kernel>(<argument>, ...), <bits>` | A kernel dispatch. |\n| `fuel.charge <n>` | A charge of `n` units: an entry's, first in its body or a loop iteration's, after the loop's `while`. |\n| `if {`, `arm {`, `} then %<c> {`, `else {` | An `if` chain: each `arm` holds its condition's nodes and ends with `then`. |\n| `loop L<k> {`, `while %<c>`, `next` | A loop: its condition and `while`, which leaves the loop when `c` is false, the body, then `next`, the target of `continue` and the update. |\n| `switch L<k> %<v> {`, `case <items> {`, `default {` | A `switch`; items are values and inclusive ranges, such as `1, 3..=5`. |\n| `break L<k>`, `continue L<k>`, `return`, `return %<v>` | A jump. |\n| `print.begin`, `print.bytes \"<text>\"`, `print.value <T> %<v>`, `print.end` | One print statement. |\n| `}` | The end of a function or of a structure. |\n\n**Examples**\n\n4. A function and a script that calls it:\n\n```cint add.ci\nI64 add3(I64 a, I64 b, I64 c) {\n    return a + b + c;\n}\n\"{add3(1, 2, 3)}\\n\";\n```"
  },
  {
   "id": "spec-09p:the-text-form-p2",
   "edition": "SPEC-09P.1",
   "title": "6.2 The text form (part 3)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-text-form",
   "internal": 0,
   "content": "```text\n6\n```\n\n`cint emit-c` writes the SIR text of each module into a file named after the module with the extension `.sites`, beside its C file (7.1):\n\n```console\n$ cint emit-c --root . --out out add.ci\n$ cat out.stage-0/add.sites\nmodule add\nsites add.ci 1:2:14:add.checked.i64 2:2:18:add.checked.i64 3:4:1:fuel.charge 4:4:3:call.enter 5:4:1:print\nfunc @add.add3(%a: I64, %b: I64, %c: I64) -> I64 {\n  %t0 = add.checked.i64 %a, %b                   #1 @add.ci:2:14\n  %t1 = add.checked.i64 %t0, %c                  #2 @add.ci:2:18\n  return %t1\n}\nscript @add {\n  fuel.charge 1                                  #3 @add.ci:4:1\n  %t0 = const I64 1\n  %t1 = const I64 2\n  %t2 = const I64 3\n  %t3 = call @add.add3(%t0, %t1, %t2)            #4 @add.ci:4:3\n  print.begin                                    #5 @add.ci:4:1\n  print.value I64 %t3\n  print.bytes \"\\n\"\n  print.end\n}\n```\n\nThe two additions of `a + b + c` are sites 1 and 2, at the two `+` signs. The script charges 1 unit when its entry begins (site 3). The call charges its unit at the call's site (site 4, `call.enter`), where a call that would exceed the depth limit also faults. The function `add3` has no `fuel.charge` of its own, because it is entered only by calls.\n\n5. `cint-explain` prints the fault sites of a function and its SIR:\n\n```console\n$ cint-explain add.ci:add3\nmodule add.ci   revision bc1faa5409ed570368f6f2ed815f89623096edcce3fcde135d6a1db89a37a2f2\n\nfunction add3   add.sites:3   pure\n  signature  (in a: I64, in b: I64, in c: I64) -> I64\n  fault sites (2): 2 possible, 0 statically excluded\n    add3#1  add.ci:2:14  add.checked.i64  E_OVERFLOW possible\n    add3#2  add.ci:2:18  add.checked.i64  E_OVERFLOW possible\n...\n  sir\nfunc @add.add3(%a: I64, %b: I64, %c: I64) -> I64 {\n  %t0 = add.checked.i64 %a, %b                   #1 @add.ci:2:14\n  %t1 = add.checked.i64 %t0, %c                  #2 @add.ci:2:18\n  return %t1\n}\n```"
  },
  {
   "id": "spec-09p:the-text-form-p3",
   "edition": "SPEC-09P.1",
   "title": "6.2 The text form (part 4)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-text-form",
   "internal": 0,
   "content": "The first line gives the revision identity of the program (6.5). SPEC-06P.1 describes the other lines."
  },
  {
   "id": "spec-09p:verifier",
   "edition": "SPEC-09P.1",
   "title": "6.3 Verifier",
   "clauses": "SIR-10 SIR-11",
   "url": "/specifications/spec-09p/1/#verifier",
   "internal": 0,
   "content": "### 6.3 Verifier\n\n**Constraints**\n\n1. <a id=\"SIR-10\"></a>Before any executor runs, the verifier checks that every temporary is defined exactly once and before it is used; that the types of the operands match the node's signature exactly; that every node that can fault has a site; that every write goes to a view with write permission or carries the run-time `E_ALIAS` check; that kernel bodies meet the restrictions of SPEC-04P.2 6.13; and that the outputs of each dispatch are covered by one alias check over all its writable bindings. A failure is an internal compiler error that names the node, not a warning. The interpreter checks again, when it reads a SIR text, the rules it relies on (5.3) [SIR-10].\n2. <a id=\"SIR-11\"></a>The verifier computes the capabilities that each function and kernel needs. The executor's admission of a program compares this set with its capability table (5.5) [SIR-11]."
  },
  {
   "id": "spec-09p:transformations",
   "edition": "SPEC-09P.1",
   "title": "6.4 Transformations",
   "clauses": "SIR-12",
   "url": "/specifications/spec-09p/1/#transformations",
   "internal": 0,
   "content": "### 6.4 Transformations\n\n**Constraints**\n\n1. <a id=\"SIR-12\"></a>A transformation of SIR is admissible only if, for every input, it keeps the output bytes, whether a fault occurs, the full fault record (code, operation, operands, exact result, position and address, including the step ordinal), every effect that comes before the fault, and the fuel charged up to any point that can be observed [SIR-12]."
  },
  {
   "id": "spec-09p:revision-identity",
   "edition": "SPEC-09P.1",
   "title": "6.5 Revision identity",
   "clauses": "SIR-17",
   "url": "/specifications/spec-09p/1/#revision-identity",
   "internal": 0,
   "content": "### 6.5 Revision identity\n\nThe revision identity is a digest of a program's SIR with the source positions taken out. Fault records, checkpoints and receipts name a program by it.\n\n**Semantics**\n\n1. <a id=\"SIR-17\"></a>The *hashed encoding* of a module is its SIR text (6.2) with the `sites` line removed and, on every node line, the text ` @<path>:<line>:<column>` after the site ordinal removed. The ordinals `#<n>` stay, and so do the spaces before them; no line or column remains. The revision identity is the SHA-256 digest of these bytes, in order [SIR-17]:\n   - the domain `cint-core-1/revision/v1`, the profile name `cint-core-1` and the runtime contract version (7.10), each as a 32-bit little-endian length followed by its ASCII bytes;\n   - the number of modules, as a 32-bit little-endian integer;\n   - for each module, in byte order of its module-relative path: the path, as a 32-bit little-endian length followed by its UTF-8 bytes, then the hashed encoding, as a 64-bit little-endian length followed by its bytes."
  },
  {
   "id": "spec-09p:revision-identity-p1",
   "edition": "SPEC-09P.1",
   "title": "6.5 Revision identity (part 2)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#revision-identity",
   "internal": 0,
   "content": "   The fuel model is not an input of the revision identity. A separate *source-map digest* is the SHA-256 digest of the domain `cint-core-1/source-map/v1`, as a 32-bit little-endian length followed by its ASCII bytes; the number of modules, as a 32-bit little-endian integer; and for each module, in the same order, its path, as a 32-bit little-endian length followed by its UTF-8 bytes, its number of sites, as a 32-bit little-endian integer, and for each item of its `sites` line, in the line's order, the ordinal, line and column, as 32-bit little-endian integers, and the operation, as a 32-bit little-endian length followed by its ASCII bytes. Both are recorded with a program. Fault positions are read through the source map recorded with the revision. The interpreter recomputes the revision identity from the text it reads, so a checkpoint, a recording or a case runs on it only with the revision it names.\n**Examples**\n\n2. For `add.ci` of 6.2, the hashed encoding of the module `add.ci` is the text of `add.sites` without its second line, with each ` @add.ci:<line>:<column>` removed. Its revision identity is the digest that `cint-explain` printed in 6.2, and the same 32 bytes are the array `cg_revision` of the emitted `cint-program.c`. A copy of the module with a blank line added before it keeps the same revision, while its sites move to line 3:\n\n```console\n$ mkdir moved\n$ { echo; cat add.ci; } > moved/add.ci\n$ cint-explain --root moved add.ci:add3\nmodule add.ci   revision bc1faa5409ed570368f6f2ed815f89623096edcce3fcde135d6a1db89a37a2f2\n\nfunction add3   add.sites:3   pure\n  signature  (in a: I64, in b: I64, in c: I64) -> I64\n  fault sites (2): 2 possible, 0 statically excluded\n    add3#1  add.ci:3:14  add.checked.i64  E_OVERFLOW possible\n    add3#2  add.ci:3:18  add.checked.i64  E_OVERFLOW possible\n...\n```\n\n**Notes**"
  },
  {
   "id": "spec-09p:revision-identity-p2",
   "edition": "SPEC-09P.1",
   "title": "6.5 Revision identity (part 3)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#revision-identity",
   "internal": 0,
   "content": "3. A blank line added to a module, or a function moved down, changes the source map but not the revision identity, so a checkpoint of a context that has not faulted still restores. Reordering two statements, or adding an operation that can fault, changes the site ordinals and so the revision identity.\n4. A checkpoint of a context that holds a fault keeps the position of its fault, and a restore maps that position back to a site by its line and column. After an edit that moves the faulting line, such a checkpoint is refused even though the revision identity has not changed."
  },
  {
   "id": "spec-09p:emitted-c-contract",
   "edition": "SPEC-09P.1",
   "title": "7 Emitted-C contract",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#emitted-c-contract",
   "internal": 0,
   "content": "## 7 Emitted-C contract\n\nThe compiler emits C17 that is defined for every input that reaches it: each check comes before the operation it guards, and the C compiler is given nothing it may treat as undefined. The emitted C calls the runtime for checked operations, fuel, call depth and fault records. This clause states what the emitted C and the runtime promise each other."
  },
  {
   "id": "spec-09p:the-output-set",
   "edition": "SPEC-09P.1",
   "title": "7.1 The output set",
   "clauses": "CINTC-06",
   "url": "/specifications/spec-09p/1/#the-output-set",
   "internal": 0,
   "content": "### 7.1 The output set\n\nThe compiler writes the files of a program as one set, which a reader sees complete or not at all.\n\n**Semantics**\n\n1. <a id=\"CINTC-06\"></a>The compiler performs no input or output. The bridge reads the files named in the build manifest, in manifest order and not by listing a directory, and passes each module's path relative to the source root, with `/` separators. Outputs are committed as one set [CINTC-06]:\n   1. All output files are written into a new sibling directory `<out>.stage-<N>`, where `N` is the first unused decimal integer, created exclusively. Each module's files are written as its `emit` call completes, and the program file after the last module. A diagnostic, a fault or a failed write in any module abandons that directory: the committed set stays as it was, byte for byte, and no new file is visible to a reader.\n   2. The bridge writes the file `MANIFEST` into that directory. Its first line is `cint-manifest-1`, and each following line is `<sha256> <bytes> <path>` for one output file, in byte order of path. The bridge flushes every file to stable storage.\n   3. The commit is one atomic replacement of the single file `<out>/MANIFEST.ref`, which holds the name of the new directory and the SHA-256 digest of its `MANIFEST`: `rename` on POSIX systems, and `MoveFileExW` with `MOVEFILE_REPLACE_EXISTING` and `MOVEFILE_WRITE_THROUGH` on Windows. These are the only platform calls of the bridge.\n   4. Readers trust only the files that the `MANIFEST` named by `MANIFEST.ref` lists, after checking each file's digest. Directories left by earlier builds are removed after a commit when possible; their presence does not change what a reader sees."
  },
  {
   "id": "spec-09p:the-output-set-p1",
   "edition": "SPEC-09P.1",
   "title": "7.1 The output set (part 2)",
   "clauses": "CINTC-12",
   "url": "/specifications/spec-09p/1/#the-output-set",
   "internal": 0,
   "content": "   A reader that runs while a build commits sees `MANIFEST.ref` name either the complete old set or the complete new one. No claim is made for single files, or for durability after a crash or a power loss, which depends on the file system.\n2. <a id=\"CINTC-12\"></a>A module-relative path is one or more segments separated by `/`. Each segment is made of ASCII letters, digits, `_`, `-` and `.`, and is not empty, `.` or `..`. A path has no leading `/`, no drive letter, no `\\` and no `:`. No segment names a Windows device (`CON`, `PRN`, `AUX`, `NUL`, `COM1` to `COM9`, `LPT1` to `LPT9`, in any case) before its first `.`, and no segment ends in `.`. All the paths of one build differ under ASCII case folding. With the final `.ci` removed, every segment is an identifier, so a dotted module name and its path correspond one to one. Any other path is the diagnostic C3030, naming the path and the rule it breaks. The bridge opens every file relative to the source root and refuses symbolic links and other reparse points [CINTC-12].\n\n**Examples**\n\n3. The build of `add.ci` from 6.2:\n\n```console\n$ cint emit-c --root . --out out add.ci\n$ ls out out.stage-0\nout:\nMANIFEST.ref\n\nout.stage-0:\nMANIFEST\nadd.c\nadd.sites\ncint-program.c\ncint-program.sites\n$ cat out/MANIFEST.ref\nout.stage-0 06d38f20f86a9e377eca47c7cd7eebc5c8fd7154ee06e93498ed881a63395424\n$ cat out.stage-0/MANIFEST\ncint-manifest-1\n1a4f0c8f856d921cbfa7f478970c9926c77ce455ee776711033781b195708d34 2358 add.c\nd83a256fcde82d46d7b00eaa2de7c6e491dc1ac747e3f4f10244d35b758887f5 634 add.sites\n2a7330a85849fd42f62eb7f4643131da96de92dc9f2cec08ffeb2a36285b141b 1318 cint-program.c\nce55c32dc70f577c08198ce999ba084cbbf8e0e291a2a4828d6933b052ca778d 16 cint-program.sites\n$ sha256sum out.stage-0/MANIFEST\n06d38f20f86a9e377eca47c7cd7eebc5c8fd7154ee06e93498ed881a63395424  out.stage-0/MANIFEST\n```"
  },
  {
   "id": "spec-09p:the-output-set-p2",
   "edition": "SPEC-09P.1",
   "title": "7.1 The output set (part 3)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-output-set",
   "internal": 0,
   "content": "`add.c` is the module's C, `add.sites` its SIR text, `cint-program.c` the program file that ties the modules together and holds the revision, and `cint-program.sites` the list of modules that the interpreter reads. The digest in `MANIFEST.ref` is the SHA-256 digest of `MANIFEST`, as an external tool computes it.\n\n**Notes**\n\n4. Microsoft does not document the replacement by `MoveFileExW` as atomic, so on Windows the property of paragraph 1, that a reader sees the complete old set or the complete new one, rests on a test that stops the bridge after each file and checks what a reader sees."
  },
  {
   "id": "spec-09p:language-level-and-headers",
   "edition": "SPEC-09P.1",
   "title": "7.2 Language level and headers",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#language-level-and-headers",
   "internal": 0,
   "content": "### 7.2 Language level and headers\n\n**Constraints**"
  },
  {
   "id": "spec-09p:language-level-and-headers-p1",
   "edition": "SPEC-09P.1",
   "title": "7.2 Language level and headers (part 2)",
   "clauses": "EMIT-01 EMIT-02 EMIT-24",
   "url": "/specifications/spec-09p/1/#language-level-and-headers",
   "internal": 0,
   "content": "1. <a id=\"EMIT-01\"></a><a id=\"RT-2\"></a>Emitted C is C17: GCC and Clang compile it with `-std=c17`, and MSVC with `/std:c17`. It includes only `<stdint.h>`, `<stddef.h>`, `<stdbool.h>`, `<string.h>`, `<limits.h>` and `cint_rt.h`. It does not include `<math.h>` or `<float.h>`, and it contains no `float`, `double` or `long double` token. The C sources of the runtime, the bridge, the harness, the `cint` command, the interpreter and the bootstrap compiler contain no floating-point type, literal or header either; `python3 tools/cint_lint.py` checks each of these sources for them [EMIT-01, RT-2].\n2. <a id=\"EMIT-02\"></a>Emitted C relies only on behavior that C17 defines for every input that reaches it, and on these properties of the C implementation, each checked when `cint_rt.h` is compiled: `CHAR_BIT` is 8 (a static assertion); `int8_t` to `int64_t` and `uint8_t` to `uint64_t` exist, which in C17 makes the signed exact-width types two's complement (an `#error` otherwise); `size_t` has at least 32 bits (a static assertion); and pointers have 64 bits, so the runtime supports 64-bit hosts only (a static assertion). External identifiers must be significant to at least 247 characters, which no source check can test; a generated symbol longer than 247 bytes is the diagnostic C9002 (7.7). No string literal of emitted C, after adjacent literals are joined, is longer than 4,095 characters, the minimum that C17 5.2.4.1 requires an implementation to accept: the literal text of a print statement reaches the runtime in pieces of at most 1,024 bytes, each written as adjacent literals of at most 64 bytes, and the PTX of a module's kernels is an array of literals, one per line [EMIT-02].\n3. <a id=\"EMIT-24\"></a>Emitted C is ASCII with LF line endings, a final LF, no trailing space, no tab and four-space indentation. Its first line is the comment `/* cint-core-1, cint-rt-3, emitted by cintc"
  },
  {
   "id": "spec-09p:checks-before-operations",
   "edition": "SPEC-09P.1",
   "title": "7.3 Checks before operations",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#checks-before-operations",
   "internal": 0,
   "content": "### 7.3 Checks before operations\n\nIn C, a signed overflow, a division by zero and a shift by the width of the type are undefined. Emitted C performs the check that cint requires before the operation, so the undefined case is never evaluated, and it computes the defined result with operations that C defines for all inputs.\n\n**Semantics**"
  },
  {
   "id": "spec-09p:checks-before-operations-p1",
   "edition": "SPEC-09P.1",
   "title": "7.3 Checks before operations (part 2)",
   "clauses": "EMIT-03 EMIT-04 EMIT-05 EMIT-07 EMIT-08 EMIT-09 EMIT-10",
   "url": "/specifications/spec-09p/1/#checks-before-operations",
   "internal": 0,
   "content": "1. <a id=\"EMIT-03\"></a><a id=\"RT-9\"></a>No emitted operation is evaluated when its C result would be undefined. Either the check comes first, or the operation is one that C defines for all inputs: unsigned arithmetic, or a checked builtin. Computing a signed result that overflows and testing it afterward is forbidden. Every helper of the runtime computes a defined C result before it reports any fault [EMIT-03, RT-9].\n2. <a id=\"EMIT-04\"></a><a id=\"EMIT-05\"></a><a id=\"RT-8\"></a><a id=\"RT-12\"></a>Emitted C performs a checked operation by calling a helper `bool cint_<op>_<t>(cint_ctx *ctx, cint_site site, ..., T *out)`, such as `cint_add_i64(ctx, site, a, b, &out)`. A helper writes `*out` and returns `true` when the exact result is in range. Otherwise it writes the full fault record into the context, if the context holds none yet, and returns `false` without writing `*out`. A wrapping helper that cannot fault takes no context; a wrapping left shift takes the context and the site, because it still faults `E_SHIFT` for a bad count. The checked add, subtract and multiply have two *helper modes*. With `CINT_RT_HELPERS_BUILTIN`, they use `__builtin_add_overflow`, `__builtin_sub_overflow` and `__builtin_mul_overflow` on GCC and Clang, and the intrinsics `_mul128` and `_umul128` for the multiply on MSVC for x64. With `CINT_RT_HELPERS_PORTABLE`, which `CINT_RT_PORTABLE=1` also selects, they use range tests in `int64_t` and `uint64_t` before the operation. Defining both macros is an `#error`. With neither defined, `cint_rt.h` selects the builtin mode on GCC and Clang and the portable mode elsewhere. The two modes give identical outcomes, and the conformance suite runs in both [EMIT-04, EMIT-05, RT-8, RT-12].\n3. <a id=\"EMIT-07\"></a>A wrapping operation (`+%`, `-%`, `*%`, `<<%`) is computed in the unsigned type of the same width, or in `uint64_t` for widths below 64, and the result "
  },
  {
   "id": "spec-09p:checks-before-operations-p2",
   "edition": "SPEC-09P.1",
   "title": "7.3 Checks before operations (part 3)",
   "clauses": "EMIT-11 EMIT-12",
   "url": "/specifications/spec-09p/1/#checks-before-operations",
   "internal": 0,
   "content": "| Case | Shift back | Outcome |\n| --- | --- | --- |\n| `I64` `1 << 62` | arithmetic: `2^62 >> 62` is 1 | 4611686018427387904 |\n| `I64` `1 << 63` | arithmetic: `MIN >> 63` is -1, not 1 | `E_OVERFLOW` |\n| `I64` `-1 << 63` | arithmetic: `MIN >> 63` is -1 | -9223372036854775808 |\n| `U64` `1 << 63` | logical: `2^63 >> 63` is 1 | 9223372036854775808 |\n| `I8` `64 << 1` | arithmetic at width 8: `-128 >> 1` is -64, not 64 | `E_OVERFLOW` |\n\n7. <a id=\"EMIT-11\"></a>A checked conversion `as` tests the source value against the range of the target before any conversion is evaluated, and the conversion is then exact. The test depends on the signedness of the two types [EMIT-11]:\n\n| Source | Target | Test |\n| --- | --- | --- |\n| signed | unsigned | a value below 0 faults; otherwise `(uint64_t)v` is compared with the target's maximum as `uint64_t` |\n| unsigned | signed | `v`, as `uint64_t`, is compared with the target's maximum converted to `uint64_t`; there is no lower test |\n| signed | signed | compared in `int64_t` with the target's minimum and maximum |\n| unsigned | unsigned | compared in `uint64_t` with the target's maximum |\n\n8. <a id=\"EMIT-12\"></a>A wide integer, `I128` to `I1024`, is emitted as a struct that holds an array of `uint64_t` limbs, least significant limb first. `__int128` and `_BitInt(N)` do not appear in any interface or stored layout. In the builtin helper mode, the runtime may compute a limb product with `unsigned __int128` on GCC and Clang, written with `__extension__` so that `-Wpedantic -Werror` accepts it, and with `_umul128` and `_udiv128` on MSVC for x64 [EMIT-12].\n\n**Examples**\n\n9. The shifts of the table, on both sides of the limit:\n\n```cint shifts.ci\nI64 one = 1;\nI64 neg = -1;\nU64 u = 1;\n\"{one << 62} {neg << 63} {u << 63}\\n\";\nI8 b = 64;\nI8 c = b << 1;\n```"
  },
  {
   "id": "spec-09p:checks-before-operations-p3",
   "edition": "SPEC-09P.1",
   "title": "7.3 Checks before operations (part 4)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#checks-before-operations",
   "internal": 0,
   "content": "```text\n4611686018427387904 -9223372036854775808 9223372036854775808\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> shifts.ci:6:10\n   |\n 6 | I8 c = b << 1;\n   |          ^ shl.checked.i8\n   |\n   = operation: shl.checked.i8\n   = operand-count: 2\n   = operand: I8 64\n   = operand: I64 1\n   = exact:   128\n   = limit:   I8 127\n...\n```\n\n10. A wrapping multiplication of `U16` values. In C, `uint16_t` operands are promoted to `int` and 65535 \u00d7 65535 overflows a 32-bit `int`, which is undefined. Emitted C multiplies in `uint64_t` and reduces the product modulo 2^16:\n\n```cint wrap16.ci\nU16 a = 65535;\nU16 p = a *% a;\n\"{p}\\n\";\n```\n\n```text\n1\n```\n\n11. Floor division, the remainder of (`MIN`, -1), and the quotient of the same pair:\n\n```cint divmin.ci\nI64 m = I64.min;\nI64 d = -1;\nI64 a = -7;\nI64 two = 2;\n\"{a / two} {a % two} {m % d}\\n\";\nI64 q = m / d;\n```\n\n```text\n-4 1 0\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> divmin.ci:6:11\n   |\n 6 | I64 q = m / d;\n   |           ^ div.checked.i64\n   |\n   = operation: div.checked.i64\n   = operand-count: 2\n   = operand: I64 -9223372036854775808\n   = operand: I64 -1\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n...\n```\n\n12. Checked conversions at the limits of the table of paragraph 7:\n\n```cint narrow.ci\nI64 a = -128;\nU64 b = 9223372036854775807;\nU8 c = 255;\n\"{a as I8} {b as I64}\\n\";\nI8 d = c as I8;\n```\n\n```text\n-128 9223372036854775807\nfault[E_NARROW]: the value does not fit the destination type\n  --> narrow.ci:5:10\n   |\n 5 | I8 d = c as I8;\n   |          ^ as.checked.u8.i8\n   |\n   = operation: as.checked.u8.i8\n   = operand-count: 1\n   = operand: U8 255\n   = exact:   255\n   = limit:   I8 127\n...\n```"
  },
  {
   "id": "spec-09p:memory",
   "edition": "SPEC-09P.1",
   "title": "7.4 Memory",
   "clauses": "EMIT-13 EMIT-14 EMIT-15",
   "url": "/specifications/spec-09p/1/#memory",
   "internal": 0,
   "content": "### 7.4 Memory\n\n**Semantics**\n\n1. <a id=\"EMIT-13\"></a>Index and slice checks are computed on integer offsets before any pointer is formed. No emitted expression forms a pointer outside an object or more than one element past its end [EMIT-13].\n2. <a id=\"EMIT-14\"></a>The bytes of a buffer are reinterpreted only with `memcpy` or through `unsigned char`. No pointer is cast between distinct object types, so the aliasing rules of C17 6.5 are neither relied on nor broken [EMIT-14].\n3. <a id=\"EMIT-15\"></a>Every scalar local is initialized where it is declared, and every array is zeroed where the language says it is. A wide temporary may be left uninitialized at its declaration when the node that defines it comes before every use on every path, which the emitter reads from the structured control flow of SIR [EMIT-15]."
  },
  {
   "id": "spec-09p:the-shape-of-the-code",
   "edition": "SPEC-09P.1",
   "title": "7.5 The shape of the code",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-shape-of-the-code",
   "internal": 0,
   "content": "### 7.5 The shape of the code\n\n**Semantics**"
  },
  {
   "id": "spec-09p:the-shape-of-the-code-p1",
   "edition": "SPEC-09P.1",
   "title": "7.5 The shape of the code (part 2)",
   "clauses": "EMIT-16 EMIT-17 EMIT-18",
   "url": "/specifications/spec-09p/1/#the-shape-of-the-code",
   "internal": 0,
   "content": "1. <a id=\"EMIT-16\"></a>Each SIR node becomes one C statement, with two exceptions: an index check that the emitter shows cannot fail becomes none, and a *counted loop* is emitted twice. A counted loop is a loop whose `I64` counter is compared by `<` with a bound that the loop does not change, is stepped once per iteration by a constant of at least 1, and whose body holds only loads, stores, element and field accesses, arithmetic, conversions, comparisons, built-ins and checks. Before it, one test enters a copy of the loop that charges no fuel per iteration, when the context holds no fault and the fuel left covers every iteration the counter allows; otherwise the loop runs as written. Each exit of the copy first sets the fuel consumed to the count the loop as written would have reached, so the outcome, fault record and fuel are those of the loop as written. No emitted C expression contains more than one operation that can fault or has a side effect, so C's unspecified order of evaluation of operands and arguments never matters [EMIT-16].\n2. <a id=\"EMIT-17\"></a>Scalar temporaries are C locals, such as `int64_t t3`, not slots in memory managed by the runtime [EMIT-17].\n3. <a id=\"EMIT-18\"></a>Faults do not use `setjmp`, `longjmp` or signals. A function emitted for a cint function follows the convention of the runtime's helpers [EMIT-18]:\n   - It returns `bool`: `true` on success, and `false` after the runtime has written the fault record. A function that returns a value writes it through a final `T *result` parameter, and only when it returns `true`.\n   - A checked operation calls a helper with a `cint_site`, the pair of the module's index in the program and the site ordinal. When the helper returns `false`, the function jumps to its single fault exit.\n   - A call of a cint function is preceded by `cint_rt_call_enter(ctx, site)`, which checks the depth limit, charges the "
  },
  {
   "id": "spec-09p:the-shape-of-the-code-p2",
   "edition": "SPEC-09P.1",
   "title": "7.5 The shape of the code (part 3)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-shape-of-the-code",
   "internal": 0,
   "content": "**Examples**\n\n4. The function `add3` of 6.2, as the compiler emits it in `add.c`. The two additions are sites 1 and 2 of module 0:\n\n```c\nstatic bool ci_3_add_4_add3(cint_ctx *ctx, int64_t v_a, int64_t v_b, int64_t v_c, int64_t *result)\n{\n    int64_t t0 = 0;\n    int64_t t1 = 0;\n    (void)ctx;\n    (void)v_a;\n    (void)v_b;\n    (void)v_c;\n    (void)result;\n    static const cint_site cs1 = {0u, 1u}; (void)cs1;\n    static const cint_site cs2 = {0u, 2u}; (void)cs2;\n    if (!cint_add_i64(ctx, cs1, v_a, v_b, &t0)) goto fault;\n    if (!cint_add_i64(ctx, cs2, t0, v_c, &t1)) goto fault;\n    *result = t1;\n    return true;\nfault:\n    return false;\n}\n```\n\nThe script calls it between `cint_rt_call_enter(ctx, cs4)` and `cint_rt_call_leave(ctx)`, and the program's entry, `cg_3_add_run`, begins with `cint_rt_entry_begin(ctx, (cint_site){0u, 3u}, fuel, CINT_DEPTH_FROM_CONFIG)`, which makes the entry's charge at site 3."
  },
  {
   "id": "spec-09p:independence-from-the-c-compiler-s-options",
   "edition": "SPEC-09P.1",
   "title": "7.6 Independence from the C compiler's options",
   "clauses": "EMIT-19 EMIT-20",
   "url": "/specifications/spec-09p/1/#independence-from-the-c-compiler-s-options",
   "internal": 0,
   "content": "### 7.6 Independence from the C compiler's options\n\n**Semantics**\n\n1. <a id=\"EMIT-19\"></a>The observable behavior of emitted C does not depend on the optimization level, on `-fwrapv`, `-ftrapv` or `-fno-strict-aliasing` or on MSVC's `/O1`, `/O2` or `/Od`, for a program that does not exhaust the C stack. The conformance suite runs at `-O0` and `-O2` (`/Od` and `/O2`) and requires identical outcomes [EMIT-19].\n2. <a id=\"EMIT-20\"></a>With GCC and Clang, the conformance suite also runs under `-fsanitize=undefined,address`, UndefinedBehaviorSanitizer and AddressSanitizer, and requires that they report nothing. A sanitized build is a conformance build only [EMIT-20].\n\n**Notes**\n\n3. The sanitized runs are evidence for 7.3 paragraph 1 over the programs run, not a proof for all programs (11.4)."
  },
  {
   "id": "spec-09p:deterministic-output",
   "edition": "SPEC-09P.1",
   "title": "7.7 Deterministic output",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#deterministic-output",
   "internal": 0,
   "content": "### 7.7 Deterministic output\n\n**Semantics**"
  },
  {
   "id": "spec-09p:deterministic-output-p1",
   "edition": "SPEC-09P.1",
   "title": "7.7 Deterministic output (part 2)",
   "clauses": "BACK-02 EMIT-21 EMIT-22 EMIT-25",
   "url": "/specifications/spec-09p/1/#deterministic-output",
   "internal": 0,
   "content": "1. <a id=\"EMIT-21\"></a>Emitted C is a function of these inputs only: the bytes of the declared input files and their module-relative paths, the compiler source identity, the language profile and the executor and its options. It contains no time, date, host name, user name, absolute path, environment value, random value or digest of the compiler's executable. The C toolchain that built the compiler is not an input [EMIT-21].\n2. <a id=\"EMIT-25\"></a>Emitting the same program twice, from different working directories, with different environment variables and on different hosts, gives byte-identical C [EMIT-25].\n3. <a id=\"BACK-02\"></a>Every file that an executor writes, PTX text included, follows paragraphs 1 and 2: LF line endings, stable numbering and no time or path [BACK-02].\n4. <a id=\"EMIT-22\"></a>Symbol names are built with an encoding that is injective, so two different names never give the same symbol, and self-delimiting, so a symbol splits back into its parts in one way only. A component `s` is encoded as `E(s)`: each byte in `[A-Za-z0-9]` is copied, and every other byte, `_` included, becomes `_x` and two uppercase hexadecimal digits. A component is written C(s), which is `_<L>_<E(s)>`, where `<L>` is the decimal length of `E(s)` in bytes. Every symbol encodes the module-relative path `P` without `.ci`, with `/` separators, never the dotted module name. There are four families: `ci` for user functions, `ci` + C(P) + C(name); `cg` for generated internal names, `cg` + C(P) followed by a generated name; `cx` for the public wrapper of an exported function, `cx` + C(P) + C(name); and `cm` for the public descriptor of a module, `cm` + C(P). The program file also exports `cint_program_abi`, `cint_observer_desc` and `cint_library_desc`. A symbol longer than 247 bytes is the diagnostic C9002, naming the symbol. A `cx` or `cm` symbol that contains `__` is the diagnostic C"
  },
  {
   "id": "spec-09p:deterministic-output-p2",
   "edition": "SPEC-09P.1",
   "title": "7.7 Deterministic output (part 3)",
   "clauses": "EMIT-23",
   "url": "/specifications/spec-09p/1/#deterministic-output",
   "internal": 0,
   "content": "| Module | Name | Symbol |\n| --- | --- | --- |\n| `add` | `add3` | `ci_3_add_4_add3` |\n| `ab` | `x_c_d` | `ci_2_ab_11_x_x5Fc_x5Fd` |\n| `ab_c` | `x_d` | `ci_7_ab_x5Fc_6_x_x5Fd` |\n| `arith/add` | `f` | `ci_12_arith_x2Fadd_1_f` |\n| `add` | `add3`, public wrapper | `cx_3_add_4_add3` |\n| `a/b_c` | `f`, public wrapper | `cx_11_a_x2Fb_x5Fc_1_f` |\n| `a_b/c` | `f`, public wrapper | `cx_11_a_x5Fb_x2Fc_1_f` |\n\n5. <a id=\"EMIT-23\"></a><a id=\"RT-6\"></a><a id=\"RT-7\"></a>Sites are numbered from 1 in each module, in SIR node order, and 0 means no site. A site is the pair `cint_site { uint32_t module; uint32_t index; }`. The C of each module holds one constant site table, whose row `k` gives the line, column and operation identifier of site `k`, and one module descriptor that holds the module-relative path and the table. A helper that faults receives the site and resolves it into the record's position and operation; emitted code does not format a position itself. No hash-table order or address enters the numbering, so two compilations of one program give identical site tables [EMIT-23, RT-6, RT-7].\n\n**Examples**\n\n6. The same program emitted from two directories, with different time zones, locales and `SOURCE_DATE_EPOCH`:\n\n```console\n$ mkdir a b\n$ cp add.ci a/ && cp add.ci b/\n$ (cd a && TZ=UTC LANG=C cint emit-c --root . --out out add.ci)\n$ (cd b && TZ=Asia/Tokyo LANG=C.UTF-8 SOURCE_DATE_EPOCH=1 cint emit-c --root . --out out add.ci)\n$ diff -r a/out.stage-0 b/out.stage-0 && echo identical\nidentical\n```"
  },
  {
   "id": "spec-09p:warnings",
   "edition": "SPEC-09P.1",
   "title": "7.8 Warnings",
   "clauses": "EMIT-26",
   "url": "/specifications/spec-09p/1/#warnings",
   "internal": 0,
   "content": "### 7.8 Warnings\n\n**Constraints**\n\n1. <a id=\"EMIT-26\"></a>Emitted C, `cint_rt.h`, the `cint_rt` library, the bridge, the harness and the bootstrap compiler compile with no warning under these flags [EMIT-26]:\n\n| Toolchain | Flags |\n| --- | --- |\n| GCC | `-std=c17 -Wall -Wextra -Wconversion -Wsign-conversion -Wshadow -Wpedantic -Werror` |\n| Clang | the GCC flags and `-Wimplicit-int-conversion` |\n| MSVC | `/std:c17 /W4 /WX` |"
  },
  {
   "id": "spec-09p:symbol-audit",
   "edition": "SPEC-09P.1",
   "title": "7.9 Symbol audit",
   "clauses": "EMIT-31",
   "url": "/specifications/spec-09p/1/#symbol-audit",
   "internal": 0,
   "content": "### 7.9 Symbol audit\n\n**Constraints**\n\n1. <a id=\"EMIT-31\"></a>Every generated object is audited at both optimization levels of the conformance suite. The audit fails on an exported symbol other than the `cx_` and `cm_` symbols, `cint_library_desc`, `cint_program_abi` and `cint_observer_desc`; on an external definition that is not exported, other than the `ci_` and `cg_` symbols of the program's own modules; and on any undefined symbol outside this list [EMIT-31]:\n\n| Class | Symbols | Reason |\n| --- | --- | --- |\n| Runtime | `cint_rt_` and the other `cint_` functions of `rt/cint_rt.h` | the runtime contract |\n| Same build | `ci_` and `cg_` symbols of another module, or of the program file, of the same build | imports and site tables |\n| C support | `memcpy`, `memset`, `memmove`, `memcmp` | emitted by 7.4, and inserted by GCC, Clang and MSVC for large copies and zeroing |\n| MSVC x64 and ARM64 | `__chkstk`, `__security_cookie`, `__security_check_cookie`, `__GSHandlerCheck`, `__report_rangecheckfailure`, `__isa_available` | stack probes for frames over one page; the `/GS` checks, the MSVC default; the CPU feature level that code built with `/O2` reads |\n| GCC and Clang | `__stack_chk_fail`, `__stack_chk_guard` | `-fstack-protector-strong` |\n| Apple Clang, macOS | `__chkstk_darwin`, `___chkstk_darwin`, `bzero` | the stack probe on AArch64 and x86-64; the zeroing of a large local array at `-O0` |\n\n   A row for a target applies to that target only. A library build (`cint build --lib`) also exports the host functions of the runtime, which carry `CINT_RT_EXPORT` in such a build, and the audit of its export table admits exactly those. The list may shrink when a build removes the stack protector with `-fno-stack-protector` or `/GS-`; such a build records the flag in its receipt."
  },
  {
   "id": "spec-09p:the-runtime-contract",
   "edition": "SPEC-09P.1",
   "title": "7.10 The runtime contract",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-runtime-contract",
   "internal": 0,
   "content": "### 7.10 The runtime contract\n\nThe runtime is the header `rt/cint_rt.h` and the library `cint_rt`. The header is the normative statement of the contract; this subclause explains it.\n\n**Semantics**"
  },
  {
   "id": "spec-09p:the-runtime-contract-p1",
   "edition": "SPEC-09P.1",
   "title": "7.10 The runtime contract (part 2)",
   "clauses": "RCPT-08",
   "url": "/specifications/spec-09p/1/#the-runtime-contract",
   "internal": 0,
   "content": "1. <a id=\"RCPT-08\"></a>The *runtime contract version* is a string `cint-rt-<N>` that names the interface and meaning of `cint_rt.h` and the `cint_rt` library on which emitted code depends: the names and signatures of the helpers, the layout of the fault record and the layout of the site table. It changes when any of these changes incompatibly, and it is an input of the revision identity (6.5). In cint 0.2.0 it is `cint-rt-3`, and the header defines the interface version `CINT_ABI_VERSION` as `0x00030002`. A checkpoint binds to the revision identity; the compiler source identity is recorded beside it for identification only, so a new compiler that leaves the SIR and the runtime contract unchanged does not invalidate checkpoints [RCPT-08].\n2. <a id=\"RT-3\"></a>Every symbol that the runtime exports is in the `cint_` namespace. The helpers are `static inline` and add no undefined symbol to a generated object [RT-3].\n3. <a id=\"RT-4\"></a>A context, `cint_ctx`, is an opaque object that holds one instance of a program's state from its creation to its destruction. Emitted code passes the pointer to helpers and does not read its fields. For each entry it holds the fuel budget and the fuel consumed, the depth limit and the current depth, and the stack of call sites. Across entries it holds module state, registered buffers, arenas and the fault record [RT-4].\n4. <a id=\"RT-10\"></a>Faults are sticky. The first fault of an entry writes the fault record once. A later helper call on a context that holds a fault returns `false` and changes nothing. Emitted code tests every helper result and leaves through the function's single fault exit. Only the host clears the record, with `cint_ctx_clear_fault`, which changes no other state [RT-10].\n5. <a id=\"RT-11\"></a>A call checks the depth limit first, faulting `E_DEPTH` without a fuel charge, then charges one unit of fuel, then records its call"
  },
  {
   "id": "spec-09p:the-runtime-contract-p2",
   "edition": "SPEC-09P.1",
   "title": "7.10 The runtime contract (part 3)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-runtime-contract",
   "internal": 0,
   "content": "**Notes**\n\n8. The status values of `rt/cint_rt.h` are `CINT_OK` (0), `CINT_FAULT` (1), `CINT_REFUSED` (2), `CINT_BUSY` (3), `CINT_FAULTED` (4) and `CINT_RESOURCE` (5). SPEC-03P.1 specifies what each means to a host program."
  },
  {
   "id": "spec-09p:agreement",
   "edition": "SPEC-09P.1",
   "title": "8 Agreement",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#agreement",
   "internal": 0,
   "content": "## 8 Agreement\n\nTwo implementations of cint agree on a program when every observable part of its outcome is the same. This clause says what is compared, what is not, and how a case that is not compared is reported, so that a refusal is never counted as agreement."
  },
  {
   "id": "spec-09p:what-is-compared",
   "edition": "SPEC-09P.1",
   "title": "8.1 What is compared",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#what-is-compared",
   "internal": 0,
   "content": "### 8.1 What is compared\n\n**Semantics**"
  },
  {
   "id": "spec-09p:what-is-compared-p1",
   "edition": "SPEC-09P.1",
   "title": "8.1 What is compared (part 2)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#what-is-compared",
   "internal": 0,
   "content": "1. <a id=\"REF-06\"></a>A program is in the scope of both the reference and a compiler when the reference runs it and the compiler builds it without a diagnostic whose code begins with `C9`. For such a program and the same semantic inputs, the two agree as a conformance case does: the same bytes on standard output; the same kind of outcome; the same returned value; the same fuel consumed; and the same fault record in every field except the revision and the source-map digest, which the reference does not compute. For a program that both reject, they agree when they report the same diagnostic code at the same position. A disagreement is a defect of one of them or an ambiguity in the text; it is not settled by choosing one. The program, reduced to a case, joins the suite. Agreement on one program is a measurement of that program and shows nothing about another [REF-06].\n2. <a id=\"DIAG-01\"></a>A position, in a diagnostic, a fault record, SIR text or an `.expect` file, is written `<path>:<line>:<column>`. `<path>` is the module-relative path, `.ci` included, with `/` separators. Lines count from 1. Columns count from 1 in Unicode scalar values, not bytes [DIAG-01].\n3. <a id=\"DIAG-02\"></a>Codes have two separate sets of names. A fault code is one of the `E_` names of SPEC-04P.2 5.2.3. A diagnostic code is `C` and four digits, listed in Annex B of SPEC-04P.2. A constant expression whose evaluation meets a fault condition is the diagnostic C6001, which carries the fault code, and C6002 when it runs out of compile-time fuel. A diagnostic that reports a limit of an implementation has a code that begins with `C9`: C9001 for a capacity or an output size, C9002 for a generated symbol longer than 247 bytes, C9003 for a local array over the frame limit, and C9004 for nesting beyond the implementation's limit [DIAG-02].\n4. These are not compared: the message text of a diagnostic, the r"
  },
  {
   "id": "spec-09p:what-is-compared-p2",
   "edition": "SPEC-09P.1",
   "title": "8.1 What is compared (part 3)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#what-is-compared",
   "internal": 0,
   "content": "**Examples**\n\n5. The `+` below is the sixth Unicode scalar value of its line and the seventh byte, because `\u00e9` takes two bytes in UTF-8:\n\n```cint column.ci\nI8 a = 100;\n\"\u00e9{a + a}\\n\";\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> column.ci:2:6\n...\n```"
  },
  {
   "id": "spec-09p:categories-of-a-case",
   "edition": "SPEC-09P.1",
   "title": "8.2 Categories of a case",
   "clauses": "CONF-14",
   "url": "/specifications/spec-09p/1/#categories-of-a-case",
   "internal": 0,
   "content": "### 8.2 Categories of a case\n\n**Semantics**\n\n1. <a id=\"CONF-14\"></a>A conformance run reports each case in exactly one category. The category depends only on the case, its frozen expectation and the compiler under test, not on the C toolchain, so it belongs in the outcome part of the receipt [CONF-14]:\n   1. *Compared.* The implementation produced an outcome and it was compared with the frozen expectation. An expected diagnostic is compared too: the frozen outcome is a compile error, and the compiler reports the same code at the same position.\n   2. *Unsupported by this implementation.* The frozen outcome is a value, a fault or a compile error with another code or position; the compiler reports a `C9` code under a documented limit; and the file `conformance/unsupported.txt` lists that case, compiler, code and limit. For `gpu-cuda`, the refusal `E_UNSUPPORTED` of 5.5 takes the place of the `C9` code. An unsupported case is a named gap, not agreement.\n   3. *Held.* The file `conformance/held.txt` lists the case, which has no frozen expectation.\n   4. *Outside the subset.* The compiler under test accepts only a subset of the language (10.2), the case is outside it and the compiler reports the diagnostic for that. \n   5. *Not applicable.* An operation fixture whose operation has no operator form in the subset that the compiler accepts, so that no program exists for it."
  },
  {
   "id": "spec-09p:categories-of-a-case-p1",
   "edition": "SPEC-09P.1",
   "title": "8.2 Categories of a case (part 2)",
   "clauses": "BACK-05 SEED-15",
   "url": "/specifications/spec-09p/1/#categories-of-a-case",
   "internal": 0,
   "content": "   Any other result is a disagreement: a `C9` code that `conformance/unsupported.txt` does not list, a refusal by a subset compiler of a case inside its subset, or a compile error whose code or position differs from the frozen expectation. A case that the list names as unsupported and that the compiler accepts is also a disagreement, until the list is corrected.\n2. Each line of `conformance/unsupported.txt` is `<case> <compiler> <code> <limit> <reason>`. For `gpu-cuda` the compiler is `cintc/gpu-cuda`, the code is `E_UNSUPPORTED`, and the limit is `BACK-05 capability <name>`, where `<name>` is the capability that the refusal names; a refusal that names another capability is a disagreement. For example, the line `control/nest_blocks_200 cint-seed C9004 SEED-15 the seed compiles at most 199 nested blocks` lists a case that the seed refuses under its nesting limit (10.2, paragraph 8)."
  },
  {
   "id": "spec-09p:disagreement",
   "edition": "SPEC-09P.1",
   "title": "8.3 Disagreement",
   "clauses": "CONF-04",
   "url": "/specifications/spec-09p/1/#disagreement",
   "internal": 0,
   "content": "### 8.3 Disagreement\n\n**Semantics**\n\n1. <a id=\"CONF-04\"></a>Any disagreement fails the run. A disagreement between the reference and a hand-derived anchor expectation is a defect of the reference, and it also fails the run until the reference is fixed or the expectation is corrected by an erratum (9.5) [CONF-04]."
  },
  {
   "id": "spec-09p:the-run-matrix",
   "edition": "SPEC-09P.1",
   "title": "8.4 The run matrix",
   "clauses": "CONF-03",
   "url": "/specifications/spec-09p/1/#the-run-matrix",
   "internal": 0,
   "content": "### 8.4 The run matrix\n\n**Semantics**\n\n1. <a id=\"CONF-03\"></a>A conformance run executes every case on the reference and on every build in this matrix, and requires identical canonical outcomes across all of them [CONF-03]:\n\n| Axis | Values |\n| --- | --- |\n| C toolchain | GCC on Linux x86-64; Clang on Linux x86-64 and Apple Clang on macOS AArch64; MSVC on Windows x86-64 |\n| Optimization | `-O0` and `-O2` (`/Od` and `/O2`) |\n| Helper mode | `CINT_RT_HELPERS_BUILTIN` and `CINT_RT_HELPERS_PORTABLE` |\n| Compiler | the `cintc` built by the bootstrap (10.3), and the bootstrap compiler on the cases of its subset (10.2) |\n| Executor | `cpu-c17` on every case; `cpu-sir-interp` on every case; `gpu-cuda` on the cases its capability table supports, the others producing `E_UNSUPPORTED` at translation |"
  },
  {
   "id": "spec-09p:parallel-executors",
   "edition": "SPEC-09P.1",
   "title": "8.5 Parallel executors",
   "clauses": "BACK-09 BACK-10 BACK-12",
   "url": "/specifications/spec-09p/1/#parallel-executors",
   "internal": 0,
   "content": "### 8.5 Parallel executors\n\nAn executor may run the work-items of a dispatch in parallel, but its outcome is the one of running them one at a time in canonical order.\n\n**Semantics**\n\n1. <a id=\"BACK-09\"></a>The canonical outcome of a dispatch, fuel included, is the outcome of running its work-items one at a time in canonical order, as `cpu-c17` does. The dispatch first charges `N`, the number of its work-items. A parallel executor computes the outcome as follows, where `F` is the fuel left when the first work-item starts, `c(i, s)` is the fuel that item `i` has charged through its step `s`, and `C(i)` is the total charge of item `i` when it runs to its end or to its first fault other than `E_FUEL` [BACK-09]:\n   - `k_fault` is the least item with a fault other than `E_FUEL`, and `s_fault` the step of that fault.\n   - `k_fuel` is the least item `i` with a charge point `s` such that `C(0) + ... + C(i - 1) + c(i, s) > F`, and `s_fuel` is the first such `s`. Without a budget there is no `k_fuel`.\n   - The canonical fault is the lesser of (`k_fault`, `s_fault`) and (`k_fuel`, `s_fuel`) in work-item, then step, order; the second is `E_FUEL`.\n   - The fuel consumed by the dispatch is `N` plus the charges of items 0 to `k - 1` plus the charges of item `k` before its faulting step, where `k` is the item of the canonical fault; a charge that faults `E_FUEL` is not consumed. Without a fault it is `N` plus the sum of all `C(i)`.\n\n   Which work-item failed first on the hardware cannot be observed.\n2. <a id=\"BACK-10\"></a>The outputs of a dispatch that faults are not published [BACK-10].\n3. <a id=\"BACK-12\"></a>Running a work-item again to find or describe the canonical fault charges no fuel. The canonical fuel is computed once, by paragraph 1 [BACK-12].\n\n**Examples**"
  },
  {
   "id": "spec-09p:parallel-executors-p1",
   "edition": "SPEC-09P.1",
   "title": "8.5 Parallel executors (part 2)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#parallel-executors",
   "internal": 0,
   "content": "4. A dispatch of 1,000 work-items, each of which charges 10 units in its loop. Item 900 overflows on its second iteration:\n\n```console\n$ cat dispatch_fuel.ci\nkernel tenfold[n](in I64[n] a, out I64[n] b) over [i: n] {\n    I64 s = 0;\n    for j in 0..10 {\n        s += a[i];\n    }\n    b[i] = s;\n}\n\nexport I64 run() {\n    I64[1000] a;\n    I64[1000] b;\n    a[900] = I64.max;\n    tenfold(a, b);\n    return b[0];\n}\n$ python3 -m cint_ref run dispatch_fuel.ci --entry run --format 4\n...\nfuel-consumed 10003\nfault.code E_OVERFLOW\nfault.operation add.checked.i64\n...\nfault.kernel dispatch_fuel.tenfold\nfault.address 0 900 3\n...\n$ python3 -m cint_ref run dispatch_fuel.ci --entry run --format 4 --fuel 6001\n...\nfuel-consumed 6001\nfault.code E_FUEL\nfault.operation fuel.charge\nfault.exact none\nfault.limit I64 6001\nfault.position dispatch_fuel.ci:3:5\n...\nfault.kernel dispatch_fuel.tenfold\nfault.address 0 500 0\n...\n```\n\nWithout a budget, the entry consumes 1 unit, the dispatch 1,000, items 0 to 899 10 each, and item 900 2 before its overflow: 10,003. With a budget of 6,001, `F` is 5,000 after the entry's unit and the dispatch's 1,000, items 0 to 499 consume it, and the first charge of item 500 faults `E_FUEL`. The overflow at item 900 is not reported, because item 500 comes first. The address is the dispatch, the work-item and the step."
  },
  {
   "id": "spec-09p:the-conformance-suite",
   "edition": "SPEC-09P.1",
   "title": "9 The conformance suite",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-conformance-suite",
   "internal": 0,
   "content": "## 9 The conformance suite\n\nThe conformance suite, in `conformance/`, holds the cases on which every implementation must agree, with their expected outcomes. Most expectations come from the reference, and the boundary cases are derived by hand."
  },
  {
   "id": "spec-09p:case-files",
   "edition": "SPEC-09P.1",
   "title": "9.1 Case files",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#case-files",
   "internal": 0,
   "content": "### 9.1 Case files\n\n**Semantics**"
  },
  {
   "id": "spec-09p:case-files-p1",
   "edition": "SPEC-09P.1",
   "title": "9.1 Case files (part 2)",
   "clauses": "CONF-01 CONF-02",
   "url": "/specifications/spec-09p/1/#case-files",
   "internal": 0,
   "content": "1. <a id=\"CONF-01\"></a>There are two kinds of case, with one rule of agreement (8.1). An *operation fixture* is one operation on given operands, in a CIF-1 file under `conformance/integer-machine/`, one JSON object per line. A *program case* is a `.ci` file and its `.expect` file, for whole programs: control flow, views, kernels, diagnostics and fuel. Each operation fixture is also run through generated *table programs*, `conformance/tables/<name>.ci` with the list of calls `<name>.cases`, so both kinds run on every implementation. A program case begins with a header comment of lines `// case: <name>`, `// clause: <rules>` and `// entry: <entries>; args: <arguments>[; fuel <n>][; depth <n>]`; without an `entry` line, the case runs its script, else its function `main`, else its only test. A case with several entries has one file `<case>.<entry>.expect` for each. The `.expect` file is canonical text in the grammar of 9.3 [CONF-01].\n2. <a id=\"CONF-02\"></a>An expectation comes from one of three sources, which its `source` line states: `anchor`, derived by hand, with the derivation written beside it, and used for boundary cases and to check the reference itself; `reference`, written by the reference with `conformance/tools/gen_expect.py` and then frozen; or `compile-error`, the expected diagnostic code and position. A frozen expectation is not edited in place. It changes in one of three ways [CONF-02]:\n   - A change of meaning (a value, a fault code or content, a fuel count or a diagnostic code or position) comes with a new language profile, which has its own frozen expectations. A change of encoding with the same content comes with a new version of that encoding: a new domain string, a new runtime contract version (7.10) or a new `.expect` format (9.3). Frozen files of the old version stay valid and are read in their own format.\n   - A `reference` expectation found wrong "
  },
  {
   "id": "spec-09p:operation-fixtures-and-coverage",
   "edition": "SPEC-09P.1",
   "title": "9.2 Operation fixtures and coverage",
   "clauses": "CONF-08",
   "url": "/specifications/spec-09p/1/#operation-fixtures-and-coverage",
   "internal": 0,
   "content": "### 9.2 Operation fixtures and coverage\n\n**Semantics**\n\n1. A CIF-1 line is one JSON object with the keys `id`, `status`, `op`, `args` and `expect`, in that order. `op` is an operation identifier, `args` a list of typed values `{\"t\": <type>, \"v\": <decimal>}`, and `expect` holds either a `value` or a `fault` with its code and, where the record has them, its exact result and limit. Every integer is a JSON string of decimal digits, so no JSON reader loses precision. A hand-derived anchor adds a key `derivation` that shows the arithmetic.\n2. The suite holds these fixtures: `anchors.cif1.jsonl`, the anchors; `exh8/`, every operand pair of the 14 binary operator forms (`+ - * / % << >> +% -% *% <<% +| -| *|`) on `I8` and `U8`, 1,835,008 records; `bnd64/`, the `I64` boundary matrix of the 16 values `MIN`, `MIN + 1`, -2^32, -2^31, -2, -1, 0, 1, 2, 2^31 - 1, 2^31, 2^32, 3037000499, 3037000500, `MAX - 1` and `MAX` for each form (3037000499 and 3037000500 bracket the square root of 2^63); and `bnd128/` to `bnd1024/`, the boundary matrices of the wide types.\n3. <a id=\"CONF-08\"></a>Every implementation that evaluates constants is also run on the *constant and run-time category*: each boundary-matrix and exhaustive 8-bit expression is evaluated as a constant expression and at run time from variables, and the two must give the same value, or the same fault code, operation and operands, which the constant program reports as the diagnostic C6001. If the front end folded `I8` `100 +| 100` to anything other than 127, the two programs would disagree [CONF-08].\n\n**Examples**\n\n4. The reference checks the anchors against their hand-derived values:\n\n```console\n$ python3 -m cint_ref cif1 conformance/integer-machine/anchors.cif1.jsonl\ncif1: 300 records, 300 agree, 0 disagree, 0 unsupported, 0 invalid\n```"
  },
  {
   "id": "spec-09p:the-expect-format",
   "edition": "SPEC-09P.1",
   "title": "9.3 The `.expect` format",
   "clauses": "CONF-11",
   "url": "/specifications/spec-09p/1/#the-expect-format",
   "internal": 0,
   "content": "### 9.3 The `.expect` format\n\nThe `.expect` format is the canonical text of an outcome: one field per line, in a fixed order, with every integer in exact decimal.\n\n**Syntax**\n\n1. <a id=\"CONF-11\"></a>An `.expect` file is the text that this grammar derives. The notation is ABNF (RFC 5234) with the case-sensitive strings `%s\"...\"` of RFC 7405; `ALPHA`, `DIGIT`, `SP`, `LF` and `VCHAR` are the core rules of RFC 5234. A file whose third line is `format 2`, `format 3`, `format 4` or `format 5` is a file of that format. A file without that line is a format 1 file, stays valid and is compared in format 1. Keys appear in this order: `case`, `clause`, `format`, `source`, `outcome`, `stdout-bytes`, `stdout-sha256`, `return`, `fuel-consumed`, the `error.` keys, the `fault.` keys, the `diagnostic.` keys, `refused.reason` and `state.global` [CONF-11].\n\n```abnf\nexpect-file      = case-line clause-line [ format-line ]\n                   ( run-case / compile-case / refused-case )\nformat-line      = %s\"format 2\" LF                   ; absent: format 1\n\ncase-line        = %s\"case\" SP case-name LF\ncase-name        = segment *( \"/\" segment )\nsegment          = 1*( ALPHA / DIGIT / \"_\" / \"-\" / \".\" )\nclause-line      = %s\"clause\" SP text LF\ntext             = VCHAR *( *SP VCHAR )            ; printable ASCII, no edge space"
  },
  {
   "id": "spec-09p:the-expect-format-p1",
   "edition": "SPEC-09P.1",
   "title": "9.3 The `.expect` format (part 2)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-expect-format",
   "internal": 0,
   "content": "run-case         = %s\"source\" SP ( %s\"anchor\" / %s\"reference\" ) LF\n                   ( value-body / fault-body ) *state-line   ; state-line: format 2\nstate-line       = %s\"state.global\" SP module-name SP name SP typed-value LF\nvalue-body       = %s\"outcome value\" LF output-lines [ return-line ] fuel-line\nfault-body       = %s\"outcome fault\" LF output-lines fuel-line fault-record\noutput-lines     = %s\"stdout-bytes\" SP count LF\n                   [ %s\"stdout-sha256\" SP 64lhex LF ]\nreturn-line      = %s\"return\" SP typed-value LF\nfuel-line        = %s\"fuel-consumed\" SP count LF\nfault-record     = %s\"fault.code\" SP fault-code LF\n                   %s\"fault.operation\" SP op-id LF\n                   *( %s\"fault.operand\" SP typed-value LF )\n                   %s\"fault.exact\" SP ( int / %s\"none\" ) LF\n                   %s\"fault.limit\" SP ( typed-value / %s\"none\" ) LF\n                   %s\"fault.position\" SP position LF\n                   %s\"fault.revision self\" LF\n                   [ %s\"fault.source-map self\" LF ]      ; format 2\n                   %s\"fault.address\" SP ( %s\"none\" / address ) LF\n                   %s\"fault.stack-depth\" SP count LF\n                   *( %s\"fault.stack\" SP position LF )   ; format 2\n\ncompile-case     = %s\"source compile-error\" LF %s\"outcome compile-error\" LF\n                   %s\"diagnostic.code\" SP c-code LF\n                   %s\"diagnostic.position\" SP position LF\n                   [ diagnostic-fault ]\ndiagnostic-fault = %s\"diagnostic.fault.code\" SP fault-code LF\n                   %s\"diagnostic.fault.operation\" SP op-id LF\n                   *( %s\"diagnostic.fault.operand\" SP typed-value LF )\n                   %s\"diagnostic.fault.exact\" SP ( int / %s\"none\" ) LF\n                   %s\"diagnostic.fault.limit\" SP ( typed-value / %s\"none\" ) LF"
  },
  {
   "id": "spec-09p:the-expect-format-p2",
   "edition": "SPEC-09P.1",
   "title": "9.3 The `.expect` format (part 3)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-expect-format",
   "internal": 0,
   "content": "refused-case     = %s\"source reference\" LF %s\"outcome refused\" LF\n                   %s\"refused.reason\" SP text LF\n\ntyped-value      = int-type SP int / %s\"Bool\" SP ( %s\"true\" / %s\"false\" )\n                   / %s\"Z\" SP int\nint-type         = %s\"I\" ( \"8\" / \"16\" / \"32\" / \"64\" / \"128\" / \"256\" / \"512\" / \"1024\" )\n                   / %s\"U\" ( \"8\" / \"16\" / \"32\" / \"64\" )\nfault-code       = %s\"E_\" 1*( %x41-5A / \"_\" )\nop-id            = 1*( %x61-7A / DIGIT / \"_\" / \".\" )\nc-code           = %s\"C\" 4DIGIT\nposition         = segment *( \"/\" segment ) \":\" pos-int \":\" pos-int\naddress          = count SP count SP count         ; dispatch, work-item, step\nint              = [ \"-\" ] count\ncount            = \"0\" / %x31-39 *DIGIT\npos-int          = %x31-39 *DIGIT\nlhex             = DIGIT / %x61-66                 ; lowercase hexadecimal digit\nmodule-name      = name *( \".\" name )\nname             = ( ALPHA / \"_\" ) *( ALPHA / DIGIT / \"_\" )\n```\n\n2. Format 3 adds the outcome `error`, for an entry that returns an error, by incremental alternatives (`=/`), so the rules above are unchanged:\n\n```abnf\nformat-line      =/ %s\"format 3\" LF\nrun-case         =/ %s\"source\" SP ( %s\"anchor\" / %s\"reference\" ) LF\n                    error-body *state-line\nerror-body       = %s\"outcome error\" LF output-lines fuel-line error-value\nerror-value      = %s\"error.set\" SP [ module-name \".\" ] name LF\n                   %s\"error.value\" SP [ name \".\" ] name LF\n                   %s\"error.tag\" SP uint-type SP pos-int LF\nuint-type        = %s\"U\" ( \"8\" / \"16\" / \"32\" / \"64\" )\n```\n\n3. Format 4 adds the fault record of a kernel dispatch:"
  },
  {
   "id": "spec-09p:the-expect-format-p3",
   "edition": "SPEC-09P.1",
   "title": "9.3 The `.expect` format (part 4)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-expect-format",
   "internal": 0,
   "content": "```abnf\nformat-line      =/ %s\"format 4\" LF\nfault-record     =/ %s\"fault.code\" SP fault-code LF\n                    %s\"fault.operation\" SP op-id LF\n                    *( %s\"fault.operand\" SP typed-value LF )\n                    *( %s\"fault.descriptor\" SP descriptor LF )\n                    %s\"fault.exact\" SP ( int / %s\"none\" ) LF\n                    %s\"fault.limit\" SP ( typed-value / %s\"none\" ) LF\n                    %s\"fault.position\" SP position LF\n                    %s\"fault.revision self\" LF\n                    %s\"fault.source-map self\" LF\n                    %s\"fault.phase\" SP phase LF\n                    %s\"fault.kernel\" SP kernel-name LF\n                    %s\"fault.address\" SP kernel-address LF\n                    %s\"fault.stack-depth\" SP count LF\n                    *( %s\"fault.stack\" SP position LF )\nkernel-address   = count SP ( count SP count / %s\"none none\" )\n                                                   ; dispatch, then work-item and step\nphase            = %s\"entry\" / %s\"work-item\" / %s\"epilogue\"\nkernel-name      = module-name \".\" name\ndescriptor       = elem-type SP ( count SP count / %s\"none\" ) SP count SP int\n                   1*( SP count SP int SP int ) SP ( %s\"read\" / %s\"write\" )\nelem-type        = int-type\n```\n\n4. Format 5 adds fixed-point values, the unsigned wide types and fixed-point element types:\n\n```abnf\nformat-line      =/ %s\"format 5\" LF\ntyped-value      =/ q-type SP %s\"raw\" SP int\nint-type         =/ %s\"U\" ( \"128\" / \"256\" / \"512\" )\nelem-type        =/ q-type\nq-type           = %s\"Q\" pos-int \".\" count          ; i + f is 8, 16, 32 or 64\n```\n\n**Constraints**"
  },
  {
   "id": "spec-09p:the-expect-format-p4",
   "edition": "SPEC-09P.1",
   "title": "9.3 The `.expect` format (part 5)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-expect-format",
   "internal": 0,
   "content": "5. These rules hold in addition to the grammar:\n   1. The file is ASCII with an LF after every line, the last included. It contains no CR, no tab and no trailing space.\n   2. `stdout-sha256` is present exactly when `stdout-bytes` is not 0, and is the SHA-256 digest of the output bytes.\n   3. `return` is present exactly when the entry returns a value. A `void` function, a test block and a script have no `return` line.\n   4. There is one `fault.operand` line for each operand of the record, in the record's order. `fault.exact` and `fault.limit` are `none` when the record has no such field.\n   5. `fault.revision self` means that the record's revision must equal the revision identity of the program under test, and `fault.source-map self` the same for the source-map digest; both are compared only between builds of `cintc`. `fault.address` gives the dispatch, the work-item as one linear index and the step. `fault.stack-depth` is the number of positions in the record's stack. A format 2 file writes `fault.source-map self` in every fault record and one `fault.stack` line per position, outermost first; a format 1 file writes neither.\n   6. `diagnostic-fault` is present exactly when the code is C6001 or C6002. The message text of the diagnostic is not part of the file.\n   7. The outcome `refused` means that the host interface refused the entry before it started, for example for a fuel budget below 0. No execution exists, so the file has no output or fuel line. The `refused.reason` text is informative and is not compared. An implementation that cannot decide a case does not produce a frozen expectation for it.\n   8. The `clause` value is free text. A case cites the rules it exercises by their clause identifiers, with `;` between documents.\n   9. Two `.expect` texts agree when they are equal byte for byte, except the `refused.reason` line and the `fault.revision` and `fault.source"
  },
  {
   "id": "spec-09p:the-expect-format-p5",
   "edition": "SPEC-09P.1",
   "title": "9.3 The `.expect` format (part 6)",
   "clauses": "IM-106 IM-107 IM-30 IM-32",
   "url": "/specifications/spec-09p/1/#the-expect-format",
   "internal": 0,
   "content": "   A file of a later format may use every line of the earlier formats, and files of earlier formats are not rewritten. `conformance/tools/check_expect_abnf.py` checks every `.expect` file of the suite against this grammar and the rules that a single file can show.\n\n**Examples**\n\n6. The expectation of the case `arith/add_i64_overflow` is in format 1:\n\n```console\n$ cat conformance/arith/add_i64_overflow.expect\ncase arith/add_i64_overflow\nclause SPEC-01 IM-30, IM-32, IM-106, IM-107\nsource reference\noutcome fault\nstdout-bytes 0\nfuel-consumed 1\nfault.code E_OVERFLOW\nfault.operation add.checked.i64\nfault.operand I64 9223372036854775807\nfault.operand I64 1\nfault.exact 9223372036854775808\nfault.limit I64 9223372036854775807\nfault.position arith/add_i64_overflow.ci:5:15\nfault.revision self\nfault.address none\nfault.stack-depth 0\n```\n\nThe case is a test block, which is its entry and charges 1 unit. The fault is in the entry's own body, so the stack is empty. The print after the addition does not run, so no byte was written. The program is lines 2 to 7 of `conformance/arith/add_i64_overflow.ci`, after its header comment:\n\n```cint\ntest \"add overflow at I64 max\" {\n    I64 a = 9223372036854775807;\n    I64 b = 1;\n    I64 c = a + b;\n    \"c={c}\\n\";\n}\n```"
  },
  {
   "id": "spec-09p:lists-of-the-suite",
   "edition": "SPEC-09P.1",
   "title": "9.4 Lists of the suite",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#lists-of-the-suite",
   "internal": 0,
   "content": "### 9.4 Lists of the suite\n\n**Semantics**\n\n1. `conformance/held.txt` lists, one per line, the program cases that have no frozen expectation, each with its reason. A held case is not compared.\n2. `conformance/unsupported.txt` lists the cases that an implementation refuses under a documented limit, in the line format of 8.2.\n3. `conformance/errata/` holds the errata of 9.1."
  },
  {
   "id": "spec-09p:required-case-lists",
   "edition": "SPEC-09P.1",
   "title": "9.5 Required case lists",
   "clauses": "CONF-15",
   "url": "/specifications/spec-09p/1/#required-case-lists",
   "internal": 0,
   "content": "### 9.5 Required case lists\n\n**Semantics**\n\n1. <a id=\"CONF-15\"></a>A *required case list* is a file `conformance/required/<name>.txt` with one line `<case> <compiler> <category>` for each case and compiler, where the category is one of 8.2 and, where the category needs one, the line adds the limit. The compiler column names the executor as well: `cintc` for the compiler's C on `cpu-c17`, `cintc/cpu-sir-interp` for its SIR text on the interpreter, and `cintc/gpu-cuda` for `gpu-cuda`. `python3 tools/cint_check.py --required FILE` fails a run when a listed case is absent, a case of the suite is not listed, a case's category differs from the list, a compile error's code or position differs from the frozen expectation, or a case has no `.expect` file and is not held [CONF-15]."
  },
  {
   "id": "spec-09p:observing-compiled-programs",
   "edition": "SPEC-09P.1",
   "title": "9.6 Observing compiled programs",
   "clauses": "CONF-10 CONF-10a CONF-12",
   "url": "/specifications/spec-09p/1/#observing-compiled-programs",
   "internal": 0,
   "content": "### 9.6 Observing compiled programs\n\n**Semantics**\n\n1. <a id=\"CONF-10\"></a>A compiled conformance program is observed through `cint-harness`, a C17 program. It reads a *case list*, one call per line, `<module> <function> <typed arguments>`, and calls each exported function through its observer entry with a fresh context and the case's fuel budget. It writes the canonical outcome (the returned value, or the full fault record from the context, and the fuel consumed) in `.expect` syntax. The reference evaluates the same calls. The same harness serves every compiler under test, so all are compared through the same path [CONF-10].\n2. <a id=\"CONF-10a\"></a>The interpreter is observed the same way: `cint-interp observe` takes the command line of `cint-harness`, with a directory of SIR text in place of a program library, and writes the same text. `tools/cint_check.py --interp` runs it on every compared case [CONF-10a].\n3. <a id=\"CONF-12\"></a>A case list is the text that this grammar derives, with the core rules of 9.3. Line `n` is call `n`, and each call runs in a fresh context [CONF-12]:\n\n```abnf\ncase-list        = *call-line\ncall-line        = module-name SP name *( SP typed-value ) LF\n```"
  },
  {
   "id": "spec-09p:observing-compiled-programs-p1",
   "edition": "SPEC-09P.1",
   "title": "9.6 Observing compiled programs (part 2)",
   "clauses": "CONF-13",
   "url": "/specifications/spec-09p/1/#observing-compiled-programs",
   "internal": 0,
   "content": "4. <a id=\"CONF-13\"></a>A program built for the harness follows the observer interface `cint-observe-1` [CONF-13]:\n   - It is one shared library built from the C of all its modules, the program file and the `cint_rt` library of the same version as the harness. Its exported symbols have C linkage and carry `CINT_RT_EXPORT`. The harness resolves the program's path before it loads it.\n   - It exports exactly two observer symbols, both defined in the program file: `const uint32_t cint_program_abi = CINT_ABI_VERSION;` and `const cint_observer cint_observer_desc;`. The descriptor names the program (every module's site table, the root module first) and lists one entry for every exported function of every module whose parameters and result are scalars, in module order and then declaration order. The harness does not call a program whose `cint_program_abi` differs from its own.\n   - Each entry carries its module index, its name, a type signature of its result and at most 16 parameters (the tags of `I8` to `I64`, `U8` to `U64` and `Bool`) and its function, of type `cint_status (*)(cint_ctx *ctx, int64_t fuel, int64_t depth, const uint64_t *args, uint64_t *result)`. An argument is a 64-bit pattern: sign-extended for a signed type, zero-extended for an unsigned type, 0 or 1 for `Bool`. The function calls `cint_rt_entry_begin(ctx, <its entry site>, fuel, depth)`, returns that status unless it is `CINT_OK`, then runs the body and returns `cint_rt_entry_end(ctx)`. It writes `*result` only when there is a result and the status is `CINT_OK`.\n   - Entry functions are `static`, named `cg` + C(P) + `_o<N>`, with type signatures `cg` + C(P) + `_t<N>`, numbered in each module in declaration order (7.7). Each module's C file defines its observer table `cg` + C(P) + `_obs` and its site table with external linkage, not exported, so that the program file can name them."
  },
  {
   "id": "spec-09p:observing-compiled-programs-p2",
   "edition": "SPEC-09P.1",
   "title": "9.6 Observing compiled programs (part 3)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#observing-compiled-programs",
   "internal": 0,
   "content": "   A change to this interface is a new version, `cint-observe-2`. The layouts of `cint_observer` and `cint_observer_entry` are declared in `rt/cint_rt.h`, which governs where it and this paragraph differ."
  },
  {
   "id": "spec-09p:further-checks-of-a-run",
   "edition": "SPEC-09P.1",
   "title": "9.7 Further checks of a run",
   "clauses": "CONF-05 CONF-16 CONF-17",
   "url": "/specifications/spec-09p/1/#further-checks-of-a-run",
   "internal": 0,
   "content": "### 9.7 Further checks of a run\n\n**Semantics**\n\n1. <a id=\"CONF-05\"></a>For each conformance program, the compiler is run twice: from two different working directories, with the source tree at two different absolute paths, and with different values of `TZ`, `LANG` and `SOURCE_DATE_EPOCH`. The two sets of emitted C are compared byte for byte, and a difference fails the run [CONF-05].\n2. <a id=\"CONF-16\"></a>The reference writes the canonical type signature of each export (SPEC-03P.1), and `tools/cint_check.py` compares it, for every export of the suite that has a public wrapper, with the bytes that the compiler under test writes into the program's reflection table. A difference fails the run as an outcome difference does [CONF-16].\n3. <a id=\"CONF-17\"></a>A conformance run on `gpu-cuda` uses the same frozen expectations. Each compared case runs at two block sizes, 32 and 256 work-items (`tools/cint_check.py --backend gpu-cuda --block 32` and `--block 256`), on the device. The boundary matrices of `bnd64/` also run as kernels, through the kernel tables `conformance/tables/kernel_<op>_<form>_i64.ci`: one dispatch over the rows that do not fault, and one dispatch for each row that faults, with expectations in format 4. A case that the capability table of `gpu-cuda` does not support is unsupported, with its line in `conformance/unsupported.txt` naming the capability (8.2) [CONF-17]."
  },
  {
   "id": "spec-09p:running-one-case",
   "edition": "SPEC-09P.1",
   "title": "9.8 Running one case",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#running-one-case",
   "internal": 0,
   "content": "### 9.8 Running one case\n\n**Examples**\n\n1. The reference checks one case against its frozen expectation. It prints nothing and exits with status 0 when they agree, and names the first line that differs otherwise:\n\n```console\n$ python3 -m cint_ref check conformance/arith/add_i64_overflow.ci conformance/arith/add_i64_overflow.expect\n$ echo $?\n0\n$ sed 's/^fuel-consumed 1$/fuel-consumed 2/' conformance/arith/add_i64_overflow.expect > wrong.expect\n$ python3 -m cint_ref check conformance/arith/add_i64_overflow.ci wrong.expect\nwrong.expect: line 6 differs\n  expected: fuel-consumed 2\n  actual:   fuel-consumed 1\n$ echo $?\n1\n```\n\n2. `tools/cint_check.py` runs cases through a compiler and compares them with their frozen expectations and with the reference. `--only` selects the cases whose name contains its argument, and `--quick` leaves out the table programs. `--compiler b1 --cint \"$BOOT/cint\"` tests the compiler inside the `cint` command that the bootstrap of 10.3 wrote into the directory `$BOOT`; without `--cint`, the tool first runs that bootstrap itself. `--leg`, `--opt` and `--helpers` choose the configuration and `--no-receipt` writes no receipt (11.3 writes them):"
  },
  {
   "id": "spec-09p:running-one-case-p1",
   "edition": "SPEC-09P.1",
   "title": "9.8 Running one case (part 2)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#running-one-case",
   "internal": 0,
   "content": "```console\n$ python3 tools/cint_check.py --leg gcc --opt 0 --helpers portable --quick --compiler b1 --cint \"$BOOT/cint\" --only arith/add_i64_overflow --no-receipt\ninventory: 1 programs, 1 records, 0 cases classified without compiling; cint_ref against the frozen .expect files: 0 differ (23 ms)\n...\nruntime symbol audit: 131 defined external symbols, 0 outside cint_\ngcc-0-portable-quick: 1 programs compiled, 1 records compared, 0 disagree, 0 sanitizer reports, 0 nondeterministic, 0 symbol audit findings, 0 type signatures compared, 0 type signature disagreements, 8 s; suite 5ccd378e30da7e1917bb03176f68a388d770da998075a10160043635f6e89d79\nnot compared: held 0, not_applicable 0, outside_subset 0, unsupported 0; disagreements before compiling: 0\n...\n```\n\nThe first line reports that the reference agrees with the frozen expectation. The runtime's own symbols are audited (7.10). The case was compiled twice (9.7) and compared, and no case fell in another category of 8.2. The digest after `suite` is the SHA-256 digest of the suite's files, which identifies the version of the suite."
  },
  {
   "id": "spec-09p:bootstrap",
   "edition": "SPEC-09P.1",
   "title": "10 Bootstrap",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#bootstrap",
   "internal": 0,
   "content": "## 10 Bootstrap\n\nThe compiler is written in cint, so building it needs a cint compiler. cint 0.2.0 breaks this circle with a C17 program written by hand, which compiles the compiler's source once. Every later compiler is built from that one. This clause describes that program, how the compiler is built from it, the check that the compiler reproduces itself, and what that check does not show."
  },
  {
   "id": "spec-09p:names",
   "edition": "SPEC-09P.1",
   "title": "10.1 Names",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#names",
   "internal": 0,
   "content": "### 10.1 Names\n\n1. These names are used in this clause only:\n   - *C0*: the C toolchain of a configuration.\n   - *the seed*: the bootstrap compiler `cint-seed`, built by C0 from `seed/`.\n   - *the seed's C*: the C that the seed emits for the compiler's source.\n   - *the first compiler*: the compiler that C0 builds from the seed's C, the runtime and the bridge. The `cint` command contains the same compiler objects as the first compiler.\n   - *the first emitted C*: the C that the first compiler emits for the compiler's source.\n   - *the second compiler*: the compiler that C0 builds from the first emitted C.\n   - *the second emitted C*: the C that the second compiler emits for the compiler's source."
  },
  {
   "id": "spec-09p:the-seed",
   "edition": "SPEC-09P.1",
   "title": "10.2 The seed",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-seed",
   "internal": 0,
   "content": "### 10.2 The seed\n\n**Semantics**"
  },
  {
   "id": "spec-09p:the-seed-p1",
   "edition": "SPEC-09P.1",
   "title": "10.2 The seed (part 2)",
   "clauses": "SEED-01 SEED-02 SEED-03 SEED-04 SEED-05 SEED-13 SEED-15 SEED-16",
   "url": "/specifications/spec-09p/1/#the-seed",
   "internal": 0,
   "content": "1. <a id=\"SEED-01\"></a>The seed compiles the compiler's source into the seed's C, and, for its own conformance, programs of the boot subset of paragraph 7. It is not a compiler for users and is not installed [SEED-01].\n2. <a id=\"SEED-02\"></a>The seed is written by hand in C17. It is not generated from cint, and no generated C file is an input of the bootstrap [SEED-02].\n3. <a id=\"SEED-03\"></a>The seed depends only on the C17 standard library, `cint_rt.h`, the `cint_rt` library and the bridge. Its platform calls are confined to the bridge [SEED-03].\n4. <a id=\"SEED-04\"></a>The seed shares no code with `cintc` other than the runtime and the bridge. It translates its parse tree directly into C and builds no SIR [SEED-04].\n5. <a id=\"SEED-05\"></a>The seed performs every run-time check of the boot subset and produces the full fault record, field for field identical to the one `cintc` produces, except the revision, which it reports as absent because it builds no SIR [SEED-05].\n6. <a id=\"SEED-13\"></a>The seed performs no optimization. It does not remove, merge or reorder run-time checks; it folds no expression that is not a constant expression; it does not inline functions, eliminate common subexpressions, hoist loop invariants or unroll loops; it does not choose a representation for a value from the value; and it relies on no extension of the C compiler other than those that `cint_rt.h` selects. The C compiler that compiles the seed's C may optimize [SEED-13].\n7. <a id=\"BOOT-01\"></a><a id=\"BOOT-02\"></a>The *boot subset*, `cint-boot-1`, is the part of the language that the seed accepts: the integer types `I8` to `I64` and `U8` to `U64`, `Bool`, the checked, wrapping and bitwise operators, `as` and `as%`, structs, local arrays of constant extent, rank-1 views as parameters, constants, functions, `if`, `while`, the C form and the range form of `for`, `switch`, and `import` and `"
  },
  {
   "id": "spec-09p:the-seed-p2",
   "edition": "SPEC-09P.1",
   "title": "10.2 The seed (part 3)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-seed",
   "internal": 0,
   "content": "**Notes**\n\n10. The root of trust that the seed adds is a set of files a reader can read. The C toolchain that compiles it stays trusted, and 10.5 says what checks it.\n11. Two translators of different structure that agree, such as the seed and `cintc`, are stronger evidence than one translator checked against itself."
  },
  {
   "id": "spec-09p:building-the-compiler",
   "edition": "SPEC-09P.1",
   "title": "10.3 Building the compiler",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#building-the-compiler",
   "internal": 0,
   "content": "### 10.3 Building the compiler\n\n**Semantics**"
  },
  {
   "id": "spec-09p:building-the-compiler-p1",
   "edition": "SPEC-09P.1",
   "title": "10.3 Building the compiler (part 2)",
   "clauses": "CINTC-07 RCPT-05",
   "url": "/specifications/spec-09p/1/#building-the-compiler",
   "internal": 0,
   "content": "1. <a id=\"BOOT-03\"></a>The compiler's own source keeps these design rules: no call cycle; no print statement or other input or output; no module-level variable or statement, since state outside the tables that the bridge allocates would outlive a module; no call of a program function in a constant, a static assertion or an extent; and ASCII bytes only. In cint 0.2.0 the compiler's source is inside the boot subset, so the seed compiles it directly [BOOT-03].\n2. <a id=\"CINTC-07\"></a>The compiler's sources, the seed, the runtime, the bridge and the harness use LF line endings, and the bootstrap refuses a CR byte in them [CINTC-07].\n3. `python3 tools/cint_bootstrap.py --leg gcc --out \"$BOOT\"` builds the compiler with GCC into the directory `$BOOT`, which must lie outside the source tree. It builds, in order: the runtime objects; the seed, from `seed/*.c`, `rt/cint_rt.c` and `rt/cint_bridge.c`; the seed's C, by running the seed on `compiler/main.ci` in `compiler/`, one C file for the whole compiler; the first compiler, from the seed's C, `compiler/tests/golden_host.c`, the runtime and the bridge; and the `cint` command, from `cli/` and the same compiler objects. It then writes `cint`, two toolchain files and the receipt `bootstrap.json` into `$BOOT`. `cint.toolchain` is the configuration with which `cint run` and `cint build` compile programs, `-O2` with the builtin helpers, and `cint-bootstrap.toolchain` the one with which the first compiler and `cint` were built, `-O0` with the portable helpers.\n4. <a id=\"RCPT-05\"></a>Digests are computed twice: by the `digest` export of `compiler/sha256.ci` in the first compiler, and by an external SHA-256 implementation. The bootstrap tool computes in the first compiler the digests of the source manifests, of the seed's C, of `cint` and of the runtime sources, compares each with Python's `hashlib` and fails on any difference. The recei"
  },
  {
   "id": "spec-09p:building-the-compiler-p2",
   "edition": "SPEC-09P.1",
   "title": "10.3 Building the compiler (part 3)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#building-the-compiler",
   "internal": 0,
   "content": "**Examples**\n\n5. The receipt of a bootstrap:\n\n```console\n$ jq -r '.schema, .identity.profile, .identity.runtime_contract_version, .outcome.source_digest_verification' \"$BOOT/bootstrap.json\"\ncint-bootstrap-receipt-1\ncint-core-1\ncint-rt-3\npass\n$ jq -r '.identity.compiler_sources[].path' \"$BOOT/bootstrap.json\"\ncompiler/back_c.ci\ncompiler/back_ptx.ci\ncompiler/check.ci\ncompiler/decl.ci\ncompiler/emit.ci\ncompiler/fold.ci\ncompiler/limits.ci\ncompiler/lowering.ci\ncompiler/main.ci\ncompiler/parse.ci\ncompiler/resolve.ci\ncompiler/scan.ci\ncompiler/sha256.ci\ncompiler/verify.ci\n$ jq -cS '{identity, outcome}' \"$BOOT/bootstrap.json\" | tr -d '\\n' | sha256sum\n2b4859c123ecdced8c3bb8ec5e6eee55c1de5fb55b5e53eb014dee1daf9d0cfc  -\n$ jq -r .identity_sha256 \"$BOOT/bootstrap.json\"\n2b4859c123ecdced8c3bb8ec5e6eee55c1de5fb55b5e53eb014dee1daf9d0cfc\n```\n\nThe identity names the 14 source files of the compiler with their digests, the runtime sources and the seed's source identity. The last two commands recompute the receipt identity (11.2) with external tools and show the value the receipt records."
  },
  {
   "id": "spec-09p:the-fixpoint",
   "edition": "SPEC-09P.1",
   "title": "10.4 The fixpoint",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-fixpoint",
   "internal": 0,
   "content": "### 10.4 The fixpoint\n\n**Semantics**"
  },
  {
   "id": "spec-09p:the-fixpoint-p1",
   "edition": "SPEC-09P.1",
   "title": "10.4 The fixpoint (part 2)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#the-fixpoint",
   "internal": 0,
   "content": "1. <a id=\"FIX-01\"></a>The first compiler compiles the compiler's source into the first emitted C, one C file for each module and a `MANIFEST`; C0 builds the second compiler from it; and the second compiler compiles the same source into the second emitted C. The first and the second emitted C are byte-identical, file by file, the `MANIFEST` included. The seed's C is not compared with them, because the seed is a separate translator that does not optimize, and its C differs from that of `cintc` [FIX-01].\n2. <a id=\"FIX-02\"></a>The fixpoint is checked by comparing bytes and by comparing the SHA-256 digest of each file, and both results are recorded in the receipt. The report of a difference names the first differing file, its byte offset and its line [FIX-02].\n3. <a id=\"FIX-03\"></a>The first and the second compiler emit byte-identical C for every program of the corpus: every `.ci` program under `conformance/`, `examples/` and `compiler/tests/`. This extends the fixpoint from one program, the compiler, to all of them [FIX-03].\n4. <a id=\"FIX-05\"></a>The digests of the executables of the seed and of the first and second compilers are recorded as observations, outside every identity. They differ between toolchains and may differ between two builds with one toolchain; for example, an MSVC link without `/Brepro` writes a time stamp into the executable. No claim is made that executables are byte-identical [FIX-05].\n5. `python3 tools/cint_fixpoint.py --leg gcc --receipt FILE` builds the seed, the two compilers and the two emitted C in one configuration and checks paragraphs 1 to 3; `--opt` and `--helpers` choose the configuration, `--sanitize` adds the sanitizers of 7.6 and `--no-corpus` checks paragraphs 1 and 2 only. The receipt's identity holds the input digests and the digest of the first emitted C, and no path, time or executable digest."
  },
  {
   "id": "spec-09p:what-the-fixpoint-does-not-show",
   "edition": "SPEC-09P.1",
   "title": "10.5 What the fixpoint does not show",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#what-the-fixpoint-does-not-show",
   "internal": 0,
   "content": "### 10.5 What the fixpoint does not show\n\n**Semantics**\n\n1. <a id=\"FIX-04\"></a>*Cross-toolchain bootstrap agreement*: the first emitted C is byte-identical whichever toolchain of the run matrix (8.4) is C0, at every optimization level. `python3 tools/cint_fixpoint.py --compare RECEIPT ...` checks that a set of fixpoint receipts has one identity. Different C compilers produce different executables of the seed and of the first compiler, so a miscompilation that changed the compiler's emitted C would have to occur identically in every C compiler of the matrix to go undetected. The check shows that the compiler's emitted C does not depend on which toolchain of the matrix built the compiler. It does not show that any distributed executable corresponds to the compiler's source (10.4 paragraph 4); that the shared inputs, the compiler's source, the seed, the runtime and the bridge, are free of defects, since every toolchain compiles the same ones; or that the toolchains share no code or design [FIX-04].\n\n**Notes**\n\n2. The idea of rebuilding a compiler with a diverse second compiler and comparing the result comes from Wheeler's diverse double-compiling. That technique makes a different claim: under its stated assumptions, the equality of the final executable with the distributed one shows that source and executable correspond. The check of paragraph 1 designates no trusted compiler and compares emitted C, so it makes no claim about executables and is not diverse double-compiling."
  },
  {
   "id": "spec-09p:reproducing-the-bootstrap",
   "edition": "SPEC-09P.1",
   "title": "10.6 Reproducing the bootstrap",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#reproducing-the-bootstrap",
   "internal": 0,
   "content": "### 10.6 Reproducing the bootstrap\n\n**Examples**\n\n1. A reader with a C17 toolchain, Python 3 and the source tree reproduces the bootstrap and the fixpoint with two commands, each on one configuration:\n\n```text\npython3 tools/cint_bootstrap.py --leg gcc --out \"$BOOT\"\npython3 tools/cint_fixpoint.py --leg gcc --receipt fixpoint-gcc-0-portable.json\n```\n\n`--leg` is `gcc`, `clang` or `apple-clang` on Linux and macOS, and `msvc` on Windows. The fixpoint receipt's identity is then compared with the published one (11.3)."
  },
  {
   "id": "spec-09p:receipts-and-reproduction",
   "edition": "SPEC-09P.1",
   "title": "11 Receipts and reproduction",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#receipts-and-reproduction",
   "internal": 0,
   "content": "## 11 Receipts and reproduction\n\nA receipt records what a run read, what it concluded and what it observed of the machine. Its identity covers only the first two, so two machines that ran the same inputs to the same outcome produce the same identity. A published figure is rerun by producing a receipt and comparing its identity."
  },
  {
   "id": "spec-09p:identities",
   "edition": "SPEC-09P.1",
   "title": "11.1 Identities",
   "clauses": "RCPT-01",
   "url": "/specifications/spec-09p/1/#identities",
   "internal": 0,
   "content": "### 11.1 Identities\n\n**Semantics**\n\n1. <a id=\"RCPT-01\"></a>Each kind of output has its own identity [RCPT-01]:\n\n| Identity | Inputs | What it determines |\n| --- | --- | --- |\n| Build identity of emitted text | the sources and their module-relative paths, the compiler source identity, the language profile, the executor and its options | emitted C and PTX, byte for byte; C0 is not an input (7.7) |\n| Executable observation | the above and C0 | executables and objects, recorded and not claimed identical (10.4) |\n| Revision identity | 6.5 | the meaning of a program, shared by every build of it against one runtime contract version |\n| Execution identity | the revision and the semantic inputs | the output bytes, the fault record and the fuel |\n\n   An x86-64 executable and a GPU kernel do not share a digest; built against one runtime contract version, they share the revision identity and the canonical outcomes."
  },
  {
   "id": "spec-09p:receipt-content",
   "edition": "SPEC-09P.1",
   "title": "11.2 Receipt content",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#receipt-content",
   "internal": 0,
   "content": "### 11.2 Receipt content\n\n**Semantics**"
  },
  {
   "id": "spec-09p:receipt-content-p1",
   "edition": "SPEC-09P.1",
   "title": "11.2 Receipt content (part 2)",
   "clauses": "RCPT-02 RCPT-03 RCPT-04",
   "url": "/specifications/spec-09p/1/#receipt-content",
   "internal": 0,
   "content": "1. <a id=\"RCPT-02\"></a>A bootstrap, a fixpoint run and a conformance run each write a receipt. A receipt file is the receipt object followed by one LF, written as the JSON Canonicalization Scheme (RFC 8785) writes it, with keys sorted and no white space outside strings, except in the escaping of strings. That departure is this: a receipt holds ASCII characters only, so a character outside ASCII is written `\\u` with four lowercase hexadecimal digits, and a character above U+FFFF as its UTF-16 surrogate pair, where RFC 8785 writes the character itself. The tools of this clause write a receipt with Python's `json.dumps` and the arguments `sort_keys=True`, `separators=(\",\", \":\")` and `ensure_ascii=True`. They refuse a string outside ASCII, and they write U+007F as `\\u007f`, where RFC 8785 and the tools of SPEC-06P.1 12.1 write it as itself. A receipt holds integers only, each within the I-JSON range of plus or minus 2^53 - 1; larger values and all digests are strings, and digests are 64 lowercase hexadecimal characters. Arrays of files are in byte order of path. The key `schema` names the format of the receipt and its version, such as `cint-bootstrap-receipt-1` or `cint-conformance-receipt-2`. A new version is written to a new file, and a receipt of an earlier version is not edited or regenerated; it stays valid for the sources it names. `identity.encodings` records each encoding version that the receipt relies on, such as the `.expect` formats and the fault record version [RCPT-02].\n2. <a id=\"RCPT-03\"></a>A receipt has three parts: `identity`, the inputs and the digests of emitted text; `outcome`, the result of each check; and `observations`, the timings, the host, the C toolchain, the digests of executables and the counts of executions. The receipt identity is the SHA-256 digest of the bytes of the object `{\"identity\": ..., \"outcome\": ...}`, written as paragraph 1 state"
  },
  {
   "id": "spec-09p:rerunning-a-published-figure",
   "edition": "SPEC-09P.1",
   "title": "11.3 Rerunning a published figure",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#rerunning-a-published-figure",
   "internal": 0,
   "content": "### 11.3 Rerunning a published figure\n\n**Examples**\n\n1. A published figure of agreement is a set of receipts. To rerun one, a reader builds `cint` with the bootstrap of 10.3, runs `tools/cint_check.py` with the same arguments, writes the receipt with `--receipt` and compares its identity with the published one. Two configurations of the same tree and the same suite have the same identity, because nothing in it depends on the configuration:"
  },
  {
   "id": "spec-09p:rerunning-a-published-figure-p1",
   "edition": "SPEC-09P.1",
   "title": "11.3 Rerunning a published figure (part 2)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#rerunning-a-published-figure",
   "internal": 0,
   "content": "```console\n$ python3 tools/cint_check.py --leg gcc --opt 0 --helpers portable --quick --compiler b1 --cint \"$BOOT/cint\" --only arith/add_i64_overflow --receipt rc/receipt-gcc-0-portable.json\n...\nreceipt written\n$ python3 tools/cint_check.py --leg gcc --opt 2 --helpers builtin --quick --compiler b1 --cint \"$BOOT/cint\" --only arith/add_i64_overflow --receipt rc/receipt-gcc-2-builtin.json\n...\ngcc-2-builtin-quick: 1 programs compiled, 1 records compared, 0 disagree, 0 sanitizer reports, 0 nondeterministic, 0 symbol audit findings, 0 type signatures compared, 0 type signature disagreements, 14 s; suite 5ccd378e30da7e1917bb03176f68a388d770da998075a10160043635f6e89d79\n...\nreceipt written\n$ python3 tools/cint_receipts.py identity rc\nreceipt-gcc-0-portable.json 0dd4dfea0066583c pass\nreceipt-gcc-2-builtin.json 0dd4dfea0066583c pass\n1 receipt identity in 2 receipts\n$ python3 tools/cint_receipts.py compare --outcome rc/receipt-gcc-0-portable.json rc/receipt-gcc-2-builtin.json\ncompare: same outcome\n$ jq -c '.identity | {schema, profile, runtime_contract_version, encodings}' rc/receipt-gcc-0-portable.json\n{\"schema\":\"cint-conformance-receipt-2\",\"profile\":\"cint-core-1\",\"runtime_contract_version\":\"cint-rt-3\",\"encodings\":{\"expect_formats\":[1,2,3,4,5],\"fault\":\"cint-core-1/fault/v2\",\"type_signature\":\"cint-core-1/type-signature/v1\"}}\n$ jq -cS '{identity, outcome}' rc/receipt-gcc-0-portable.json | tr -d '\\n' | sha256sum\n0dd4dfea0066583c8e5dcc9ddc73017defc38ee2a4443760b3231a1e2e11d7af  -\n$ jq -r .observations.receipt_identity_sha256 rc/receipt-gcc-0-portable.json\n0dd4dfea0066583c8e5dcc9ddc73017defc38ee2a4443760b3231a1e2e11d7af\n```"
  },
  {
   "id": "spec-09p:rerunning-a-published-figure-p2",
   "edition": "SPEC-09P.1",
   "title": "11.3 Rerunning a published figure (part 3)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#rerunning-a-published-figure",
   "internal": 0,
   "content": "`cint_receipts.py identity` prints the first 16 hexadecimal digits of each receipt identity and whether the run passed. The last two commands compute the receipt identity with `jq` and `sha256sum`, which share no code with the tools of the tree; `jq -cS` writes the object with sorted keys and no spaces, which for these receipts are the bytes of 11.2, paragraph 1. A reader whose receipt identity equals the published one ran the same inputs to the same outcome.\n\n2. <a id=\"DISC-07\"></a>A report of a reproduction states the machine, the operating system, the toolchain and its version, the commands run, the resulting receipt identities and any deviation from the published procedure [DISC-07]."
  },
  {
   "id": "spec-09p:claims",
   "edition": "SPEC-09P.1",
   "title": "11.4 Claims",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#claims",
   "internal": 0,
   "content": "### 11.4 Claims\n\n**Semantics**\n\n1. <a id=\"DISC-02\"></a>A published claim about cint is backed by material that a reader can obtain, normally a receipt. No claim of compliance with MISRA C, the SEI CERT C Coding Standard or another standard is made without a documented assessment against named editions and rules. Citations are to published material [DISC-02].\n2. <a id=\"DISC-03\"></a>The statement that emitted C has no undefined behavior is made only in this form [DISC-03]:\n\n| Part | Content |\n| --- | --- |\n| Claim | Emitted C, `cint_rt.h` and the `cint_rt` library do not evaluate an operation whose C17 behavior is undefined, for programs that `cintc` accepts. |\n| Design rules | 7.3 and 7.4. |\n| Evidence | The conformance programs compiled and run under UndefinedBehaviorSanitizer and AddressSanitizer on the toolchains and versions that the receipts record, with no report. These sanitizers do not detect violations of the aliasing rules, unsequenced modifications or every lifetime error, so the evidence covers the programs run, not every accepted program. |\n| Assumptions | A correct bootstrap compiler (10.2), `cintc`, runtime and bridge; the properties of 7.2 paragraph 2; a correct C toolchain for the constructs used (none of the toolchains of the matrix claims full C17 conformance); no foreign code; buffers from the host that meet the contract of SPEC-03P.1. |\n| Exclusions | Exhaustion of the C stack; foreign functions; buffers from the host that break the contract. |\n\n3. <a id=\"DISC-04\"></a>A performance number is published only with its workload, machine, toolchain, flags and method of measurement [DISC-04]."
  },
  {
   "id": "spec-09p:refusals-of-the-cint-tools-in-0-2-0",
   "edition": "SPEC-09P.1",
   "title": "12 Refusals of the cint tools in 0.2.0",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#refusals-of-the-cint-tools-in-0-2-0",
   "internal": 0,
   "content": "## 12 Refusals of the cint tools in 0.2.0\n\nThis clause is informative. It lists the constructs that the reference runs and that a tool of cint 0.2.0 refuses, by construct, with the tool and the diagnostic, and the limits of the tools that are below the minimums of SPEC-04P.2. A refused program is not run with another meaning (8.2), and on an implementation that runs it, its outcome is the one SPEC-04P.2 specifies. The interpreter runs the SIR text that `cint` writes, so a construct that `cint` refuses does not reach it.\n\n1. The `cint` command (`cint run`, `cint build`, `cint test` and `cint emit-c`) refuses these constructs with the diagnostic C9102, or the one that the row names, at the position shown:"
  },
  {
   "id": "spec-09p:refusals-of-the-cint-tools-in-0-2-0-p1",
   "edition": "SPEC-09P.1",
   "title": "12 Refusals of the cint tools in 0.2.0 (part 2)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#refusals-of-the-cint-tools-in-0-2-0",
   "internal": 0,
   "content": "| Construct | Example | Position |\n| --- | --- | --- |\n| Fixed-point types `Q<i>.<f>` and fraction literals | `Q16.16 a = 1.5;`, `Q8.8 x = 0.25;` | the type |\n| `as?` from a wide type | `I64 r = v as? I64 catch -1;` with `I128 v` | the operand |\n| A result form on a wide type | `I128 r = add_result(a, b) catch 0;` | the call |\n| `switch` on a wide value | `switch (v)` with `I256 v` | the scrutinee |\n| `rotl` and `rotr` by a count of a wide type | `rotl(a, n)` with `U64 a`, `I128 n` | the call |\n| `muldiv` of narrow operands into a wide result type | `muldiv(I128, a, b, c, floor)` with `I64` operands | the call |\n| An exported function with a parameter or a result of a wide integer type or a fixed-point type | `export I64 low(I128 x)` | the parameter's name, or the result type |\n| An array declared at the top level of a script | `I64[3] a = [1, 2, 3];` | the array literal, or the declaration when it has none |\n| A struct type declared in a script | `struct P { I64 x; I64 y; }` before top-level statements | the struct's name |\n| An array literal of structs | `P[2] ps = [P(1, 2), P(3, 4)];` | the `[` of the literal |\n| A view variable over an array of structs | `in P[_] v = ps;` | the variable's name |\n| Named arguments in a call of a user function | `diff(b = 1, a = 10)` | the first name |\n| A step `by` in a range `for` loop | `for i in 0..10 by 3 { ... }` | the step |\n| A selected import | `import geo.vec.{V2, dot2};` | the `import` |\n| `catch` on a call of a function of an imported module | `parse.digit(c) catch -1` with `import lib.parse;` | the function's name |\n| A `catch` expression as the operand of another operator | `(f(1) catch 0) + 1` | the `catch` |\n| The wrapping negation `-%` | `I8 n = -%m;` | the operator |\n| `len` of a string literal | `len(\"abc\")` | the string literal |\n| The format conversions `!bits` and `!lanes(T)` in a print statement | `\"{x!bits}\\n"
  },
  {
   "id": "spec-09p:refusals-of-the-cint-tools-in-0-2-0-p2",
   "edition": "SPEC-09P.1",
   "title": "12 Refusals of the cint tools in 0.2.0 (part 3)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#refusals-of-the-cint-tools-in-0-2-0",
   "internal": 0,
   "content": "2. A program whose entry is a function `main`, rather than top-level statements, may declare struct types: the row of a struct declared in a script applies to scripts only. The `cint` command also reports C9102 for `==` between two arrays, which the reference rejects with the diagnostic C2013 at the same position, so both reject such a program. It reports C9102 for a fraction literal given to an integer type, as in `I64 x = 1.5;`, which the reference rejects with the diagnostic C2004 at the same position. In the same way it reports C9102, at the print statement, for the conversion `!ratio` of an integer, as in `\"{x!ratio}\\n\";` with `I64 x`. SPEC-04P.2 7.5.4 makes that conversion C1037, and the reference reports C1037 at the value of the hole. The C3005 of a kernel called after a module's name is not a refusal in the sense of SPEC-04P.2 4, paragraph 4, whose codes begin with `C9`: the `cint` command rejects that conforming program as it rejects an undefined name.\n3. In one case the direction is reversed, and the reference refuses a run that the `cint` command carries out. For `clamp(x, lo, hi)` with `lo` greater than `hi` at run time, `cint run` faults `E_DOMAIN` with the operation `clamp.checked.<t>`, such as `clamp.checked.i64`, and the operands `x`, `lo` and `hi`, with no exact result and no limit, as SPEC-04P.2 7.2.1 states. The reference reports the outcome `refused` for that run.\n4. A `gpu-cuda` build refuses a kernel whose body needs a capability that the `gpu-cuda` table lists as unsupported, with `E_UNSUPPORTED`, naming the kernel, the capability, the SIR node and the position (5.5). The `cpu-c17` build of the same program runs it."
  },
  {
   "id": "spec-09p:refusals-of-the-cint-tools-in-0-2-0-p3",
   "edition": "SPEC-09P.1",
   "title": "12 Refusals of the cint tools in 0.2.0 (part 4)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#refusals-of-the-cint-tools-in-0-2-0",
   "internal": 0,
   "content": "| Capability | Construct in a kernel body | Example |\n| --- | --- | --- |\n| `sat` | the saturating operators `+\\|`, `-\\|` and `*\\|` | `b[i] = a[i] +\\| a[i];` |\n| `div` | `/` and `%` | `b[i] = a[i] / 2;` |\n| `shift` | `<<` and `>>`, wrapping or checked | `b[i] = a[i] << 1;` |\n| `bits` | `&`, `\\|`, `^`, `~` and `!` | `b[i] = a[i] & 3;` |\n| `neg` | unary `-` | `b[i] = -a[i];` |\n| `as.wrap` | the wrapping conversion `as%` | `(a[i] as% I32) as I64` |\n| `builtin` | every built-in function except `div_round` | `b[i] = min(a[i], 2);` |\n| `switch` | `switch` | `switch (a[i]) { ... }` |\n| `store.narrow` | a store into a view of 8-bit, 16-bit or `Bool` elements | `out U8[n] b` |\n| `array` | a local array | `I64[2] t;` |\n| `wide` | any value of `I128` to `I1024` | `in I128[n] a` |\n\n5. Three limits of the tools of cint 0.2.0 are below the minimums that SPEC-04P.2 5.3 states. A program beyond any of them is stopped, and the reference runs it:"
  },
  {
   "id": "spec-09p:refusals-of-the-cint-tools-in-0-2-0-p4",
   "edition": "SPEC-09P.1",
   "title": "12 Refusals of the cint tools in 0.2.0 (part 5)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#refusals-of-the-cint-tools-in-0-2-0",
   "internal": 0,
   "content": "| Quantity | Minimum in SPEC-04P.2 5.3 | Limit of the tools | Beyond the limit |\n| --- | --- | --- | --- |\n| Size of one source file | 16,777,216 bytes | 4,194,304 bytes, in `cint run`, `cint build`, `cint test` and `cint emit-c` | For the file it is given, the command stops with a tool error and exit status 5; an imported module of that size is the diagnostic C3009. The reference runs a file of 5,242,880 bytes. |\n| Call-depth limit accepted as a semantic input | 4,096 active calls | 1,024 active calls, the constant `CINT_RT_MAX_DEPTH` of the runtime (7.10) | An entry whose depth limit is larger faults `E_UNSUPPORTED` at `call.enter` before it runs, with the limit 1,024. The reference runs a recursion 4,000 calls deep under a depth limit of 4,096. |\n| Size of an imported module, against the size of the root module | 16,777,216 bytes, as for every source file | A bound that grows with the size of the root module, in `cint run`, `cint build`, `cint test` and `cint emit-c`: 745,090 bytes for a root module of 34 bytes | The command stops with the diagnostic C9001 at line 0 of the root module, position `0:0`, though the imported module is under 4,194,304 bytes; SPEC-04P.2 5.3 places a C9001 that concerns a whole file at line 1. Under a root module of 34 bytes, an imported module of 745,091 bytes is C9001. Under a root module of 341 bytes, an imported module of 4,000,000 bytes runs, and so does a root module of 4,000,000 bytes that holds the same function. The reference runs the program. |"
  },
  {
   "id": "spec-09p:future-directions",
   "edition": "SPEC-09P.1",
   "title": "13 Future directions",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#future-directions",
   "internal": 0,
   "content": "## 13 Future directions\n\nThis clause is informative. It names work that cint 0.2.0 does not include.\n\n1. *Reproducible executables.* The executables of a bootstrap differ between toolchains and may differ between two builds with one toolchain, so receipts record their digests as observations only (10.4). Byte-identical executables, built with options such as `-ffile-prefix-map` for GCC and Clang and `/Brepro` for MSVC, let a receipt identify the executable as well as the C it was built from.\n2. *Diverse double-compiling.* In Wheeler's technique, the compiler's source is compiled by a second compiler that is trusted, and the resulting executable is compared with the distributed one; equality shows that the source and the executable correspond. It needs reproducible executables and a designated trusted compiler, and it extends the agreement of 10.5 from emitted C to executables."
  },
  {
   "id": "spec-09p:measured-agreement",
   "edition": "SPEC-09P.1",
   "title": "Annex A (informative) Measured agreement",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#measured-agreement",
   "internal": 0,
   "content": "## Annex A (informative) Measured agreement"
  },
  {
   "id": "spec-09p:measured-agreement-p1",
   "edition": "SPEC-09P.1",
   "title": "Annex A (informative) Measured agreement (part 2)",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#measured-agreement",
   "internal": 0,
   "content": "1. The figures of this annex are sets of receipts published with cint 0.2.0, and 11.3 shows how a reader reruns them. Every receipt was written from one source tree, whose suite digest is `3a19e408ac4c5822411ec2444a42d6507e97952a914591ccfa09e6375bd1377e`. The source package of the release publishes the conformance tables as a separate file, `cint-v0.2.0-conformance-tables.tar.gz`, so a run of the package reports the suite digest of 11.3 and another receipt identity than the figures below.\n2. `cpu-c17`: 24 configurations pass with one receipt identity, `1970cbf4dd7c5ef39f04cc10cbfa293702057fc31e6e64bea30ed2b80996a128`. They are GCC and Clang on Linux x86-64 at `-O0` and `-O2` in both helper modes, each with and without the sanitizers of 7.6 (16); MSVC on Windows x86-64 at `/Od` and `/O2` in both helper modes (4); and Apple Clang on macOS AArch64 at `-O0` and `-O2` in both helper modes (4). Each compiles 658 programs and compares 1,868,066 records with no disagreement; 11 cases are held, 67 are not applicable and 47 are unsupported, the cases of `conformance/fixed/` (clause 12).\n3. `cpu-c17` and `cpu-sir-interp` together: 44 of the 48 configurations of this run pass, with the counts of paragraph 2 and two receipt identities, `30ffed5415bcc145a41090b4411c111120393191bca59e31120dd42fae016d89` for `cpu-c17` and `4c89cb670ff83b3a9d425d9b5c47b430e99a3cca7b20ba7d99ebad3c1733b35f` for `cpu-sir-interp`. Four configurations with GCC 16.2.1 and Clang 22.1.8 on Linux x86-64 did not complete, so this figure is incomplete: GCC at `-O2` in portable mode on both executors, the same with the sanitizers on `cpu-c17`, and Clang at `-O0` in portable mode on `cpu-c17`.\n4. Sanitized runs: 23 configurations of GCC and Clang on Linux x86-64 under UndefinedBehaviorSanitizer and AddressSanitizer, 15 on `cpu-c17` and 8 on `cpu-sir-interp`, report no finding.\n5. The fixpoint (10.4 and 10.5) passe"
  },
  {
   "id": "spec-09p:bibliography",
   "edition": "SPEC-09P.1",
   "title": "Bibliography",
   "clauses": "",
   "url": "/specifications/spec-09p/1/#bibliography",
   "internal": 0,
   "content": "## Bibliography\n\n- David A. Wheeler. *Fully Countering Trusting Trust through Diverse Double-Compiling*. PhD dissertation, George Mason University, 2009. arXiv:1004.5534. Diverse double-compiling, in 10.5 and 13.\n- Free Software Foundation. \"Integer Overflow Builtins.\" *Using the GNU Compiler Collection (GCC)*. https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html. The builtins of the helper mode of 7.3, paragraph 2.\n- LLVM Project, the Clang Team. \"UndefinedBehaviorSanitizer.\" *Clang documentation*. https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html. The sanitized conformance runs of 7.6 and 11.4.\n- LLVM Project, the Clang Team. \"AddressSanitizer.\" *Clang documentation*. https://clang.llvm.org/docs/AddressSanitizer.html. The sanitized conformance runs of 7.6 and 11.4."
  },
  {
   "id": "spec-09p:annex-b-informative-clause-identifiers-stated-in",
   "edition": "SPEC-09P.1",
   "title": "Annex B (informative) Clause identifiers stated in other editions",
   "clauses": "BACK-07 BACK-08 BACK-13 CINTC-09",
   "url": "/specifications/spec-09p/1/#annex-b-informative-clause-identifiers-stated-in-other-editions",
   "internal": 0,
   "content": "## Annex B (informative) Clause identifiers stated in other editions\n\nA tool message, or an earlier edition, may cite a clause identifier of this document's series whose rule a 0.2.0 edition states elsewhere. Each such identifier is listed here with the edition and section that state it, or, where no 0.2.0 edition states its rule, with the section that describes the topic.\n\n| Identifier | Stated in |\n|---|---|\n| <a id=\"BACK-07\"></a>BACK-07 | [SPEC-02P.1 9.1](SPEC-02P.1-KERNELS.md#BACK-07) |\n| <a id=\"BACK-08\"></a>BACK-08 | [SPEC-02P.1 9.2](SPEC-02P.1-KERNELS.md#BACK-08) |\n| <a id=\"BACK-13\"></a>BACK-13 | [SPEC-02P.1 10.6](SPEC-02P.1-KERNELS.md#BACK-13) |\n| <a id=\"CINTC-09\"></a>CINTC-09 | [SPEC-06P.1 9.9](SPEC-06P.1-TOOLS.md#CINTC-09) |"
  },
  {
   "id": "glossary-p:glossary-p-2",
   "edition": "GLOSSARY-P.2",
   "title": "GLOSSARY-P.2",
   "clauses": "",
   "url": "/specifications/glossary-p/2/",
   "internal": 0,
   "content": "# GLOSSARY-P.2: Glossary\n\nGLOSSARY-P.2, edition 2 of the glossary of the cint specification, cint v0.2.0, 2026-10-11.\n\nThis edition replaces GLOSSARY-P.1. It is a reference to the rules of the other editions: where an entry and the section it points to differ, the section governs. Its text does not change after its release; a correction that changes no meaning is listed in [ERRATA.md](ERRATA.md), and a change of meaning is published as a new edition.\n\nSection 1 explains, in plain words, the ideas a first reading meets. Section 2 lists the types and operators. Section 3 lists every term that a 0.2.0 edition defines in its clause 3, with the first sentence of its definition and a link to it. Each entry has an anchor named by its word, such as `GLOSSARY-P.2.md#golden` in section 1 and `GLOSSARY-P.2.md#term-fuel` in section 3."
  },
  {
   "id": "glossary-p:1-words-for-a-first-reading",
   "edition": "GLOSSARY-P.2",
   "title": "1 Words for a first reading",
   "clauses": "",
   "url": "/specifications/glossary-p/2/#1-words-for-a-first-reading",
   "internal": 0,
   "content": "## 1 Words for a first reading\n\nThese entries explain words that the specifications use in their everyday programming sense, for a reader who is new to programming or to C. Each points to the section that teaches the idea. Section 3 gives the precise definitions."
  },
  {
   "id": "glossary-p:1-words-for-a-first-reading-p1",
   "edition": "GLOSSARY-P.2",
   "title": "1 Words for a first reading (part 2)",
   "clauses": "",
   "url": "/specifications/glossary-p/2/#1-words-for-a-first-reading",
   "internal": 0,
   "content": "| Word | Meaning | Read |\n|---|---|---|\n| <a id=\"value\"></a>value | A number a program works with. In cint every value has a type: an integer type, `Bool`, a fixed-point type or an array or struct type built from them. A fixed-point value such as `1.5` in `Q16.16` is held as an integer count of units of 2^-16. | [SPEC-04P.2 6.2.1](SPEC-04P.2-LANGUAGE.md#values) |\n| <a id=\"type\"></a>type | The kind of a value: its range and the operations it allows. `I32` is a signed integer of 32 bits; `U8` an unsigned integer of 8 bits, from 0 to 255. Every variable has one type, written before its name. | [SPEC-04P.2 6.3](SPEC-04P.2-LANGUAGE.md#types) |\n| <a id=\"variable\"></a>variable | A named place that holds a value and can be given a new one: `I64 total = 0;` declares one, and `total = total + 5;` changes it. | [SPEC-04P.2 6.9.1](SPEC-04P.2-LANGUAGE.md#variables) |\n| <a id=\"constant\"></a>constant | A named value that never changes, fixed when the program is translated: `const I64 DAYS = 7;`. | [SPEC-04P.2 6.9.2](SPEC-04P.2-LANGUAGE.md#constants) |\n| <a id=\"expression\"></a>expression | Text that computes a value, such as `price * count + 1`. | [SPEC-04P.2 6.7](SPEC-04P.2-LANGUAGE.md#expressions) |\n| <a id=\"statement\"></a>statement | One step of a program, such as a declaration, an assignment, an `if` or a loop. A declaration, an assignment and a call end with `;`; an `if`, a loop and a block end with `}`. | [SPEC-04P.2 6.10](SPEC-04P.2-LANGUAGE.md#statements) |\n| <a id=\"loop\"></a>loop | A statement that runs a block again and again: `for i in 0..10 { }` runs it once for each `i` from 0 to 9, and `while (x > 0) { }` runs it while the condition holds. | [SPEC-04P.2 6.10.3, 6.10.4](SPEC-04P.2-LANGUAGE.md#the-for-statement) |\n| <a id=\"function\"></a>function | A named piece of program that receives values through its parameters, computes, and may return a value: `I64 square(I64 x) { r"
  },
  {
   "id": "glossary-p:2-types-and-operators",
   "edition": "GLOSSARY-P.2",
   "title": "2 Types and operators",
   "clauses": "",
   "url": "/specifications/glossary-p/2/#2-types-and-operators",
   "internal": 0,
   "content": "## 2 Types and operators"
  },
  {
   "id": "glossary-p:2-types-and-operators-p1",
   "edition": "GLOSSARY-P.2",
   "title": "2 Types and operators (part 2)",
   "clauses": "",
   "url": "/specifications/glossary-p/2/#2-types-and-operators",
   "internal": 0,
   "content": "| Spelling | Meaning | Read |\n|---|---|---|\n| `I8` `I16` `I32` `I64` | Signed integers of 8, 16, 32 and 64 bits. | [SPEC-04P.2 6.3.1](SPEC-04P.2-LANGUAGE.md#integer-types) |\n| `U8` `U16` `U32` `U64` | Unsigned integers of 8, 16, 32 and 64 bits. | [SPEC-04P.2 6.3.1](SPEC-04P.2-LANGUAGE.md#integer-types) |\n| `I128` `I256` `I512` `I1024`, `U128` `U256` `U512` | The wide integer types, with the same operators as the others. | [SPEC-04P.2 6.3.1](SPEC-04P.2-LANGUAGE.md#integer-types) |\n| `Q<i>.<f>`, such as `Q16.16` | Signed fixed point with `i` integer bits and `f` fraction bits: an integer counted in units of 2^-`f`. | [SPEC-04P.2 6.3.2](SPEC-04P.2-LANGUAGE.md#fixed-point-types) |\n| `Bool` | `true` or `false`. | [SPEC-04P.2 6.3.3](SPEC-04P.2-LANGUAGE.md#bool) |\n| `T[n]`, `T[n, m]` | An array of `n` elements, or of `n` by `m`, of type `T`. | [SPEC-04P.2 6.3.4](SPEC-04P.2-LANGUAGE.md#array-types) |\n| `in T[_]`, `inout T[_]` | A view that may only be read, or may be read and written. | [SPEC-04P.2 6.3.5](SPEC-04P.2-LANGUAGE.md#view-types) |\n| `E!T` | An error union: a value of `T`, or an error of the error set `E`. | [SPEC-04P.2 6.3.7](SPEC-04P.2-LANGUAGE.md#error-sets-and-error-unions) |\n| `+` `-` `*` `/` `%` `<<` `>>` | Every plain operator is checked: the exact result when it is in range, and a fault otherwise. | [SPEC-04P.2 6.7](SPEC-04P.2-LANGUAGE.md#expressions) |\n| `+%` `-%` `*%` `<<%` | Wrapping operators, which never fault: the exact result reduced into the type's range. | [SPEC-04P.2 6.7.6](SPEC-04P.2-LANGUAGE.md#additive-operators) |\n| `+\\|` `-\\|` `*\\|` | Saturating operators, which never fault: the exact result clamped to the type's range. | [SPEC-04P.2 6.7.6](SPEC-04P.2-LANGUAGE.md#additive-operators), [6.7.7](SPEC-04P.2-LANGUAGE.md#multiplicative-operators) |\n| `/` and `%` on integers | Division rounded toward negative infinity, and the remainder with the sign "
  },
  {
   "id": "glossary-p:3-terms-of-the-specifications",
   "edition": "GLOSSARY-P.2",
   "title": "3 Terms of the specifications",
   "clauses": "",
   "url": "/specifications/glossary-p/2/#3-terms-of-the-specifications",
   "internal": 0,
   "content": "## 3 Terms of the specifications"
  },
  {
   "id": "glossary-p:3-terms-of-the-specifications-p1",
   "edition": "GLOSSARY-P.2",
   "title": "3 Terms of the specifications (part 2)",
   "clauses": "",
   "url": "/specifications/glossary-p/2/#3-terms-of-the-specifications",
   "internal": 0,
   "content": "| Term | Definition | Defined in |\n|---|---|---|\n| <a id=\"term-address\"></a>address | The part of a fault record that locates a fault in a dispatch: the kernel's qualified name, the dispatch number, the phase, and, in the work-item phase, the work-item index and the step ordinal. | [SPEC-02P.1 3.10](SPEC-02P.1-KERNELS.md#term-address) |\n| <a id=\"term-addressed-storage\"></a>addressed storage | The set of element offsets that a view reaches. | [SPEC-02P.1 3.15](SPEC-02P.1-KERNELS.md#term-addressed-storage) |\n| <a id=\"term-agreement\"></a>agreement | The relation between two implementations whose canonical outcomes for a program and the same semantic inputs are equal. | [SPEC-09P.1 3.13](SPEC-09P.1-TOOLCHAIN.md#term-agreement) |\n| <a id=\"term-arena\"></a>arena | A region of storage with a fixed capacity from which objects are taken and released together. | [SPEC-04P.2 3.30](SPEC-04P.2-LANGUAGE.md#term-arena) |\n| <a id=\"term-array\"></a>array | A fixed number of elements of one type, stored in order. | [SPEC-04P.2 3.26](SPEC-04P.2-LANGUAGE.md#term-array) |\n| <a id=\"term-bootstrap\"></a>bootstrap | The building of the compiler from its source text and a C toolchain, with no cint compiler built earlier. | [SPEC-09P.1 3.18](SPEC-09P.1-TOOLCHAIN.md#term-bootstrap) |\n| <a id=\"term-borrow\"></a>borrow | The use of host memory by cint code without a copy. | [SPEC-03P.1 3.12](SPEC-03P.1-HOST-INTERFACE.md#term-borrow) |\n| <a id=\"term-boundary\"></a>boundary | A point of a run at which the state of its context is defined and its state hash is taken: the end of an entry that ran, or, at dispatch density, the publication of a kernel dispatch. | [SPEC-01P.2 3.16](SPEC-01P.2-ENCODINGS.md#term-boundary) |\n| boundary | A point of a run at which the state of its context is defined and its state hash is taken, such as the end of an entry that ran (SPEC-01P.2, 3.16). | [SPEC-06P.1 3.7](SPEC-06P.1"
  },
  {
   "id": "references-p:references-p-2",
   "edition": "REFERENCES-P.2",
   "title": "REFERENCES-P.2",
   "clauses": "",
   "url": "/specifications/references-p/2/",
   "internal": 0,
   "content": "# REFERENCES-P.2: References\n\nREFERENCES-P.2, edition 2 of the references of the cint specification, cint v0.2.0, 2026-10-11.\n\nThis edition replaces REFERENCES-P.1.\n\nStatus: Informative. This edition is the shared bibliography of the editions of the cint specification published with cint v0.2.0: SPEC-00P.2, SPEC-01P.2, SPEC-02P.1, SPEC-03P.1, SPEC-04P.2, SPEC-06P.1 and SPEC-09P.1. The text of this edition does not change after its release. Corrections that change no meaning, such as a locator that has moved, are listed in [ERRATA.md](ERRATA.md); an entry added or removed makes a new edition.\n\nEvery published work that a 0.2.0 edition cites is listed here once, with a stable key. An edition lists in its clause 2, Normative references, the works whose content is part of its requirements. It lists the other works it cites in a Bibliography at its end, or names them in the text where they are used. SPEC-00P.2 is informative and has no clause 2; it names works in its text. The editions of the cint specification are not listed here; SPEC-00P.2 section 3 lists them. Each entry ends with a \"Cited by\" note that names the citing editions by identifier and the clauses that cite the work."
  },
  {
   "id": "references-p:how-to-read-an-entry",
   "edition": "REFERENCES-P.2",
   "title": "How to read an entry",
   "clauses": "",
   "url": "/specifications/references-p/2/#how-to-read-an-entry",
   "internal": 0,
   "content": "## How to read an entry\n\n- An entry gives the author or organization, the title, the date and a stable identifier: a standard number, an RFC number, a FIPS number, a DOI, an arXiv identifier, an ISBN or the official documentation URL. Titles of whole works are in italics; titles of parts (articles, chapters, pages, sections) are in quotation marks.\n- \"Read 2026-10-10\" marks a web page with no version of its own; the page may change after that date. Where a locator serves the newest version of a versioned document, the entry says so.\n- Where an edition names a work without its edition, version or revision, the entry gives the one read on 2026-10-10 and says so.\n- In a \"Cited by\" note, \"2\" is the citing edition's clause 2, Normative references, and \"Bibliography\" is its list of other works. Any other number is a section of that edition, followed where it helps by a note, a paragraph or an item."
  },
  {
   "id": "references-p:how-the-entries-were-checked",
   "edition": "REFERENCES-P.2",
   "title": "How the entries were checked",
   "clauses": "",
   "url": "/specifications/references-p/2/#how-the-entries-were-checked",
   "internal": 0,
   "content": "## How the entries were checked\n\nEach entry's identifier, title, authors or organization, and date were checked on 2026-10-10 against the publisher's own page or registry: Crossref for DOIs, arXiv for arXiv identifiers and the RFC Editor for RFCs."
  },
  {
   "id": "references-p:1-standards-and-specifications",
   "edition": "REFERENCES-P.2",
   "title": "1. Standards and specifications",
   "clauses": "",
   "url": "/specifications/references-p/2/#1-standards-and-specifications",
   "internal": 0,
   "content": "## 1. Standards and specifications"
  },
  {
   "id": "references-p:1-standards-and-specifications-p1",
   "edition": "REFERENCES-P.2",
   "title": "1. Standards and specifications (part 2)",
   "clauses": "LS-275",
   "url": "/specifications/references-p/2/#1-standards-and-specifications",
   "internal": 0,
   "content": "- [ArrayAPI-2023.12] Consortium for Python Data API Standards. *Python array API standard*, version 2023.12. https://data-apis.org/array-api/2023.12/; the method `array.__dlpack__`: https://data-apis.org/array-api/2023.12/API_specification/generated/array_api.array.__dlpack__.html. The newest version on 2026-10-10 is 2025.12.\n  - Cited by: SPEC-03P.1 2 and 8.3.\n- [FIPS-180-4] National Institute of Standards and Technology. *Secure Hash Standard (SHS)*. FIPS PUB 180-4, August 2015. DOI 10.6028/NIST.FIPS.180-4.\n  - Cited by: SPEC-01P.2 2, 7.6, 8.5 and 9; SPEC-03P.1 2 and 5.1; SPEC-06P.1 2 and 6; SPEC-09P.1 2, 6.5, 10.3 and 11.2.\n- [IEEE-754-2019] IEEE. *IEEE Std 754-2019, IEEE Standard for Floating-Point Arithmetic*. IEEE, 2019 (approved 2019-06-13, published 2019-07-22). DOI 10.1109/IEEESTD.2019.8766229.\n  - Cited by: SPEC-03P.1 2 and 8.5; SPEC-04P.2 6.7.15, note 12.\n- [ISO-1539-1-2023] ISO/IEC JTC 1/SC 22. *ISO/IEC 1539-1:2023, Programming languages: Fortran: Part 1: Base language* (Fortran 2023). International Organization for Standardization, 2023. https://www.iso.org/standard/82170.html. The editions name Fortran without an edition; this is the edition in force on 2026-10-10.\n  - Cited by: SPEC-03P.1 8.2, paragraph 13 (Fortran-ordered arrays); SPEC-04P.2 7.2.2, note 11 (`MOD` and `MODULO`), and 7.3, paragraphs 28 and 31 (array element order).\n- [ISO-9899-2018] ISO/IEC JTC 1/SC 22. *ISO/IEC 9899:2018, Information technology: Programming languages: C* (C17). International Organization for Standardization, 2018. https://www.iso.org/standard/74528.html. ISO lists this edition as withdrawn on 2024-10-31 and replaced by ISO/IEC 9899:2024; the editions cite the 2018 edition by its date. The WG 14 working paper N2310 (2018-11-06) marks its changes against that edition and can be read without charge: https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2310.pdf.\n  - Cited by: "
  },
  {
   "id": "references-p:2-vendor-project-and-tool-documentation",
   "edition": "REFERENCES-P.2",
   "title": "2. Vendor, project and tool documentation",
   "clauses": "",
   "url": "/specifications/references-p/2/#2-vendor-project-and-tool-documentation",
   "internal": 0,
   "content": "## 2. Vendor, project and tool documentation"
  },
  {
   "id": "references-p:2-vendor-project-and-tool-documentation-p1",
   "edition": "REFERENCES-P.2",
   "title": "2. Vendor, project and tool documentation (part 2)",
   "clauses": "LS-275",
   "url": "/specifications/references-p/2/#2-vendor-project-and-tool-documentation",
   "internal": 0,
   "content": "- [CERN-ROOT-CINT] CERN, ROOT project. \"CINT the C++ Interpreter.\" Chapter 9 of the ROOT users guide for ROOT 5. https://root.cern/root/html534/guides/users-guide/CINT.html. Read 2026-10-10.\n  - Cited by: SPEC-00P.2 8, which names this interpreter to say that cint is not related to it.\n- [Clang-ASan] LLVM Project, the Clang Team. \"AddressSanitizer.\" *Clang documentation*. https://clang.llvm.org/docs/AddressSanitizer.html. Read 2026-10-10; the page is the documentation of the development version and names no release.\n  - Cited by: SPEC-00P.2 7, claim 9; SPEC-09P.1 7.6, 11.4 and Bibliography.\n- [Clang-UBSan] LLVM Project, the Clang Team. \"UndefinedBehaviorSanitizer.\" *Clang documentation*. https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html. Read 2026-10-10; the page is the documentation of the development version and names no release.\n  - Cited by: SPEC-00P.2 7, claim 9; SPEC-09P.1 7.6, 11.4 and Bibliography.\n- [Davis-HolyC] Terry A. Davis. \"HolyC.\" TempleOS documentation, file `Doc/HolyC.DD` (undated). No publisher-maintained locator exists; community archive of the TempleOS source: https://github.com/cia-foundation/TempleOS/blob/archive/Doc/HolyC.DD. Read 2026-10-10.\n  - Cited by: SPEC-00P.2 9.\n- [DLPack] DLPack contributors. *DLPack: Open In Memory Tensor Structure*. Repository https://github.com/dmlc/dlpack; release v1.3 (2026-01-26), the newest on 2026-10-10, whose `include/dlpack/dlpack.h` defines version 1.3. The documentation is at https://dmlc.github.io/dlpack/latest/, including the C API (`c_api.html`) and the Python specification (`python_spec.html`). Its pages are headed \"DLPack 0.6.0 documentation.\" Read 2026-10-10.\n  - Cited by: SPEC-03P.1 2, 6.3 and 8.3.\n- [GCC-Case-Ranges] Free Software Foundation. \"Case Ranges.\" *Using the GNU Compiler Collection (GCC)*. https://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html. Read 2026-10-10.\n  - Cited by: SPEC-04"
  },
  {
   "id": "references-p:3-papers-books-and-reports",
   "edition": "REFERENCES-P.2",
   "title": "3. Papers, books and reports",
   "clauses": "",
   "url": "/specifications/references-p/2/#3-papers-books-and-reports",
   "internal": 0,
   "content": "## 3. Papers, books and reports\n\n- [Blelloch-1990] Guy E. Blelloch. *Prefix Sums and Their Applications*. Technical Report CMU-CS-90-190, School of Computer Science, Carnegie Mellon University, November 1990. https://www.cs.cmu.edu/~scandal/papers/CMU-CS-90-190.html.\n  - Cited by: SPEC-02P.1 Bibliography, for 9.2 and 10.5.\n- [Henriksen-2017] Troels Henriksen, Niels G. W. Serup, Martin Elsman, Fritz Henglein and Cosmin E. Oancea. \"Futhark: Purely Functional GPU-Programming with Nested Parallelism and In-Place Array Updates.\" *Proceedings of the 38th ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI 2017)*, pages 556-571, 2017. DOI 10.1145/3062341.3062354.\n  - Cited by: SPEC-00P.2 9.\n- [OCallahan-2017] Robert O'Callahan, Chris Jones, Nathan Froyd, Kyle Huey, Albert Noll and Nimrod Partush. \"Engineering Record and Replay for Deployability: Extended Technical Report.\" arXiv:1705.05937, 2017. https://arxiv.org/abs/1705.05937. The paper describes the rr debugger.\n  - Cited by: SPEC-00P.2 9.\n- [Pharr-2012] Matt Pharr and William R. Mark. \"ispc: A SPMD Compiler for High-Performance CPU Programming.\" *2012 Innovative Parallel Computing (InPar)*, pages 1-13, May 2012. DOI 10.1109/InPar.2012.6339601.\n  - Cited by: SPEC-00P.2 9; SPEC-02P.1 8.2 and Bibliography.\n- [Wheeler-2009] David A. Wheeler. *Fully Countering Trusting Trust through Diverse Double-Compiling*. PhD dissertation, George Mason University, 2009. arXiv:1004.5534. https://dwheeler.com/trusting-trust/; repository copy: http://mars.gmu.edu/handle/1920/5667.\n  - Cited by: SPEC-00P.2 7, which names the technique; SPEC-09P.1 10.5, 13 and Bibliography."
  },
  {
   "id": "errata:errata",
   "edition": "ERRATA",
   "title": "ERRATA",
   "clauses": "",
   "url": "/specifications/errata/",
   "internal": 0,
   "content": "# Errata\n\nCorrections to released editions that change no meaning: a typo, a broken link, or a clearer sentence. The edition's own text is not edited; its corrections are listed here, numbered per edition (`SPEC-01P.1 E1`, `SPEC-01P.1 E2`), and in the notes of the release that lists them. A correction that changes meaning is a new edition, not an erratum.\n\nEach entry gives the erratum's name, the section and clause, the text as published, the corrected text, and the release that lists it."
  },
  {
   "id": "errata:spec-00p-1",
   "edition": "ERRATA",
   "title": "SPEC-00P.1",
   "clauses": "",
   "url": "/specifications/errata/#spec-00p-1",
   "internal": 0,
   "content": "## SPEC-00P.1\n\nNone."
  },
  {
   "id": "errata:spec-01p-1",
   "edition": "ERRATA",
   "title": "SPEC-01P.1",
   "clauses": "",
   "url": "/specifications/errata/#spec-01p-1",
   "internal": 0,
   "content": "## SPEC-01P.1\n\nNone."
  },
  {
   "id": "errata:spec-04p-1",
   "edition": "ERRATA",
   "title": "SPEC-04P.1",
   "clauses": "",
   "url": "/specifications/errata/#spec-04p-1",
   "internal": 0,
   "content": "## SPEC-04P.1\n\nNone."
  },
  {
   "id": "errata:glossary-p-1",
   "edition": "ERRATA",
   "title": "GLOSSARY-P.1",
   "clauses": "",
   "url": "/specifications/errata/#glossary-p-1",
   "internal": 0,
   "content": "## GLOSSARY-P.1\n\nNone."
  },
  {
   "id": "errata:references-p-1",
   "edition": "ERRATA",
   "title": "REFERENCES-P.1",
   "clauses": "",
   "url": "/specifications/errata/#references-p-1",
   "internal": 0,
   "content": "## REFERENCES-P.1\n\nNone."
  },
  {
   "id": "errata:spec-00p-2",
   "edition": "ERRATA",
   "title": "SPEC-00P.2",
   "clauses": "",
   "url": "/specifications/errata/#spec-00p-2",
   "internal": 0,
   "content": "## SPEC-00P.2\n\nNone."
  },
  {
   "id": "errata:spec-01p-2",
   "edition": "ERRATA",
   "title": "SPEC-01P.2",
   "clauses": "",
   "url": "/specifications/errata/#spec-01p-2",
   "internal": 0,
   "content": "## SPEC-01P.2\n\nNone."
  },
  {
   "id": "errata:spec-02p-1",
   "edition": "ERRATA",
   "title": "SPEC-02P.1",
   "clauses": "",
   "url": "/specifications/errata/#spec-02p-1",
   "internal": 0,
   "content": "## SPEC-02P.1\n\nNone."
  },
  {
   "id": "errata:spec-03p-1",
   "edition": "ERRATA",
   "title": "SPEC-03P.1",
   "clauses": "",
   "url": "/specifications/errata/#spec-03p-1",
   "internal": 0,
   "content": "## SPEC-03P.1\n\nNone."
  },
  {
   "id": "errata:spec-04p-2",
   "edition": "ERRATA",
   "title": "SPEC-04P.2",
   "clauses": "",
   "url": "/specifications/errata/#spec-04p-2",
   "internal": 0,
   "content": "## SPEC-04P.2\n\nNone."
  },
  {
   "id": "errata:spec-06p-1",
   "edition": "ERRATA",
   "title": "SPEC-06P.1",
   "clauses": "",
   "url": "/specifications/errata/#spec-06p-1",
   "internal": 0,
   "content": "## SPEC-06P.1\n\nNone."
  },
  {
   "id": "errata:spec-09p-1",
   "edition": "ERRATA",
   "title": "SPEC-09P.1",
   "clauses": "",
   "url": "/specifications/errata/#spec-09p-1",
   "internal": 0,
   "content": "## SPEC-09P.1\n\nNone."
  },
  {
   "id": "errata:glossary-p-2",
   "edition": "ERRATA",
   "title": "GLOSSARY-P.2",
   "clauses": "",
   "url": "/specifications/errata/#glossary-p-2",
   "internal": 0,
   "content": "## GLOSSARY-P.2\n\nNone."
  },
  {
   "id": "errata:references-p-2",
   "edition": "ERRATA",
   "title": "REFERENCES-P.2",
   "clauses": "",
   "url": "/specifications/errata/#references-p-2",
   "internal": 0,
   "content": "## REFERENCES-P.2\n\nNone."
  },
  {
   "id": "cu-101-00:cu-101-2",
   "edition": "CU-101.2",
   "title": "CU-101.2",
   "clauses": "",
   "url": "/university/101/00-welcome/",
   "internal": 0,
   "content": "# 101-00: welcome\n\n<a id=\"101-00\"></a>This is lesson 101-00 of CU-101.2, checked against cint 0.2.0.\n\n*You will run your first program, change it and run it again.*"
  },
  {
   "id": "cu-101-00:what-a-program-is",
   "edition": "CU-101.2",
   "title": "what a program is",
   "clauses": "",
   "url": "/university/101/00-welcome/#what-a-program-is",
   "internal": 0,
   "content": "## what a program is\n\nA program is a list of instructions that a computer carries out in order. A programming language is a way of writing those instructions down so that both you and the computer can read them. cint is a programming language about whole numbers, which programmers call integers. It makes one promise about its plain arithmetic signs, such as `+` and `*`: each answer is exact, or the program stops and tells you where and why.\n\nYou can run every program in this course in two places:\n\n- **In your browser**: each program on these pages has a **Run** button, and there is nothing to install.\n- **On your computer**: [set up cint](../setup.md) once, with an editor to write programs in and a terminal to run them. Then save a program in a file, and in the terminal type `cint run` and the file's name.\n\nUse whichever you like. What a program prints is the same in both, down to the last character; only the messages about mistakes are laid out differently in the browser."
  },
  {
   "id": "cu-101-00:your-first-program",
   "edition": "CU-101.2",
   "title": "your first program",
   "clauses": "",
   "url": "/university/101/00-welcome/#your-first-program",
   "internal": 0,
   "content": "## your first program\n\n```ci\n\"Hello, world\\n\";\n```\n\nRun it. cint prints:\n\n```text\nHello, world\n```"
  },
  {
   "id": "cu-101-00:what-happened",
   "edition": "CU-101.2",
   "title": "what happened",
   "clauses": "",
   "url": "/university/101/00-welcome/#what-happened",
   "internal": 0,
   "content": "## what happened\n\nThe program is one line, and that line is one **statement**: one instruction to the computer.\n\n- Text between double quotes, on its own, is printed. Programmers call printed text **output**.\n- `\\n` does not print a backslash and an n. It means \"end the line here\", so that whatever comes next starts on a new line.\n- The semicolon `;` ends the statement, the way a period ends a sentence."
  },
  {
   "id": "cu-101-00:change-it",
   "edition": "CU-101.2",
   "title": "change it",
   "clauses": "",
   "url": "/university/101/00-welcome/#change-it",
   "internal": 0,
   "content": "## change it\n\nChange the program, then run it again. Guess what it will print before you run it.\n\n1. Print your own name instead of \"world\".\n2. Print two lines: put a second statement under the first, such as `\"Goodbye, world\\n\";`.\n3. In the two-line program, delete the `\\n` from the first line only.\n\n<details>\n<summary>what the third change prints</summary>\n\n```text\nHello, worldGoodbye, world\n```\n\nWithout `\\n`, the first line never ends, so the second statement's text follows it on the same line. If you printed your own name in step 1, it appears in place of the first \"world\".\n</details>"
  },
  {
   "id": "cu-101-00:what-cint-0-2-0-does-not-do",
   "edition": "CU-101.2",
   "title": "what cint 0.2.0 does not do",
   "clauses": "",
   "url": "/university/101/00-welcome/#what-cint-0-2-0-does-not-do",
   "internal": 0,
   "content": "## what cint 0.2.0 does not do\n\nMany first programs ask for your name and greet you, or roll dice. cint 0.2.0 cannot do either: it has no way to read what you type, no way to keep a piece of text in the program's memory and no random numbers. It does not draw pictures.\n\nSo every program in this course carries its numbers and text inside it. To try different text or a different number, you change the program and run it again, as you just did. Lesson 101-01 shows how much you can still draw with plain characters."
  },
  {
   "id": "cu-101-00:new-words",
   "edition": "CU-101.2",
   "title": "new words",
   "clauses": "",
   "url": "/university/101/00-welcome/#new-words",
   "internal": 0,
   "content": "## new words\n\n[program]({{GLOSSARY}}#program), [statement]({{GLOSSARY}}#statement), [output]({{GLOSSARY}}#output), [integer]({{GLOSSARY}}#integer)\n\nNext: [lesson 101-01, printing](01-printing.md)."
  },
  {
   "id": "cu-101-01:cu-101-2",
   "edition": "CU-101.2",
   "title": "CU-101.2",
   "clauses": "",
   "url": "/university/101/01-printing/",
   "internal": 0,
   "content": "# 101-01: printing\n\n<a id=\"101-01\"></a>This is lesson 101-01 of CU-101.2, checked against cint 0.2.0.\n\n*You will draw a picture with characters one line at a time and meet your first error message.*"
  },
  {
   "id": "cu-101-01:the-program",
   "edition": "CU-101.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/101/01-printing/#the-program",
   "internal": 0,
   "content": "## the program\n\n```ci\n// A house, one line at a time.\n\"    /\\\\\\n\";\n\"   /  \\\\\\n\";\n\"  /____\\\\\\n\";\n\"  | [] |\\n\";\n\"  |____|\\n\";\n```\n\nRun it:\n\n```text\n    /\\\n   /  \\\n  /____\\\n  | [] |\n  |____|\n```"
  },
  {
   "id": "cu-101-01:what-happened",
   "edition": "CU-101.2",
   "title": "what happened",
   "clauses": "",
   "url": "/university/101/01-printing/#what-happened",
   "internal": 0,
   "content": "## what happened\n\n**The first line is a comment.** Everything from `//` to the end of the line is for people. cint skips it. Comments say what a program is for, or why a line is there.\n\n**Each other line is one statement**, and each prints one line of the picture. The computer carries them out from top to bottom, so the roof comes out first.\n\n**Spaces inside the quotes are printed.** The spaces before `/\\` push the top of the roof to the right, so it sits in the middle.\n\n**A backslash is written twice.** Inside quotes, a backslash starts an **escape code**: you met `\\n`, which ends a line. Because of that, a backslash on its own would be read as the start of an escape code. To print one backslash, you write two: `\\\\`. So the first statement holds `/\\\\\\n`: a slash, a backslash written as `\\\\`, then `\\n` to end the line.\n\nFour escape codes are all this course needs:\n\n| You write | cint prints |\n|---|---|\n| `\\n` | the end of a line |\n| `\\\\` | one backslash |\n| `\\\"` | a double quote, without ending the text |\n| `\\t` | a tab, a wide space for lining things up |\n\nFor example, `\"She said \\\"hi\\\"\\n\";` prints `She said \"hi\"`."
  },
  {
   "id": "cu-101-01:change-it",
   "edition": "CU-101.2",
   "title": "change it",
   "clauses": "",
   "url": "/university/101/01-printing/#change-it",
   "internal": 0,
   "content": "## change it\n\n1. Add a chimney to the roof. You will need to change two lines, and add a backslash or two.\n2. Draw the first letter of your name, five lines tall.\n3. Print a line with a quote in it, such as `The sign said \"open\"`."
  },
  {
   "id": "cu-101-01:when-it-goes-wrong",
   "edition": "CU-101.2",
   "title": "when it goes wrong",
   "clauses": "",
   "url": "/university/101/01-printing/#when-it-goes-wrong",
   "internal": 0,
   "content": "## when it goes wrong\n\nLeave out the closing quote on the first line of a program:\n\n```ci\n\"Hello, world\\n;\n```\n\ncint does not run anything. It prints:\n\n```text\nerror[C1034]: invalid character or string literal\n  --> hello.ci:1:1\n   |\n 1 | \"Hello, world\\n;\n   | ^\n   |\n```\n\nRead an error message from the top:\n\n- **`error`** means cint found a problem before running the program, so nothing ran.\n- **`C1034`** is the error's code. Each kind of mistake has its own code, and the [list of messages]({{DIAGNOSTICS}}) explains each one.\n- **The rest of the first line** says what kind of problem it is. A **string literal** is a piece of text in quotes, so this one says the text in quotes is not right.\n- **`--> hello.ci:1:1`** is the **source position**: `hello.ci`, the file the program was saved in, then line 1, character 1, counting characters from the left of the line.\n- **The picture below it** shows that line, with `^` under the place where cint found the problem.\n\nIn your browser the same message is laid out differently, with the same code and position.\n\nHere the `^` points at the opening quote, the start of a piece of text that never ends. Put the closing quote back, after `\\n`, and the program runs.\n\nEvery lesson from here on ends with one mistake like this, so that you meet each of these messages first in a lesson."
  },
  {
   "id": "cu-101-01:new-words",
   "edition": "CU-101.2",
   "title": "new words",
   "clauses": "",
   "url": "/university/101/01-printing/#new-words",
   "internal": 0,
   "content": "## new words\n\n[comment]({{GLOSSARY}}#comment), [escape code]({{GLOSSARY}}#escape), [string literal]({{GLOSSARY}}#string-literal), [error]({{GLOSSARY}}#error), [source position]({{GLOSSARY}}#source-position)\n\nNext: [lesson 101-02, arithmetic](02-arithmetic.md)."
  },
  {
   "id": "cu-101-02:cu-101-2",
   "edition": "CU-101.2",
   "title": "CU-101.2",
   "clauses": "",
   "url": "/university/101/02-arithmetic/",
   "internal": 0,
   "content": "# 101-02: arithmetic\n\n<a id=\"101-02\"></a>This is lesson 101-02 of CU-101.2, checked against cint 0.2.0.\n\n*You will have the computer do arithmetic inside printed text, and find out what it does with a remainder.*"
  },
  {
   "id": "cu-101-02:the-program",
   "edition": "CU-101.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/101/02-arithmetic/#the-program",
   "internal": 0,
   "content": "## the program\n\n```ci\n\"minutes in a week: {7 * 24 * 60}\\n\";\n\"2 + 3 * 4 = {2 + 3 * 4}\\n\";\n\"(2 + 3) * 4 = {(2 + 3) * 4}\\n\";\n\"17 / 5 = {17 / 5}, remainder {17 % 5}\\n\";\n\"-17 / 5 = {-17 / 5}, remainder {-17 % 5}\\n\";\n```\n\nRun it:\n\n```text\nminutes in a week: 10080\n2 + 3 * 4 = 14\n(2 + 3) * 4 = 20\n17 / 5 = 3, remainder 2\n-17 / 5 = -4, remainder 3\n```"
  },
  {
   "id": "cu-101-02:what-happened",
   "edition": "CU-101.2",
   "title": "what happened",
   "clauses": "",
   "url": "/university/101/02-arithmetic/#what-happened",
   "internal": 0,
   "content": "## what happened\n\n**Braces make a hole in the text.** cint works out what is inside `{` and `}` and prints the answer in its place. Outside the braces, `2 + 3 * 4` is printed just as it is written; inside them, it is worked out.\n\n**These signs are called operators.** `+` adds, `-` subtracts and `*` multiplies. `/` divides and `%` gives the remainder of a division.\n\n**Multiplying and dividing come before adding and subtracting**, as in school arithmetic. So `2 + 3 * 4` is `2 + 12`, which is 14. Parentheses go first, so `(2 + 3) * 4` is `5 * 4`, which is 20.\n\n**Division gives a whole number.** cint works with whole numbers only, so `17 / 5` is 3, not 3.4. `%` gives what is left over: 17 is three 5s and 2 more.\n\n**Division rounds down.** The last line divides a negative number. On a number line, -17 divided by 5 is -3.4, and \"down\" means toward the left, so the answer is -4, not -3. The remainder is then 3, because five times -4 is -20, and -20 plus 3 is -17. For every division that gives an answer, the answer times the number you divided by, plus the remainder, gives back the number you started with.\n\n```text\n   -5     -4     -3     -2     -1      0\n    |------|------|------|------|------|\n               ^\n             -3.4 rounds down to -4\n```"
  },
  {
   "id": "cu-101-02:change-it",
   "edition": "CU-101.2",
   "title": "change it",
   "clauses": "",
   "url": "/university/101/02-arithmetic/#change-it",
   "internal": 0,
   "content": "## change it\n\n1. Print how many hours are in a year of 365 days.\n2. Print how many days old you are, roughly: your age times 365.\n3. What is `100 / 7`, and what is `100 % 7`? Check the rule from above: the answer times 7, plus the remainder, is 100.\n\n<details>\n<summary>answers</summary>\n\n```text\nhours in a year: 8760\n```\n\n`100 / 7` is 14 and `100 % 7` is 2: 14 times 7 is 98, and 98 plus 2 is 100.\n</details>"
  },
  {
   "id": "cu-101-02:when-it-goes-wrong",
   "edition": "CU-101.2",
   "title": "when it goes wrong",
   "clauses": "",
   "url": "/university/101/02-arithmetic/#when-it-goes-wrong",
   "internal": 0,
   "content": "## when it goes wrong\n\nIn school, many people write `x` for times. Try it:\n\n```ci\n\"minutes in a week: {7 x 24 x 60}\\n\";\n```\n\n```text\nerror[C1035]: invalid character or string literal\n  --> minutes.ci:1:22\n   |\n 1 | \"minutes in a week: {7 x 24 x 60}\\n\";\n   |                      ^\n   |\n```\n\nThe `^` points into the hole: what is inside the braces is not something cint can work out, because `x` is not an operator. Write `*` for times."
  },
  {
   "id": "cu-101-02:new-words",
   "edition": "CU-101.2",
   "title": "new words",
   "clauses": "",
   "url": "/university/101/02-arithmetic/#new-words",
   "internal": 0,
   "content": "## new words\n\n[operator]({{GLOSSARY}}#operator), [remainder]({{GLOSSARY}}#remainder), [rounding down]({{GLOSSARY}}#floor)\n\nNext: [lesson 101-03, names for values](03-names.md)."
  },
  {
   "id": "cu-101-03:cu-101-2",
   "edition": "CU-101.2",
   "title": "CU-101.2",
   "clauses": "",
   "url": "/university/101/03-names/",
   "internal": 0,
   "content": "# 101-03: names for values\n\n<a id=\"101-03\"></a>This is lesson 101-03 of CU-101.2, checked against cint 0.2.0.\n\n*You will give a number a name, change it as the program runs and count money exactly.*"
  },
  {
   "id": "cu-101-03:the-program",
   "edition": "CU-101.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/101/03-names/#the-program",
   "internal": 0,
   "content": "## the program\n\n```ci\n// A jar of coins, counted in cents.\nI64 jar = 0;\njar += 125;\n\"put in 125, jar holds {jar}\\n\";\njar += 240;\n\"put in 240, jar holds {jar}\\n\";\njar -= 15;\n\"took out 15, jar holds {jar}\\n\";\nI64 dollars = jar / 100;\nI64 cents = jar % 100;\n\"that is {dollars} dollars and {cents} cents\\n\";\n```\n\nRun it:\n\n```text\nput in 125, jar holds 125\nput in 240, jar holds 365\ntook out 15, jar holds 350\nthat is 3 dollars and 50 cents\n```"
  },
  {
   "id": "cu-101-03:what-happened",
   "edition": "CU-101.2",
   "title": "what happened",
   "clauses": "",
   "url": "/university/101/03-names/#what-happened",
   "internal": 0,
   "content": "## what happened\n\n**`I64 jar = 0;` makes a variable.** A **variable** is a named place that holds a number. This line does three things: `I64` says what kind of number the place holds, `jar` is its name and `= 0` puts 0 in it to start. Until lesson 101-04 explains it, read `I64` as \"a whole number, which may be negative\".\n\n**A variable's number can change.** `jar += 125;` means \"add 125 to what `jar` holds\". After it, `jar` holds 125. `jar -= 15;` takes 15 away. You can also write the long form, `jar = jar + 125;`: work out the right side, then put the answer in the variable on the left. This is called an **assignment**, and the `=` sign here means \"put\", not \"is equal to\".\n\n**A name in a hole prints its number.** `{jar}` prints whatever `jar` holds at that moment, so the same hole prints 125, then 365, then 350 as the program runs.\n\n**Money is counted in cents.** The jar holds 350 cents, not 3.50 dollars, because cint counts in whole numbers. Lesson 101-02's `/` and `%` turn cents into dollars and cents: 350 divided by 100 is 3, with 50 left over. Many programs that handle money count this way, in the smallest unit, because a whole number of cents is always exact. Many other languages store an amount such as 0.10 as the nearest fraction a computer can hold, which is close to 0.10 but not equal to it.\n\n**Names are yours to choose.** A name starts with a letter and may hold letters, digits and the underscore `_`. Pick names that say what the number is: `jar`, `dollars`, `cents`."
  },
  {
   "id": "cu-101-03:change-it",
   "edition": "CU-101.2",
   "title": "change it",
   "clauses": "",
   "url": "/university/101/03-names/#change-it",
   "internal": 0,
   "content": "## change it\n\n1. Start the jar at 1000 cents instead of 0. What does the last line print?\n2. Add a line that puts in 99 more cents, and a line after it that prints the jar.\n3. Add a variable `quarters` that holds how many whole quarters (25 cents each) the jar could be changed into.\n\n<details>\n<summary>what the last line prints after the first change</summary>\n\n```text\nthat is 13 dollars and 50 cents\n```\n</details>"
  },
  {
   "id": "cu-101-03:when-it-goes-wrong",
   "edition": "CU-101.2",
   "title": "when it goes wrong",
   "clauses": "",
   "url": "/university/101/03-names/#when-it-goes-wrong",
   "internal": 0,
   "content": "## when it goes wrong\n\nNames must match exactly, capital letters included. Here the last line says `Jar` instead of `jar`:\n\n```ci\nI64 jar = 0;\njar = jar + 10;\n\"{jar}\\n\";\n\"{Jar}\\n\";\n```\n\n```text\nerror[C3005]: undefined or unusable name\n  --> jar.ci:4:3\n   |\n 4 | \"{Jar}\\n\";\n   |   ^\n   |\n```\n\nTo cint, `Jar` and `jar` are two different names, and no variable is called `Jar`. You get the same message if you use a name before the line that makes it, or leave out the `I64` in that line."
  },
  {
   "id": "cu-101-03:new-words",
   "edition": "CU-101.2",
   "title": "new words",
   "clauses": "",
   "url": "/university/101/03-names/#new-words",
   "internal": 0,
   "content": "## new words\n\n[variable]({{GLOSSARY}}#variable), [name]({{GLOSSARY}}#name), [assignment]({{GLOSSARY}}#assignment)\n\nNext: [lesson 101-04, numbers have sizes](04-sizes.md)."
  },
  {
   "id": "cu-101-04:cu-101-2",
   "edition": "CU-101.2",
   "title": "CU-101.2",
   "clauses": "",
   "url": "/university/101/04-sizes/",
   "internal": 0,
   "content": "# 101-04: numbers have sizes\n\n<a id=\"101-04\"></a>This is lesson 101-04 of CU-101.2, checked against cint 0.2.0.\n\n*You will meet cint's eight kinds of whole number, see how large each can be and watch cint refuse a number that does not fit.*"
  },
  {
   "id": "cu-101-04:the-program",
   "edition": "CU-101.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/101/04-sizes/#the-program",
   "internal": 0,
   "content": "## the program\n\n```ci\nU8 brightness = 255;\nI8 temperature = -40;\nI32 population = 2_000_000_000;\nI64 grains = 9_223_372_036_854_775_807;\n\"brightness {brightness}, smallest U8 {U8.min}, largest {U8.max}\\n\";\n\"temperature {temperature}, I8 runs from {I8.min} to {I8.max}\\n\";\n\"population {population}, I32 tops out at {I32.max}\\n\";\n\"grains {grains}\\n\";\n```\n\nRun it:\n\n```text\nbrightness 255, smallest U8 0, largest 255\ntemperature -40, I8 runs from -128 to 127\npopulation 2000000000, I32 tops out at 2147483647\ngrains 9223372036854775807\n```"
  },
  {
   "id": "cu-101-04:what-happened",
   "edition": "CU-101.2",
   "title": "what happened",
   "clauses": "",
   "url": "/university/101/04-sizes/#what-happened",
   "internal": 0,
   "content": "## what happened\n\n**A computer keeps a number in a box of bits.** A **bit** is a single 0 or 1. Eight bits can be set in 256 different ways, so a box of 8 bits can hold 256 different numbers. A box of 16 bits can hold 65,536 different numbers, and every extra bit doubles the count.\n\n**The name of a type says the size of its box.** The kind of number a variable holds is called its **type**. In cint, a type's name says two things: `U` for numbers that are never negative (unsigned), or `I` for numbers that may be negative (signed: an integer with a sign), then the number of bits.\n\n| Type | Smallest | Largest |\n|---|---|---|\n| `U8` | 0 | 255 |\n| `U16` | 0 | 65535 |\n| `U32` | 0 | 4294967295 |\n| `U64` | 0 | 18446744073709551615 |\n| `I8` | -128 | 127 |\n| `I16` | -32768 | 32767 |\n| `I32` | -2147483648 | 2147483647 |\n| `I64` | -9223372036854775808 | 9223372036854775807 |\n\nYou never need to learn these by heart: `U8.min` and `U8.max` give them, as the program shows, and the same works for every type.\n\n**Pick the type that fits the job.** A pixel's brightness runs from 0 to 255, so it fits a `U8`, and a picture with millions of pixels takes a quarter of the memory it would as `I32`. When in doubt, use `I64`: it holds any whole number from about minus nine billion billion to about nine billion billion.\n\n**Underscores make long numbers readable.** `2_000_000_000` is two billion. cint ignores the `_`; it is there for your eyes.\n\n**cint checks that a number fits its box.** Write a number that cannot fit, and cint refuses the program before it runs. This lesson's mistake shows it.\n\n**cint never moves a number to another type on its own.** Even when the number would fit, you say so:\n\n```ci\nU8 b = 200;\nI64 wide = b as I64;\n\"{wide}\\n\";\n```"
  },
  {
   "id": "cu-101-04:what-happened-p1",
   "edition": "CU-101.2",
   "title": "what happened (part 2)",
   "clauses": "",
   "url": "/university/101/04-sizes/#what-happened",
   "internal": 0,
   "content": "This prints `200`. Without `as I64`, cint refuses the line. `as` is a checked **conversion**: cint checks that the number fits the new type, and lesson 101-05 shows what happens when it does not. Keeping each number in the type you chose means you always know which box it is in."
  },
  {
   "id": "cu-101-04:change-it",
   "edition": "CU-101.2",
   "title": "change it",
   "clauses": "",
   "url": "/university/101/04-sizes/#change-it",
   "internal": 0,
   "content": "## change it\n\n1. Print the largest `U16`.\n2. Put `-1` in a `U8`. What does cint say?\n3. Make a `U8` that holds 200 and add it to an `I64` that holds 100, using `as`. The answer, 300, would not fit in a `U8`.\n\n<details>\n<summary>one way to write the third change</summary>\n\n```ci\nU8 a = 200;\nI64 total = (a as I64) + 100;\n\"{total}\\n\";\n```\n\nThis prints `300`.\n</details>"
  },
  {
   "id": "cu-101-04:when-it-goes-wrong",
   "edition": "CU-101.2",
   "title": "when it goes wrong",
   "clauses": "",
   "url": "/university/101/04-sizes/#when-it-goes-wrong",
   "internal": 0,
   "content": "## when it goes wrong\n\n```ci\nU8 brightness = 256;\n```\n\n```text\nerror[C2003]: literal does not fit its type\n  --> brightness.ci:1:17\n   |\n 1 | U8 brightness = 256;\n   |                 ^\n   |\n```\n\nA **literal** is a value written out in the program, like `256` or text in quotes. The largest `U8` is 255, so 256 does not fit, and cint says so before anything runs. Change the type to `U16`, or the number to 255."
  },
  {
   "id": "cu-101-04:new-words",
   "edition": "CU-101.2",
   "title": "new words",
   "clauses": "",
   "url": "/university/101/04-sizes/#new-words",
   "internal": 0,
   "content": "## new words\n\n[bit]({{GLOSSARY}}#bit), [type]({{GLOSSARY}}#type), [unsigned]({{GLOSSARY}}#unsigned), [signed]({{GLOSSARY}}#signed), [literal]({{GLOSSARY}}#literal), [conversion]({{GLOSSARY}}#conversion)\n\nNext: [lesson 101-05, when a number runs out](05-runs-out.md)."
  },
  {
   "id": "cu-101-05:cu-101-2",
   "edition": "CU-101.2",
   "title": "CU-101.2",
   "clauses": "",
   "url": "/university/101/05-runs-out/",
   "internal": 0,
   "content": "# 101-05: when a number runs out\n\n<a id=\"101-05\"></a>This is lesson 101-05 of CU-101.2, checked against cint 0.2.0.\n\n*You will double a number until it no longer fits its box, watch cint stop at that exact step and read the report it prints.*"
  },
  {
   "id": "cu-101-05:the-program",
   "edition": "CU-101.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/101/05-runs-out/#the-program",
   "internal": 0,
   "content": "## the program\n\n```ci\n// Double a number until it no longer fits in a U8.\nU8 x = 1;\nfor step in 1..=10 {\n    \"step {step}: {x}\\n\";\n    x *= 2;\n}\n```\n\nThe program has two new parts. `for step in 1..=10 { ... }` is a **loop**: it runs the lines between the braces ten times, with `step` counting 1, 2, 3 and so on up to 10. Lesson 101-07 is all about loops. `x *= 2;` doubles `x`, the way `+=` added in lesson 101-03.\n\nRun it:\n\n```text\nstep 1: 1\nstep 2: 2\nstep 3: 4\nstep 4: 8\nstep 5: 16\nstep 6: 32\nstep 7: 64\nstep 8: 128\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> doubling.ci:5:7\n   |\n 5 |     x *= 2;\n   |       ^ mul.checked.u8\n   |\n   = operation: mul.checked.u8\n   = operand-count: 2\n   = operand: U8 128\n   = operand: U8 2\n   = exact:   256\n   = limit:   U8 255\n   = revision: 8efe88d0637573b3291746f4096933013c3e869ecc8be5ae436c45314575f6f4\n   = source-map: none\n   = address: none\n   = stack-depth: 0\n   = fuel-consumed: 9 (not part of the fault record)\n   = state: the program stopped; stdout holds what it wrote before the fault\n```"
  },
  {
   "id": "cu-101-05:what-happened",
   "edition": "CU-101.2",
   "title": "what happened",
   "clauses": "",
   "url": "/university/101/05-runs-out/#what-happened",
   "internal": 0,
   "content": "## what happened\n\nEight lines printed. At step 8, `x` held 128, and the next doubling would make 256. The largest `U8` is 255. There is no right answer that fits, so cint stopped the program at that multiplication and told you what happened. This is called a **fault**. Lesson 101-01's errors stop a program before it runs; a fault stops it while it runs, at the exact step that went wrong."
  },
  {
   "id": "cu-101-05:reading-the-fault-report",
   "edition": "CU-101.2",
   "title": "reading the fault report",
   "clauses": "",
   "url": "/university/101/05-runs-out/#reading-the-fault-report",
   "internal": 0,
   "content": "## reading the fault report\n\nThe report is long, but five parts of it explain the fault:\n\n| Line | What it tells you |\n|---|---|\n| `fault[E_OVERFLOW]: the exact result is outside the type's range` | What kind of fault. **Overflow** means the true answer is too large (or too small) for the type. |\n| `--> doubling.ci:5:7` and the picture | Where: line 5, character 7, the `*=`. |\n| `operation: mul.checked.u8` | What was being done: a checked multiplication (`mul`) of two `U8` numbers. |\n| `operand: U8 128` and `operand: U8 2` | The numbers it was working on. **Operands** are the numbers an operation takes. |\n| `exact: 256` and `limit: U8 255` | The true answer, and the most the type can hold. |\n\nThe other lines are there for tools that read faults, and you can skip them. `revision` is a fingerprint of the program's operations. `fuel-consumed` counts the steps the program took to run, which are not the loop's `step`. `stack-depth` (lesson 101-11 uses it), `source-map` and `address` matter in larger programs.\n\nNotice what did not happen: the program did not print a wrong number. Everything it printed before the fault is true."
  },
  {
   "id": "cu-101-05:the-same-fault-every-time",
   "edition": "CU-101.2",
   "title": "the same fault, every time",
   "clauses": "",
   "url": "/university/101/05-runs-out/#the-same-fault-every-time",
   "internal": 0,
   "content": "## the same fault, every time\n\nRun the program again, and again. You get the same eight lines and the same report, with the same numbers in it, every time. Run it on another computer and the output is the same down to the last character. In your browser the report is laid out differently, but it names the same fault, the same operation and the same numbers.\n\nA mistake that shows up every time, at the same place, with the numbers that caused it written down, is a mistake you can find and fix. It also means that you can run the old and new versions of a changed program and compare them line by line. Any difference then comes from your change."
  },
  {
   "id": "cu-101-05:fix-it",
   "edition": "CU-101.2",
   "title": "fix it",
   "clauses": "",
   "url": "/university/101/05-runs-out/#fix-it",
   "internal": 0,
   "content": "## fix it\n\nThere are two ways to fix a program that runs out, and each one means something different:\n\n1. **A bigger box**: change `U8` to `U16` in the line `U8 x = 1;`. Now all ten steps fit.\n2. **Fewer steps**: the doubling at the end of step 8 is the one that does not fit. If the program only needs the first seven numbers, change `1..=10` to `1..=7`. The last doubling is then 64 times 2, and 128 fits."
  },
  {
   "id": "cu-101-05:change-it",
   "edition": "CU-101.2",
   "title": "change it",
   "clauses": "",
   "url": "/university/101/05-runs-out/#change-it",
   "internal": 0,
   "content": "## change it\n\n1. Make the box `U16` and the loop `1..=20`, and delete the comment line. Before you run it: at which step will it stop, and what will `exact` and `limit` say?\n2. Triple instead of double, with `x *= 3;`. Which step stops a `U8` now?\n\n<details>\n<summary>where the U16 version stops</summary>\n\n```text\nstep 16: 32768\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> doubling.ci:4:7\n   ...\n   = operand: U16 32768\n   = operand: U16 2\n   = exact:   65536\n   = limit:   U16 65535\n```\n\n(The line number is 4 because the comment line is gone.)\n</details>\n\nTwo other programming languages, C and Python, behave differently. The same loop in C, with an 8-bit unsigned `x`, built with GCC 13.3 on Linux with no options, prints `step 9: 0` and `step 10: 0` and gives no sign that anything went wrong. Python's whole numbers have no fixed limit, so it prints 256 and 512."
  },
  {
   "id": "cu-101-05:when-it-goes-wrong",
   "edition": "CU-101.2",
   "title": "when it goes wrong",
   "clauses": "",
   "url": "/university/101/05-runs-out/#when-it-goes-wrong",
   "internal": 0,
   "content": "## when it goes wrong\n\nLesson 101-04's `as` is checked the same way. Moving 300 into a `U8`:\n\n```ci\nI64 big = 300;\nU8 small = big as U8;\n```\n\nstops with a different fault:\n\n```text\nfault[E_NARROW]: the value does not fit the destination type\n  --> narrow.ci:2:16\n   |\n 2 | U8 small = big as U8;\n   |                ^ as.checked.i64.u8\n   |\n   = operation: as.checked.i64.u8\n   = operand-count: 1\n   = operand: I64 300\n   = exact:   300\n   = limit:   U8 255\n   ...\n```\n\n**Narrow** means moving a number into a smaller type. The same five parts describe the fault: what kind of fault, where, which operation, the number it had and the limit it hit."
  },
  {
   "id": "cu-101-05:new-words",
   "edition": "CU-101.2",
   "title": "new words",
   "clauses": "",
   "url": "/university/101/05-runs-out/#new-words",
   "internal": 0,
   "content": "## new words\n\n[fault]({{GLOSSARY}}#fault), [overflow]({{GLOSSARY}}#overflow), [operand]({{GLOSSARY}}#operand), [fault report]({{GLOSSARY}}#fault-record), [loop]({{GLOSSARY}}#loop)\n\nNext: [lesson 101-06, true or false](06-true-or-false.md)."
  },
  {
   "id": "cu-101-06:cu-101-2",
   "edition": "CU-101.2",
   "title": "CU-101.2",
   "clauses": "",
   "url": "/university/101/06-true-or-false/",
   "internal": 0,
   "content": "# 101-06: true or false\n\n<a id=\"101-06\"></a>This is lesson 101-06 of CU-101.2, checked against cint 0.2.0.\n\n*You will ask questions whose answer is true or false, and make a program do one thing or another depending on the answer.*"
  },
  {
   "id": "cu-101-06:the-program",
   "edition": "CU-101.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/101/06-true-or-false/#the-program",
   "internal": 0,
   "content": "## the program\n\n```ci\nI64 year = 2024;\nBool leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\nif (leap) {\n    \"{year} is a leap year\\n\";\n} else {\n    \"{year} is not a leap year\\n\";\n}\n\"leap = {leap}\\n\";\n```\n\nRun it:\n\n```text\n2024 is a leap year\nleap = true\n```"
  },
  {
   "id": "cu-101-06:what-happened",
   "edition": "CU-101.2",
   "title": "what happened",
   "clauses": "",
   "url": "/university/101/06-true-or-false/#what-happened",
   "internal": 0,
   "content": "## what happened\n\n**A comparison is a question with a yes or no answer.** `year % 4 == 0` asks whether the remainder of `year` divided by 4 is 0. For 2024 the answer is yes, and cint writes yes as `true` and no as `false`. These are the comparisons:\n\n| Written | Asks |\n|---|---|\n| `a == b` | is `a` equal to `b`? |\n| `a != b` | is `a` different from `b`? |\n| `a < b` and `a <= b` | is `a` less than `b`, or less than or equal to it? |\n| `a > b` and `a >= b` | is `a` greater than `b`, or greater than or equal to it? |\n\nThe test for equality is two equals signs, `==`. One `=` puts a number into a variable, as in lesson 101-03.\n\n**`Bool` is the type of true and false.** A `Bool` variable holds one of the two answers. `leap` holds the answer to the whole question on the second line, and `{leap}` prints it as `true`.\n\n**`&&`, `||` and `!` combine answers.** `a && b` is true when both are true. `a || b` is true when at least one is. `!a` is true when `a` is false. The parentheses work as they do in arithmetic: the part inside them is worked out first. The second line reads \"divisible by 4, and either not divisible by 100 or divisible by 400\". That is the calendar's rule: 2024 and 2000 are leap years, and 1900 is not.\n\n**`if` chooses.** The lines in the braces after `if (leap)` run when `leap` is true. The lines after `else` run when it is false. Exactly one of the two prints. The question in the parentheses after `if` is called the **condition**.\n\n**`else if` asks another question.** When there are more than two choices, ask them one after another:\n\n```ci\nI64 t = 25;\nif (t < 10) {\n    \"cold\\n\";\n} else if (t < 20) {\n    \"mild\\n\";\n} else {\n    \"warm\\n\";\n}\n```\n\nThis prints `warm`. cint checks the conditions from the top and runs the first one that is true. If none is, it runs the `else`."
  },
  {
   "id": "cu-101-06:change-it",
   "edition": "CU-101.2",
   "title": "change it",
   "clauses": "",
   "url": "/university/101/06-true-or-false/#change-it",
   "internal": 0,
   "content": "## change it\n\n1. Set `year` to 1900. What do the two lines say?\n2. Set `year` to 2000 and run it again.\n3. Add an `else if` to the temperature example that prints `hot` from 30 up. Where can it go, and why?\n\n<details>\n<summary>what 1900 prints</summary>\n\n```text\n1900 is not a leap year\nleap = false\n```\n</details>\n\n<details>\n<summary>where the else if for hot can go</summary>\n\nIt can go anywhere between the `if` and the `else`:\n\n```ci\nI64 t = 35;\nif (t < 10) {\n    \"cold\\n\";\n} else if (t < 20) {\n    \"mild\\n\";\n} else if (t >= 30) {\n    \"hot\\n\";\n} else {\n    \"warm\\n\";\n}\n```\n\nThis prints `hot`. Nothing can come after the `else`, because the `else` takes every value the questions above it left.\n</details>"
  },
  {
   "id": "cu-101-06:when-it-goes-wrong",
   "edition": "CU-101.2",
   "title": "when it goes wrong",
   "clauses": "",
   "url": "/university/101/06-true-or-false/#when-it-goes-wrong",
   "internal": 0,
   "content": "## when it goes wrong\n\nOne `=` where two were meant is a common slip. cint stops it before the program runs:\n\n```ci\nI64 x = 5;\nif (x = 3) { \"three\\n\"; }\n```\n\n```text\nerror[C1041]: assignment in a condition\n  --> assign.ci:2:5\n   |\n 2 | if (x = 3) { \"three\\n\"; }\n   |     ^\n   |\n```\n\nA condition must be a `Bool`, too. A number on its own is not a question:\n\n```ci\nI64 year = 2024;\nif (year) {\n    \"yes\\n\";\n}\n```\n\n```text\nerror[C2002]: condition is not `Bool`\n  --> ifnum.ci:2:5\n   |\n 2 | if (year) {\n   |     ^\n   |\n```\n\nSome other languages, such as C and Python, take any number that is not 0 to mean true. In cint, a condition must be true or false, so a test on a number is written out, such as `year != 0`."
  },
  {
   "id": "cu-101-06:new-words",
   "edition": "CU-101.2",
   "title": "new words",
   "clauses": "",
   "url": "/university/101/06-true-or-false/#new-words",
   "internal": 0,
   "content": "## new words\n\n[Bool]({{GLOSSARY}}#bool), [comparison]({{GLOSSARY}}#comparison), [condition]({{GLOSSARY}}#condition)\n\nNext: [lesson 101-07, counting loops](07-counting-loops.md)."
  },
  {
   "id": "cu-101-07:cu-101-2",
   "edition": "CU-101.2",
   "title": "CU-101.2",
   "clauses": "",
   "url": "/university/101/07-counting-loops/",
   "internal": 0,
   "content": "# 101-07: counting loops\n\n<a id=\"101-07\"></a>This is lesson 101-07 of CU-101.2, checked against cint 0.2.0.\n\n*You will repeat lines a set number of times, put one loop inside another and line up numbers in rows.*"
  },
  {
   "id": "cu-101-07:the-program",
   "edition": "CU-101.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/101/07-counting-loops/#the-program",
   "internal": 0,
   "content": "## the program\n\n```ci\n// Times tables from 1 to 9.\nfor row in 1..=9 {\n    for col in 1..=9 {\n        \"{row * col:>3}\";\n    }\n    \"\\n\";\n}\n```\n\nRun it:\n\n```text\n  1  2  3  4  5  6  7  8  9\n  2  4  6  8 10 12 14 16 18\n  3  6  9 12 15 18 21 24 27\n  4  8 12 16 20 24 28 32 36\n  5 10 15 20 25 30 35 40 45\n  6 12 18 24 30 36 42 48 54\n  7 14 21 28 35 42 49 56 63\n  8 16 24 32 40 48 56 64 72\n  9 18 27 36 45 54 63 72 81\n```"
  },
  {
   "id": "cu-101-07:what-happened",
   "edition": "CU-101.2",
   "title": "what happened",
   "clauses": "",
   "url": "/university/101/07-counting-loops/#what-happened",
   "internal": 0,
   "content": "## what happened\n\n**A `for` loop counts.** Lesson 101-05 met the loop: `for row in 1..=9 { ... }` runs the lines between the braces once for each number from 1 to 9, and `row` holds that number. Each time through the lines is called a **pass**.\n\n**A range says where to start and stop.** There are two ways to write one:\n\n- `1..=9` means 1 up to 9, including 9.\n- `1..9` means 1 up to 9, leaving 9 out: 1 to 8.\n\nThe second kind is useful when counting starts at 0, as it does for lists in lesson 101-12. `0..7` gives seven numbers, 0 to 6.\n\n**A loop can hold another loop.** For each `row`, the inner loop runs through `col` from 1 to 9. The line `\"{row * col:>3}\";` runs 9 times 9, which is 81 times, once for each number in the table.\n\n**A print without `\\n` stays on the same line.** The inner loop prints nine numbers side by side. After it ends, `\"\\n\";` ends the line, and the outer loop goes on to the next row.\n\n**`:>3` sets a width.** `{row * col:>3}` prints the number in 3 characters, with spaces in front to fill them, so `4` prints as two spaces and a 4. This keeps the numbers lined up under each other. The `>` means the number goes at the right of its space."
  },
  {
   "id": "cu-101-07:change-it",
   "edition": "CU-101.2",
   "title": "change it",
   "clauses": "",
   "url": "/university/101/07-counting-loops/#change-it",
   "internal": 0,
   "content": "## change it\n\n1. Change `1..=9` to `1..9` in both loops. Which row disappears, and which number disappears from each row?\n2. Make the table go up to 12 in both loops. Look at the last rows: what goes wrong, and what width fixes it?\n3. Print only the squares, 1, 4, 9 and so on up to 81, one on each line. You need only one loop.\n\n<details>\n<summary>the last rows of the 12 table</summary>\n\n```text\n  9 18 27 36 45 54 63 72 81 90 99108\n 10 20 30 40 50 60 70 80 90100110120\n 11 22 33 44 55 66 77 88 99110121132\n 12 24 36 48 60 72 84 96108120132144\n```\n\nFrom row 9 on, numbers with three digits fill all 3 characters and run together. A width of 4 leaves a space between them.\n</details>"
  },
  {
   "id": "cu-101-07:when-it-goes-wrong",
   "edition": "CU-101.2",
   "title": "when it goes wrong",
   "clauses": "",
   "url": "/university/101/07-counting-loops/#when-it-goes-wrong",
   "internal": 0,
   "content": "## when it goes wrong\n\nA `for` loop's counter belongs to the loop, and the lines inside cannot change it:\n\n```ci\nfor row in 1..=3 {\n    row = 5;\n}\n```\n\n```text\nerror[C2052]: loop variable assigned\n  --> loopvar.ci:2:5\n   |\n 2 |     row = 5;\n   |     ^\n   |\n```\n\nA range also counts only upward. This loop never runs its lines, because 10 is past 1, so the program prints only `done`:\n\n```ci\nfor i in 10..1 {\n    \"{i}\\n\";\n}\n\"done\\n\";\n```\n\nLesson 101-08 shows a loop that can count down."
  },
  {
   "id": "cu-101-07:new-words",
   "edition": "CU-101.2",
   "title": "new words",
   "clauses": "",
   "url": "/university/101/07-counting-loops/#new-words",
   "internal": 0,
   "content": "## new words\n\n[width]({{GLOSSARY}}#width), [range]({{GLOSSARY}}#range), [pass]({{GLOSSARY}}#pass)\n\nNext: [lesson 101-08, loops that wait](08-loops-that-wait.md)."
  },
  {
   "id": "cu-101-08:cu-101-2",
   "edition": "CU-101.2",
   "title": "CU-101.2",
   "clauses": "",
   "url": "/university/101/08-loops-that-wait/",
   "internal": 0,
   "content": "# 101-08: loops that wait\n\n<a id=\"101-08\"></a>This is lesson 101-08 of CU-101.2, checked against cint 0.2.0.\n\n*You will write a loop that runs until something becomes true, however many passes that takes. You will also stop a loop early or skip a pass.*"
  },
  {
   "id": "cu-101-08:the-program",
   "edition": "CU-101.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/101/08-loops-that-wait/#the-program",
   "internal": 0,
   "content": "## the program\n\nHere is a rule: if a number is even, halve it; if it is odd, triple it and add one. Start from 27 and repeat until the number reaches 1:\n\n```ci\n// Halve it if even, triple it and add one if odd, until it reaches 1.\nI64 start = 27;\nI64 n = start;\nI64 steps = 0;\nI64 highest = n;\nwhile (n != 1) {\n    if (n % 2 == 0) {\n        n = n / 2;\n    } else {\n        n = 3 * n + 1;\n    }\n    steps += 1;\n    if (n > highest) { highest = n; }\n}\n\"{start} reaches 1 in {steps} steps, climbing as high as {highest}\\n\";\n```\n\nRun it:\n\n```text\n27 reaches 1 in 111 steps, climbing as high as 9232\n```\n\nThe numbers rise and fall like a hailstone in a storm cloud before they come down to 1, which is why the list of numbers is called a hailstone sequence. Every positive whole number anyone has tried comes down to 1 in the end, but nobody has proved that every one does."
  },
  {
   "id": "cu-101-08:what-happened",
   "edition": "CU-101.2",
   "title": "what happened",
   "clauses": "",
   "url": "/university/101/08-loops-that-wait/#what-happened",
   "internal": 0,
   "content": "## what happened\n\n**`while` repeats as long as its condition is true.** Before each pass, cint checks `n != 1`. While it is true, the lines in the braces run again. When `n` reaches 1, the condition is false and the program goes on to the line after the loop. Nobody knows in advance how many passes that takes: for 27 it is 111. That is the difference from lesson 101-07's `for`, which counts a set number of passes.\n\n**Something inside the loop must change the condition.** Each pass changes `n`. A loop whose condition never becomes false runs until something else stops it.\n\n**`steps` and `highest` keep a running tally.** `steps += 1;` counts the passes. `highest` starts at 27, and whenever `n` climbs above it, `highest` takes the new value.\n\n**A `while` loop can count down.** A `for` range only counts up, so counting down is a job for `while`:\n\n```ci\nI64 n = 5;\nwhile (n > 0) {\n    \"{n}\\n\";\n    n -= 1;\n}\n\"liftoff\\n\";\n```\n\nThis prints 5, 4, 3, 2 and 1, one to a line, then `liftoff`."
  },
  {
   "id": "cu-101-08:stopping-early-skipping-a-pass",
   "edition": "CU-101.2",
   "title": "stopping early, skipping a pass",
   "clauses": "",
   "url": "/university/101/08-loops-that-wait/#stopping-early-skipping-a-pass",
   "internal": 0,
   "content": "## stopping early, skipping a pass\n\n`break;` leaves a loop at once. `continue;` skips the rest of the current pass and goes on to the next one:\n\n```ci\n// The first power of 2 above 1000.\nI64 x = 1;\nwhile (true) {\n    x *= 2;\n    if (x > 1_000) {\n        break;\n    }\n}\n\"first power of 2 above 1000: {x}\\n\";\n\n// The numbers from 1 to 10 that 3 does not divide.\nfor n in 1..=10 {\n    if (n % 3 == 0) {\n        continue;\n    }\n    \"{n} \";\n}\n\"\\n\";\n```\n\n```text\nfirst power of 2 above 1000: 1024\n1 2 4 5 7 8 10 \n```\n\n`while (true)` would run forever, so the `break` inside it is the only way out. In the second loop, `continue` skips the print for 3, 6 and 9."
  },
  {
   "id": "cu-101-08:change-it",
   "edition": "CU-101.2",
   "title": "change it",
   "clauses": "",
   "url": "/university/101/08-loops-that-wait/#change-it",
   "internal": 0,
   "content": "## change it\n\n1. Set `start` to 7. How many steps does it take, and how high does it climb?\n2. Set `start` to 97. Which takes more steps, 27 or 97?\n3. Change the countdown to count down from 10 in twos: 10, 8, 6, 4, 2.\n\n<details>\n<summary>what 7 prints</summary>\n\n```text\n7 reaches 1 in 16 steps, climbing as high as 52\n```\n</details>"
  },
  {
   "id": "cu-101-08:when-it-goes-wrong",
   "edition": "CU-101.2",
   "title": "when it goes wrong",
   "clauses": "",
   "url": "/university/101/08-loops-that-wait/#when-it-goes-wrong",
   "internal": 0,
   "content": "## when it goes wrong\n\nLeave out the halving by mistake, so that every pass triples and adds one:\n\n```ci\nI64 n = 27;\nI64 steps = 0;\nwhile (n != 1) {\n    n = 3 * n + 1;\n    steps += 1;\n}\n```\n\n`n` only grows, so it never reaches 1. The same loop written in Python 3.13 ran until it was stopped after 10 seconds, because Python's numbers can grow until the computer runs out of memory. In cint, the number runs out of room on pass 37 and the program stops with a fault:\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> runaway.ci:4:11\n   |\n 4 |     n = 3 * n + 1;\n   |           ^ mul.checked.i64\n   |\n   = operation: mul.checked.i64\n   = operand-count: 2\n   = operand: I64 3\n   = operand: I64 4127602470667475827\n   = exact:   12382807412002427481\n   = limit:   I64 9223372036854775807\n   ...\n```\n\nA loop that starts with a true condition, never changes anything its condition reads and has no `break` runs forever. To stop a program running in a terminal, press **Ctrl+C**. To stop one running in the browser, reload the page."
  },
  {
   "id": "cu-101-08:new-words",
   "edition": "CU-101.2",
   "title": "new words",
   "clauses": "",
   "url": "/university/101/08-loops-that-wait/#new-words",
   "internal": 0,
   "content": "## new words\n\n[while loop]({{GLOSSARY}}#while), [break]({{GLOSSARY}}#break), [continue]({{GLOSSARY}}#continue)\n\nNext: [lesson 101-09, choosing among many](09-choosing-among-many.md)."
  },
  {
   "id": "cu-101-09:cu-101-2",
   "edition": "CU-101.2",
   "title": "CU-101.2",
   "clauses": "",
   "url": "/university/101/09-choosing-among-many/",
   "internal": 0,
   "content": "# 101-09: choosing among many\n\n<a id=\"101-09\"></a>This is lesson 101-09 of CU-101.2, checked against cint 0.2.0.\n\n*You will sort a number into one of several groups with `switch`, using ranges of numbers, and make sure every number lands somewhere.*"
  },
  {
   "id": "cu-101-09:the-program",
   "edition": "CU-101.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/101/09-choosing-among-many/#the-program",
   "internal": 0,
   "content": "## the program\n\n```ci\nfor tens in 4..=10 {\n    I64 score = tens * 10;\n    \"score {score:>3}: \";\n    switch (score) {\n        case 90..=100: \"A\\n\";\n        case 80..=89: \"B\\n\";\n        case 70..=79: \"C\\n\";\n        case 60..=69: \"D\\n\";\n        default: \"F\\n\";\n    }\n}\n```\n\nRun it:\n\n```text\nscore  40: F\nscore  50: F\nscore  60: D\nscore  70: C\nscore  80: B\nscore  90: A\nscore 100: A\n```"
  },
  {
   "id": "cu-101-09:what-happened",
   "edition": "CU-101.2",
   "title": "what happened",
   "clauses": "",
   "url": "/university/101/09-choosing-among-many/#what-happened",
   "internal": 0,
   "content": "## what happened\n\n**The loop makes the scores.** `tens` counts from 4 to 10, and `score` is ten times `tens`: 40, 50 and so on up to 100. A range in cint 0.2.0 counts by ones only, so a loop that needs steps of ten counts by ones and multiplies.\n\n**`switch` sorts one number into cases.** `switch (score)` looks at `score` once and runs the lines of the case that holds it. Each **case** names a number or a range of numbers:\n\n- `case 90..=100:` holds every score from 90 to 100.\n- `case 80..=89:` holds 80 to 89, `case 70..=79:` holds 70 to 79 and `case 60..=69:` holds 60 to 69.\n- `default:` holds every number no other case holds.\n\n**Only one case runs.** When the lines of a case are done, the `switch` is done, and the program goes on after its closing brace. Here each case prints one letter and the line ends.\n\n**Every number must have a place.** A `switch` without `default` must have a case for every possible value. With `default` at the end, every number has somewhere to go.\n\n**A `switch` can do what `else if` does.** This program could be written as a chain of `if` and `else if`, as in lesson 101-06. A `switch` is shorter when every question is about the same number, and cint checks that its ranges do not overlap."
  },
  {
   "id": "cu-101-09:change-it",
   "edition": "CU-101.2",
   "title": "change it",
   "clauses": "",
   "url": "/university/101/09-choosing-among-many/#change-it",
   "internal": 0,
   "content": "## change it\n\n1. Make the loop count from 0 to 10 instead. What do scores 0 to 30 get?\n2. Add a grade `E` for scores from 50 to 59.\n3. Give exactly 100 the grade `A+`. What else must change, and why?\n\n<details>\n<summary>what 3 needs</summary>\n\n`case 100: \"A+\\n\";` added above the A case is refused, because 100 is already in `case 90..=100:` and two cases cannot hold the same number. cint points at the range in the A case that overlaps the new one:\n\n```text\nerror[C4021]: `switch` rule\n  --> aplus.ci:6:14\n   |\n 6 |         case 90..=100: \"A\\n\";\n   |              ^\n   |\n```\n\nChange the A range to `90..=99` as well.\n</details>"
  },
  {
   "id": "cu-101-09:when-it-goes-wrong",
   "edition": "CU-101.2",
   "title": "when it goes wrong",
   "clauses": "",
   "url": "/university/101/09-choosing-among-many/#when-it-goes-wrong",
   "internal": 0,
   "content": "## when it goes wrong\n\nLeave out `default`, and scores outside 60 to 100 have nowhere to go. cint refuses the program before it runs:\n\n```ci\nI64 score = 75;\nswitch (score) {\n    case 90..=100: \"A\\n\";\n    case 80..=89: \"B\\n\";\n    case 70..=79: \"C\\n\";\n    case 60..=69: \"D\\n\";\n}\n```\n\n```text\nerror[C4020]: `switch` rule\n  --> nodefault.ci:2:1\n   |\n 2 | switch (score) {\n   | ^\n   |\n```\n\nA range in a case must be written with `..=`. `case 90..100:` is refused with error C4022."
  },
  {
   "id": "cu-101-09:new-words",
   "edition": "CU-101.2",
   "title": "new words",
   "clauses": "",
   "url": "/university/101/09-choosing-among-many/#new-words",
   "internal": 0,
   "content": "## new words\n\n[switch]({{GLOSSARY}}#switch), [case]({{GLOSSARY}}#case), [default]({{GLOSSARY}}#default)\n\nNext: [lesson 101-10, functions](10-functions.md)."
  },
  {
   "id": "cu-101-10:cu-101-2",
   "edition": "CU-101.2",
   "title": "CU-101.2",
   "clauses": "",
   "url": "/university/101/10-functions/",
   "internal": 0,
   "content": "# 101-10: functions\n\n<a id=\"101-10\"></a>This is lesson 101-10 of CU-101.2, checked against cint 0.2.0.\n\n*You will give a calculation a name, use it as often as you like with different numbers and start a program from a function called `main`.*"
  },
  {
   "id": "cu-101-10:the-program",
   "edition": "CU-101.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/101/10-functions/#the-program",
   "internal": 0,
   "content": "## the program\n\n```ci\nI64 area(I64 width, I64 height) {\n    return width * height;\n}\n\nI64 larger(I64 a, I64 b) {\n    if (a > b) { return a; }\n    return b;\n}\n\nvoid main() {\n    I64 kitchen = area(4, 3);\n    I64 bedroom = area(5, 4);\n    \"kitchen {kitchen}, bedroom {bedroom}, larger {larger(kitchen, bedroom)}\\n\";\n}\n```\n\nRun it:\n\n```text\nkitchen 12, bedroom 20, larger 20\n```"
  },
  {
   "id": "cu-101-10:what-happened",
   "edition": "CU-101.2",
   "title": "what happened",
   "clauses": "",
   "url": "/university/101/10-functions/#what-happened",
   "internal": 0,
   "content": "## what happened\n\n**A function is a calculation with a name.** The first three lines make a **function** called `area`. Read its first line from left to right:\n\n- `I64` is the type of the answer it gives back.\n- `area` is its name.\n- `(I64 width, I64 height)` are its **parameters**: the numbers it needs, each with a type and a name.\n\nThe lines in the braces are its body. `return width * height;` works out the answer and gives it back.\n\n**Calling a function runs it.** `area(4, 3)` runs `area` with `width` set to 4 and `height` set to 3, and the call is replaced by the answer, 12. The numbers in a call are its **arguments**, and they fill the parameters in order. `area(5, 4)` runs the same lines again with different numbers. A function is written once and used as often as you need.\n\n**A function can make choices.** `larger` returns `a` if it is bigger and `b` otherwise. A `return` ends the function at once, so when `a > b`, the last line never runs.\n\n**`main` is where the program starts.** Until now, every program ran from its first line to its last. A program can instead start from a function called `main`, and cint runs `main` when the program starts. `void` in front of `main` means it gives back no answer. From lesson 101-12 on, programs start from `main`, because in cint 0.2.0 a list of numbers can only be made inside a function.\n\n**Each function has its own names.** `width` and `height` exist only inside `area`, and `kitchen` exists only inside `main`. Two functions can use the same name for different things without mixing them up."
  },
  {
   "id": "cu-101-10:change-it",
   "edition": "CU-101.2",
   "title": "change it",
   "clauses": "",
   "url": "/university/101/10-functions/#change-it",
   "internal": 0,
   "content": "## change it\n\n1. Add a room `hall` that is 6 by 2, and print its area.\n2. Write a function `perimeter` that gives back the distance around a room: twice the width plus twice the height. Print the kitchen's perimeter.\n3. Use `larger` twice in one line to print the largest of three rooms.\n\n<details>\n<summary>one way to write perimeter</summary>\n\n```ci\nI64 perimeter(I64 width, I64 height) {\n    return 2 * width + 2 * height;\n}\n```\n\n`\"{perimeter(4, 3)}\\n\";` prints 14. A program that has functions but no `main` runs its other lines from the top, so this line can sit below the function.\n</details>"
  },
  {
   "id": "cu-101-10:when-it-goes-wrong",
   "edition": "CU-101.2",
   "title": "when it goes wrong",
   "clauses": "",
   "url": "/university/101/10-functions/#when-it-goes-wrong",
   "internal": 0,
   "content": "## when it goes wrong\n\nA call needs one argument for each parameter. `area(3)` leaves out the height, and cint says the arguments are wrong. The same error code is also used for fields, which 101 does not teach:\n\n```ci\nI64 area(I64 w, I64 h) { return w * h; }\nvoid main() { \"{area(3)}\\n\"; }\n```\n\n```text\nerror[C2022]: wrong fields or arguments\n  --> argcount.ci:2:17\n   |\n 2 | void main() { \"{area(3)}\\n\"; }\n   |                 ^\n   |\n```\n\nA misspelled name is not a function cint knows. Calling `are` instead of `area` gives the message from lesson 101-03:\n\n```ci\nI64 area(I64 width, I64 height) {\n    return width * height;\n}\nvoid main() {\n    \"{are(4, 3)}\\n\";\n}\n```\n\n```text\nerror[C3005]: undefined or unusable name\n  --> unknownfn.ci:5:7\n   |\n 5 |     \"{are(4, 3)}\\n\";\n   |       ^\n   |\n```"
  },
  {
   "id": "cu-101-10:new-words",
   "edition": "CU-101.2",
   "title": "new words",
   "clauses": "",
   "url": "/university/101/10-functions/#new-words",
   "internal": 0,
   "content": "## new words\n\n[function]({{GLOSSARY}}#function), [parameter]({{GLOSSARY}}#parameter), [argument]({{GLOSSARY}}#argument), [return]({{GLOSSARY}}#return)\n\nNext: [lesson 101-11, functions that call themselves](11-functions-that-call-themselves.md)."
  },
  {
   "id": "cu-101-11:cu-101-2",
   "edition": "CU-101.2",
   "title": "CU-101.2",
   "clauses": "",
   "url": "/university/101/11-functions-that-call-themselves/",
   "internal": 0,
   "content": "# 101-11: functions that call themselves\n\n<a id=\"101-11\"></a>This is lesson 101-11 of CU-101.2, checked against cint 0.2.0.\n\n*You will write a function that uses itself to get its answer. You will watch it reach the edge of `I64` and read where the fault report says the call came from.*"
  },
  {
   "id": "cu-101-11:the-program",
   "edition": "CU-101.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/101/11-functions-that-call-themselves/#the-program",
   "internal": 0,
   "content": "## the program\n\nThe factorial of a number multiplies every whole number from 1 up to it: the factorial of 4 is `1 * 2 * 3 * 4`, which is 24. Mathematicians write it as 4 followed by an exclamation mark. cint has no factorial sign, so in this program the mark is only text that the program prints.\n\n```ci\nI64 factorial(I64 n) {\n    if (n <= 1) { return 1; }\n    return n * factorial(n - 1);\n}\n\nvoid main() {\n    for n in 1..=25 {\n        \"{n:>2}! = {factorial(n)}\\n\";\n    }\n}\n```\n\nRun it:\n\n```text\n 1! = 1\n 2! = 2\n 3! = 6\n 4! = 24\n 5! = 120\n 6! = 720\n 7! = 5040\n 8! = 40320\n 9! = 362880\n10! = 3628800\n11! = 39916800\n12! = 479001600\n13! = 6227020800\n14! = 87178291200\n15! = 1307674368000\n16! = 20922789888000\n17! = 355687428096000\n18! = 6402373705728000\n19! = 121645100408832000\n20! = 2432902008176640000\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> factorial.ci:3:14\n   |\n 3 |     return n * factorial(n - 1);\n   |              ^ mul.checked.i64\n   |\n   = operation: mul.checked.i64\n   = operand-count: 2\n   = operand: I64 21\n   = operand: I64 2432902008176640000\n   = exact:   51090942171709440000\n   = limit:   I64 9223372036854775807\n   = revision: c0baa23c76db8b75f2ee6e08b38a56964c2051f06b6e45554fefca759b36e4ba\n   = source-map: none\n   = address: none\n   = stack-depth: 1\n   = called from: factorial.ci:8:21\n   = fuel-consumed: 253 (not part of the fault record)\n   = state: the program stopped; stdout holds what it wrote before the fault\n```"
  },
  {
   "id": "cu-101-11:what-happened",
   "edition": "CU-101.2",
   "title": "what happened",
   "clauses": "",
   "url": "/university/101/11-functions-that-call-themselves/#what-happened",
   "internal": 0,
   "content": "## what happened\n\n**A function may call itself.** The factorial of 4 is 4 times the factorial of 3, and the factorial of 3 is 3 times the factorial of 2. The second line of `factorial` says exactly that: the factorial of `n` is `n` times the factorial of `n - 1`. A function that calls itself is called **recursive**.\n\n**It needs a place to stop.** `if (n <= 1) { return 1; }` answers the smallest case right away, without calling `factorial` again. Follow `factorial(3)`:\n\n1. `factorial(3)` needs `3 * factorial(2)`, so it calls `factorial(2)` and waits.\n2. `factorial(2)` needs `2 * factorial(1)`, so it calls `factorial(1)` and waits.\n3. `factorial(1)` returns 1 at once.\n4. `factorial(2)` can now finish: `2 * 1` is 2.\n5. `factorial(3)` can now finish: `3 * 2` is 6.\n\n**Factorials grow fast.** The factorial of 20 is 2432902008176640000, which still fits in an `I64`. The factorial of 21 is 21 times that, 51090942171709440000, more than five times the largest `I64`. So the multiplication for 21 faulted, and the program printed 20 lines and stopped.\n\n**The report says where the call came from.** `--> factorial.ci:3:14` is where the fault happened: the `*` in `factorial`. `called from: factorial.ci:8:21` is the line that called `factorial`: line 8, in `main`, at the `factorial(n)` in the print. The calls in progress at any moment are called the **call stack**. `stack-depth: 1` counts the calls in progress besides `main`: here only `factorial(21)`, the call that faulted. The calls for 20, 19 and the rest had already returned their answers."
  },
  {
   "id": "cu-101-11:change-it",
   "edition": "CU-101.2",
   "title": "change it",
   "clauses": "",
   "url": "/university/101/11-functions-that-call-themselves/#change-it",
   "internal": 0,
   "content": "## change it\n\n1. Make the loop stop at 20. Does the program finish now?\n2. Write a recursive function `sum_to(n)` that adds 1 + 2 + ... + n, and print `sum_to(100)`.\n3. The largest `U64` is 18446744073709551615, about twice the largest `I64`. Would the factorial of 21 fit in a `U64`? Work it out from the numbers in the report.\n\n<details>\n<summary>what sum_to(100) prints</summary>\n\nIt prints 5050. One way to write it:\n\n```ci\nI64 sum_to(I64 n) {\n    if (n == 0) { return 0; }\n    return n + sum_to(n - 1);\n}\n```\n</details>"
  },
  {
   "id": "cu-101-11:when-it-goes-wrong",
   "edition": "CU-101.2",
   "title": "when it goes wrong",
   "clauses": "",
   "url": "/university/101/11-functions-that-call-themselves/#when-it-goes-wrong",
   "internal": 0,
   "content": "## when it goes wrong\n\nLeave out the stopping line, and `factorial` calls itself for 5, 4, 3, 2, 1, 0, -1 and on without end:\n\n```ci\nI64 factorial(I64 n) {\n    return n * factorial(n - 1);\n}\nvoid main() {\n    \"{factorial(5)}\\n\";\n}\n```\n\nA program may have at most 256 calls in progress at once, and `main` counts as one of them. This program passes that limit and stops with a different fault:\n\n```text\nfault[E_DEPTH]: call depth limit exceeded\n  --> nobase.ci:2:16\n   |\n 2 |     return n * factorial(n - 1);\n   |                ^ call.enter\n   |\n   = operation: call.enter\n   = operand-count: 0\n   = exact:   none\n   = limit:   I64 256\n   ...\n   = stack-depth: 255\n```\n\nThe full report lists 255 `called from` lines, one for each call in progress besides `main`. A recursive function needs a stopping case that every call eventually reaches."
  },
  {
   "id": "cu-101-11:new-words",
   "edition": "CU-101.2",
   "title": "new words",
   "clauses": "",
   "url": "/university/101/11-functions-that-call-themselves/#new-words",
   "internal": 0,
   "content": "## new words\n\n[recursion]({{GLOSSARY}}#recursion), [call stack]({{GLOSSARY}}#call-stack)\n\nNext: [lesson 101-12, lists](12-lists.md)."
  },
  {
   "id": "cu-101-12:cu-101-2",
   "edition": "CU-101.2",
   "title": "CU-101.2",
   "clauses": "",
   "url": "/university/101/12-lists/",
   "internal": 0,
   "content": "# 101-12: lists\n\n<a id=\"101-12\"></a>This is lesson 101-12 of CU-101.2, checked against cint 0.2.0.\n\n*You will keep a week of numbers under one name, reach each one by its position and see what cint does when a position does not exist.*"
  },
  {
   "id": "cu-101-12:the-program",
   "edition": "CU-101.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/101/12-lists/#the-program",
   "internal": 0,
   "content": "## the program\n\n```ci\nvoid main() {\n    I64[7] temps = [12, 15, 11, 18, 21, 19, 16];\n    \"there are {len(temps)} days\\n\";\n    \"Monday was {temps[0]}, Sunday was {temps[6]}\\n\";\n    temps[2] = 13;\n    \"Wednesday, corrected: {temps[2]}\\n\";\n    \"the day after Sunday: {temps[7]}\\n\";\n}\n```\n\nRun it:\n\n```text\nthere are 7 days\nMonday was 12, Sunday was 16\nWednesday, corrected: 13\nfault[E_BOUNDS]: index out of bounds\n  --> temps.ci:7:34\n   |\n 7 |     \"the day after Sunday: {temps[7]}\\n\";\n   |                                  ^ index.checked.i64\n   |\n   = operation: index.checked.i64\n   = operand-count: 1\n   = operand: I64 7\n   = exact:   none\n   = limit:   I64 7\n   = revision: 9eb95af35c842e3f063ac00a7cb32e13cd838a461e5eb04b6d46c5eaf40c8c4b\n   = source-map: none\n   = address: none\n   = stack-depth: 0\n   = fuel-consumed: 1 (not part of the fault record)\n   = state: the program stopped; stdout holds what it wrote before the fault\n```"
  },
  {
   "id": "cu-101-12:what-happened",
   "edition": "CU-101.2",
   "title": "what happened",
   "clauses": "",
   "url": "/university/101/12-lists/#what-happened",
   "internal": 0,
   "content": "## what happened\n\n**A list holds several numbers under one name.** `I64[7] temps` makes a list of seven `I64` numbers called `temps`. In cint a list of a fixed length is called an **array**. The `[12, 15, 11, 18, 21, 19, 16]` after the `=` gives the seven numbers to start with, in order: a week of noon temperatures in degrees Celsius, from Monday to Sunday.\n\n**Positions count from 0.** `temps[0]` is the first number, 12, and `temps[6]` is the seventh and last, 16. The number in the square brackets is called the **index**. Other programming languages, such as C and Python, count positions from 0 too. An array of 7 has the indexes 0 to 6.\n\n**`len` gives the length.** `len(temps)` is 7. A loop over `0..len(temps)` visits every index, 0 to 6, as lesson 101-07 explained for `..`.\n\n**One number can change.** `temps[2] = 13;` replaces the third number, Wednesday's 11, with 13. The rest stay as they were.\n\n**There is no eighth day.** `temps[7]` asks for an index the array does not have. cint stopped the program with an **index out of bounds** fault at line 7, at `temps[7]`. The report says the index was 7 and the limit is 7, meaning the index must be less than 7. The three lines before it printed, and nothing after it did."
  },
  {
   "id": "cu-101-12:change-it",
   "edition": "CU-101.2",
   "title": "change it",
   "clauses": "",
   "url": "/university/101/12-lists/#change-it",
   "internal": 0,
   "content": "## change it\n\n1. Print the average temperature of the week with a loop that adds up every day.\n2. Find the warmest day and print its index. You need a variable that remembers the best so far, as `highest` did in lesson 101-08.\n3. Delete the last print line, so the program finishes, then print all seven days, one to a line, with a loop.\n\n<details>\n<summary>one way to print the average</summary>\n\nPut these lines before the last print line, so they run before the fault:\n\n```ci\n    I64 total = 0;\n    for day in 0..len(temps) {\n        total += temps[day];\n    }\n    \"average: {total / len(temps)}\\n\";\n```\n\nWith Wednesday corrected to 13, the week adds up to 114, and this prints `average: 16` before the fault report. Division of whole numbers drops the remainder, as in lesson 101-02.\n</details>"
  },
  {
   "id": "cu-101-12:when-it-goes-wrong",
   "edition": "CU-101.2",
   "title": "when it goes wrong",
   "clauses": "",
   "url": "/university/101/12-lists/#when-it-goes-wrong",
   "internal": 0,
   "content": "## when it goes wrong\n\nThe index can come from a variable, and cint checks it the same way when the program runs:\n\n```ci\nvoid main() {\n    I64[7] temps = [12, 15, 11, 18, 21, 19, 16];\n    I64 day = 7;\n    \"the day after Sunday: {temps[day]}\\n\";\n}\n```\n\n```text\nfault[E_BOUNDS]: index out of bounds\n  --> index.ci:4:34\n   |\n 4 |     \"the day after Sunday: {temps[day]}\\n\";\n   |                                  ^ index.checked.i64\n   |\n   = operation: index.checked.i64\n   = operand-count: 1\n   = operand: I64 7\n   ...\n```\n\nIn C, reading past the end of an array is undefined behavior: the program can quietly give back whatever number is stored next to it, or crash. In cint, every index is checked.\n\nThe starting numbers must match the length. `I64[7] temps = [12, 15];` gives two numbers for seven places, and cint refuses it with error C2011. In cint 0.2.0 an array can only be made inside a function, so this lesson's program starts from `main`, as lesson 101-10 explained."
  },
  {
   "id": "cu-101-12:new-words",
   "edition": "CU-101.2",
   "title": "new words",
   "clauses": "",
   "url": "/university/101/12-lists/#new-words",
   "internal": 0,
   "content": "## new words\n\n[array]({{GLOSSARY}}#array), [index]({{GLOSSARY}}#index), [out of bounds]({{GLOSSARY}}#bounds)\n\nBack to [101: first programs](README.md)."
  },
  {
   "id": "cu-101-overview:cu-101-2",
   "edition": "CU-101.2",
   "title": "CU-101.2",
   "clauses": "",
   "url": "/university/101/",
   "internal": 0,
   "content": "# 101: first programs\n\nThis page is CU-101.2, edition 2 of 101: first programs, checked against cint 0.2.0 and released on {{RELEASE_DATE}}.\n\nThis edition is current. Every program in it was run on cint 0.2.0 with each of four C compilers (GCC, Clang, MSVC and Apple Clang), and every output comes from those runs. The text of this edition does not change after its release. Corrections that change nothing a reader would see are listed in [ERRATA.md](../ERRATA.md). A new edition is published when a release changes what a lesson shows or when lessons are added. Lesson identifiers are the same in every edition and are never reused.\n\n101 is for people who have never written a program. It needs a browser and nothing else. To run the programs on your own computer as well, [set up cint](../setup.md). A new word is explained where it first appears and linked to the [glossary]({{GLOSSARY}})."
  },
  {
   "id": "cu-101-overview:lessons",
   "edition": "CU-101.2",
   "title": "lessons",
   "clauses": "",
   "url": "/university/101/#lessons",
   "internal": 0,
   "content": "## lessons\n\n| Lesson | Title | You build |\n|---|---|---|\n| [101-00](00-welcome.md) | welcome | your first program |\n| [101-01](01-printing.md) | printing | a house drawn in characters |\n| [101-02](02-arithmetic.md) | arithmetic | minutes in a week |\n| [101-03](03-names.md) | names for values | a coin jar |\n| [101-04](04-sizes.md) | numbers have sizes | a table of sizes |\n| [101-05](05-runs-out.md) | when a number runs out | a doubling that stops |\n| [101-06](06-true-or-false.md) | true or false | a leap-year test |\n| [101-07](07-counting-loops.md) | counting loops | the times tables |\n| [101-08](08-loops-that-wait.md) | loops that wait | a hailstone sequence |\n| [101-09](09-choosing-among-many.md) | choosing among many | letter grades |\n| [101-10](10-functions.md) | functions | the areas of two rooms |\n| [101-11](11-functions-that-call-themselves.md) | functions that call themselves | a table of factorials |\n| [101-12](12-lists.md) | lists | a week of temperatures |"
  },
  {
   "id": "cu-101-overview:changes-since-the-previous-edition",
   "edition": "CU-101.2",
   "title": "changes since the previous edition",
   "clauses": "",
   "url": "/university/101/#changes-since-the-previous-edition",
   "internal": 0,
   "content": "## changes since the previous edition\n\nCU-101.2 replaces CU-101.1, which stays readable.\n\n- Lessons 101-06 to 101-12 are new.\n- Every lesson's first line names CU-101.2.\n- 101-05 gains the sentence \"Lesson 101-07 is all about loops.\" after the one about `for`, and a pointer to 101-11 after the `stack-depth` line. It now ends with a link to 101-06.\n\nNo program's output changed."
  },
  {
   "id": "cu-201-00:cu-201-2",
   "edition": "CU-201.2",
   "title": "CU-201.2",
   "clauses": "",
   "url": "/university/201/00-start-here/",
   "internal": 0,
   "content": "# 201-00: start here\n\n<a id=\"201-00\"></a>This is lesson 201-00 of CU-201.2, checked against cint 0.2.0.\n\n*You will set up cint, meet its four commands and see the C it emits from a small program.*\n\nThis course is for readers who already program in C, Python or a language like them. If you have never programmed, start with [101](../101/00-welcome.md) instead."
  },
  {
   "id": "cu-201-00:what-cint-is",
   "edition": "CU-201.2",
   "title": "what cint is",
   "clauses": "",
   "url": "/university/201/00-start-here/#what-cint-is",
   "internal": 0,
   "content": "## what cint is\n\ncint is a language for whole numbers. Its signed integer types run from 8 to 1024 bits and its unsigned ones from 8 to 512. It has fixed-point types for fractions and no floating point. Every plain operator is checked. When `+`, `-`, `*`, `/`, a shift or a conversion has no exact result in its type, the program stops with a fault that names the operation, the operands, the exact result and the limit. Where wrapping or saturating is what a program means, it says so with a wrapping operator such as `+%` or a saturating one such as `+|`, and those never fault.\n\nThree tools run cint programs:\n\n- **`cint`**, the command you build in the next section. It translates a program to C17, compiles that with your C compiler (GCC, Clang, MSVC or Apple Clang) and runs it. The compiler inside it, `cintc`, is written in cint and compiles itself.\n- **The reference**, an implementation of the language in Python that defines what every program means. On a four-core Intel Xeon at 2.10 GHz, finding the number below 1,000,000 with the longest Collatz path did not finish in five minutes on the reference, while `cint run` took under one second. The browser workspace on [integerc.dev](https://integerc.dev) runs it.\n- **The interpreter**, which runs the same programs without a C compiler. [Lesson 201-06](06-workbench.md) uses it.\n\nFor every program in this course, all three print the same bytes. If they ever disagree, the reference decides."
  },
  {
   "id": "cu-201-00:set-up",
   "edition": "CU-201.2",
   "title": "set up",
   "clauses": "",
   "url": "/university/201/00-start-here/#set-up",
   "internal": 0,
   "content": "## set up\n\nFollow [set up cint on your computer](../setup.md). It needs Python 3.12 or later and a C compiler, and two commands build `cint` and its debugging tools. It covers VS Code and plain text editors."
  },
  {
   "id": "cu-201-00:the-four-commands",
   "edition": "CU-201.2",
   "title": "the four commands",
   "clauses": "",
   "url": "/university/201/00-start-here/#the-four-commands",
   "internal": 0,
   "content": "## the four commands\n\nSave this as `squares.ci`:\n\n```ci\nI64 square(I64 x) {\n    return x * x;\n}\n\nvoid main() {\n    for i in 1..=5 {\n        \"{i} squared is {square(i)}\\n\";\n    }\n}\n\ntest \"small squares\" {\n    assert(square(3) == 9);\n    assert(square(-4) == 16);\n}\n\ntest \"the largest square that fits\" {\n    assert(square(3_037_000_499) == 9_223_372_030_926_249_001);\n}\n\ntest \"one past it faults\" expect_fault E_OVERFLOW {\n    _ = square(3_037_000_500);\n}\n```\n\n`cint run` builds the program in a cache and runs `main`:\n\n```text\n$ cint run squares.ci\n1 squared is 1\n2 squared is 4\n3 squared is 9\n4 squared is 16\n5 squared is 25\n```\n\n`cint test` runs every `test` block. The third test passes because the multiplication faults: 3037000500 squared is 9223372037000250000, which is more than `I64.max`, 9223372036854775807.\n\n```text\n$ cint test squares.ci\ntest squares.ci:11 \"small squares\" ... ok\ntest squares.ci:16 \"the largest square that fits\" ... ok\ntest squares.ci:20 \"one past it faults\" ... ok\n3 of 3 tests passed\n```\n\n`cint build` writes an executable that runs without cint:\n\n```text\n$ cint build squares.ci\nbuilt: ./build/squares\n```\n\n`cint emit-c` writes the C. Here is `square`, as emitted:\n\n```c\nstatic bool ci_7_squares_6_square(cint_ctx *ctx, int64_t v_x, int64_t *result)\n{\n    int64_t t0 = 0;\n    (void)ctx;\n    (void)v_x;\n    (void)result;\n    static const cint_site cs1 = {0u, 1u}; (void)cs1;\n    if (!cint_mul_i64(ctx, cs1, v_x, v_x, &t0)) goto fault;\n    *result = t0;\n    return true;\nfault:\n    return false;\n}\n```\n\nThe multiplication is a call to `cint_mul_i64`, which computes the exact product and returns false when it does not fit. `cs1` is a site: an entry in a table, written beside the C, that holds the source position a fault report prints. Here that position is line 2, character 14. Each checked operation in the emitted C is a call like this."
  },
  {
   "id": "cu-201-00:scripts-and-main",
   "edition": "CU-201.2",
   "title": "scripts and `main`",
   "clauses": "",
   "url": "/university/201/00-start-here/#scripts-and-main",
   "internal": 0,
   "content": "## scripts and `main`\n\nA file of statements with no functions is a script: its statements run from top to bottom, as in course [101](../101/00-welcome.md).\n\n```ci\n\"hello, world\\n\";\nI64 answer = 6 * 7;\n\"answer={answer}\\n\";\n```\n\nOnce a program has functions, put its statements in `void main() { ... }`, as `squares.ci` does: variables declared outside a function are not visible inside functions or tests."
  },
  {
   "id": "cu-201-00:what-this-course-covers",
   "edition": "CU-201.2",
   "title": "what this course covers",
   "clauses": "",
   "url": "/university/201/00-start-here/#what-this-course-covers",
   "internal": 0,
   "content": "## what this course covers\n\nLessons 201-01 to 201-04 cover the arithmetic at the core of the language in four steps: checked arithmetic and the fault record; the integer types and conversions; the wrapping and saturating operators; division and rounding. The [labs](../401/README.md) build complete programs on top.\n\nEach lesson shows, beside cint's output, what C, Python or JavaScript prints for the same program, with the version that printed it.\n\nNext: [lesson 201-01, numbers that hold](01-numbers-that-hold.md)."
  },
  {
   "id": "cu-201-01:cu-201-2",
   "edition": "CU-201.2",
   "title": "CU-201.2",
   "clauses": "",
   "url": "/university/201/01-numbers-that-hold/",
   "internal": 0,
   "content": "# 201-01: numbers that hold\n\n<a id=\"201-01\"></a>This is lesson 201-01 of CU-201.2, checked against cint 0.2.0.\n\n*You will run a program in your browser and with `cint run`, watch it stop at the one multiplication that does not fit and read the fault record.*"
  },
  {
   "id": "cu-201-01:the-program",
   "edition": "CU-201.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/201/01-numbers-that-hold/#the-program",
   "internal": 0,
   "content": "## the program\n\nThe program puts one grain of rice on the first square of a chessboard and twice as many on each square after it. The total after 64 squares is 2<sup>64</sup> - 1.\n\n```ci\n// One grain of rice on the first square of a chessboard,\n// twice as many on each square after it.\nvoid main() {\n    I64 grains = 1;\n    I64 total = 0;\n    for square in 1..=64 {\n        total += grains;\n        \"square {square:>2}: {grains:>20}   total {total:>20}\\n\";\n        grains *= 2;\n    }\n}\n```"
  },
  {
   "id": "cu-201-01:run-it",
   "edition": "CU-201.2",
   "title": "run it",
   "clauses": "",
   "url": "/university/201/01-numbers-that-hold/#run-it",
   "internal": 0,
   "content": "## run it\n\n```text\n$ cint run chessboard.ci\nsquare  1:                    1   total                    1\nsquare  2:                    2   total                    3\nsquare  3:                    4   total                    7\n...\nsquare 62:  2305843009213693952   total  4611686018427387903\nsquare 63:  4611686018427387904   total  9223372036854775807\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> chessboard.ci:9:16\n   |\n 9 |         grains *= 2;\n   |                ^ mul.checked.i64\n   |\n   = operation: mul.checked.i64\n   = operand-count: 2\n   = operand: I64 4611686018427387904\n   = operand: I64 2\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n   = revision: 20867626996cb61a47e788e74f82b7226550f13626a9d9494bb161d07f294382\n   = source-map: none\n   = address: none\n   = stack-depth: 0\n   = fuel-consumed: 64 (not part of the fault record)\n   = state: the program stopped; stdout holds what it wrote before the fault\n```\n\nAfter square 63 the total is 9223372036854775807, which is `I64.max` exactly. The doubling that follows has no `I64` result, so the program stops at it. Every line it printed before the fault is correct; no wrong number reached the output."
  },
  {
   "id": "cu-201-01:elsewhere",
   "edition": "CU-201.2",
   "title": "elsewhere",
   "clauses": "",
   "url": "/university/201/01-numbers-that-hold/#elsewhere",
   "internal": 0,
   "content": "## elsewhere\n\nThe same loop was run in other languages on 2026-10-10:\n\n| Language | What it printed |\n|---|---|\n| Python 3.13 | The exact total, 18446744073709551615: `int` has no fixed size. |\n| JavaScript, Node 22.22.0 | At square 54, a total of 18014398509481984, one more than the exact 18014398509481983, with no error. Numbers are doubles, which hold every integer only up to 2<sup>53</sup>. Square 64 printed 18446744073709552000. |\n| NumPy 2.5.3, `int64` scalars | At square 64, grains -9223372036854775808 and total -1, with `RuntimeWarning: overflow encountered in scalar multiply`. |\n| NumPy 2.5.3, `int64` arrays | `(2 ** np.arange(64, dtype=np.int64)).sum()` gives -1, with no warning. |\n| C, GCC 13.3, `-O2` | Signed overflow is undefined behavior. This build printed grains -9223372036854775808 and total -1. Built with `-fsanitize=undefined`, it also reports `signed integer overflow: 4611686018427387904 * 2 cannot be represented in type 'long int'` and keeps going. |\n\nPython computes the exact total because its integers grow without a fixed size. JavaScript, NumPy and C give no correct result for square 64; only the NumPy scalar warning and the C sanitizer build show that something went wrong. cint keeps fixed-size integers and checks every plain operator instead."
  },
  {
   "id": "cu-201-01:walk-through",
   "edition": "CU-201.2",
   "title": "walk-through",
   "clauses": "",
   "url": "/university/201/01-numbers-that-hold/#walk-through",
   "internal": 0,
   "content": "## walk-through\n\n**Types come first.** `I64 grains = 1;` declares a signed 64-bit integer. Every variable has a type, and nothing changes it silently: [201-02](02-types-and-conversions.md) covers conversions.\n\n**`for square in 1..=64`** counts from 1 to 64 inclusive. `0..n` excludes `n`, as Python's `range` does.\n\n**Printing** happens when a string literal stands on its own as a statement. `{grains:>20}` prints `grains` right-aligned in 20 characters.\n\n**The multiplication is checked.** For `grains *= 2`, cint computes the exact product, 9223372036854775808, compares it with the type's range and stops because it does not fit. [201-00](00-start-here.md) shows the call this becomes in the emitted C."
  },
  {
   "id": "cu-201-01:reading-the-fault-record",
   "edition": "CU-201.2",
   "title": "reading the fault record",
   "clauses": "",
   "url": "/university/201/01-numbers-that-hold/#reading-the-fault-record",
   "internal": 0,
   "content": "## reading the fault record\n\n| Field | Meaning |\n|---|---|\n| `fault[E_OVERFLOW]` | The fault code. `E_OVERFLOW` means an exact result outside the type's range. |\n| `-->` and the caret | The source position of the operation, here line 9, character 16. |\n| `operation` | The operation by name: a checked (`checked`) multiply (`mul`) on `i64`. Each kind of checked operation has its own name. |\n| `operand-count`, `operand` | The inputs, each with its type. |\n| `exact` | The mathematically exact result. |\n| `limit` | The bound it crossed. |\n| `revision` | A digest of the program's operations, without their source positions. It is the same on every compiler for the same program and cint release. It stays the same when you only add blank lines or comments and changes when an operation changes. |\n| `source-map` | A separate digest of the source positions. cint 0.2.0 prints `none`. |\n| `address` | For a fault inside a kernel, the element it was working on; `none` elsewhere. |\n| `stack-depth` | How many calls deep the operation was. A fault inside a function adds a `called from` line for each caller. |\n| `fuel-consumed` | How many counted steps the program ran before the fault. It is not part of the record, but it is the same on every compiler, so a change in it means the program took a different path. |\n\nThe record is the same on every compiler cint supports, field for field, and so is everything the program printed before it. That is what lets you compare two runs of a program, on two machines or before and after a change, and trust that any difference comes from the program. [201-07](07-debugging-by-comparison.md) builds a way of debugging on it."
  },
  {
   "id": "cu-201-01:fix-it",
   "edition": "CU-201.2",
   "title": "fix it",
   "clauses": "",
   "url": "/university/201/01-numbers-that-hold/#fix-it",
   "internal": 0,
   "content": "## fix it\n\nThere are two fixes, and they mean different things:\n\n```ci\nvoid main() {\n    U64 grains = 1;\n    U64 total = 0;\n    for square in 1..=64 {\n        total += grains;\n        if (square < 64) { grains *= 2; }\n    }\n    \"64 squares: {total} grains\\n\";\n}\n```\n\n```text\n64 squares: 18446744073709551615 grains\n```\n\n`U64.max` is exactly 2<sup>64</sup> - 1, so the total fits. It fits only if the program skips the doubling after the last square, which would need 2<sup>64</sup>.\n\nThe second fix is a wider type. cint's integers go up to 1024 bits:\n\n```ci\nvoid main() {\n    I128 grains = 1;\n    I128 total = 0;\n    for square in 1..=64 {\n        total += grains;\n        grains *= 2;\n    }\n    \"64 squares: {total} grains\\n\";\n    \"next square would hold {grains}\\n\";\n}\n```\n\n```text\n64 squares: 18446744073709551615 grains\nnext square would hold 18446744073709551616\n```"
  },
  {
   "id": "cu-201-01:try-this",
   "edition": "CU-201.2",
   "title": "try this",
   "clauses": "",
   "url": "/university/201/01-numbers-that-hold/#try-this",
   "internal": 0,
   "content": "## try this\n\n1. Change both types to `I32`. Which square's total is the last one that fits, and what is it?\n2. Triple instead of double. Predict the last square an `I64` board reaches.\n\n<details>\n<summary>answer to 1</summary>\n\nThe doubling after square 31 faults:\n\n```text\n   = operation: mul.checked.i32\n   = operand-count: 2\n   = operand: I32 1073741824\n   = operand: I32 2\n   = exact:   2147483648\n   = limit:   I32 2147483647\n```\n\nSquare 31's total is 2147483647, `I32.max`.\n</details>"
  },
  {
   "id": "cu-201-01:reference",
   "edition": "CU-201.2",
   "title": "reference",
   "clauses": "",
   "url": "/university/201/01-numbers-that-hold/#reference",
   "internal": 0,
   "content": "## reference\n\n[the fault record]({{SPEC}}#fault-record), [checked arithmetic]({{SPEC}}#checked-arithmetic), [integer types]({{SPEC}}#integer-types), [ranges]({{SPEC}}#ranges), [printing]({{SPEC}}#printing)\n\nNext: [201-02, types and conversions](02-types-and-conversions.md)."
  },
  {
   "id": "cu-201-02:cu-201-2",
   "edition": "CU-201.2",
   "title": "CU-201.2",
   "clauses": "",
   "url": "/university/201/02-types-and-conversions/",
   "internal": 0,
   "content": "# 201-02: types and conversions\n\n<a id=\"201-02\"></a>This is lesson 201-02 of CU-201.2, checked against cint 0.2.0.\n\n*You will meet the integer types, see that cint never converts a value implicitly and choose what happens at each edge of a conversion.*"
  },
  {
   "id": "cu-201-02:the-program",
   "edition": "CU-201.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/201/02-types-and-conversions/#the-program",
   "internal": 0,
   "content": "## the program\n\nThe program packs an altitude in millimeters into a 16-bit field of decimeters, as a telemetry format might carry it:\n\n```ci\n// An altitude in millimeters, packed into a 16-bit field of\n// decimeters. Each conversion says what happens at the edge.\nvoid main() {\n    I64 low_mm = 3_276_700;\n    I16 low = (low_mm / 100) as I16;\n    \"low:     {low}\\n\";\n\n    I64 high_mm = 3_276_800;\n    I64 high_dm = high_mm / 100;\n    I16 wrapped = high_dm as% I16;\n    I16 clamped = high_dm as? I16 catch I16.max;\n    \"wrapped: {wrapped}\\n\";\n    \"handled: {clamped}\\n\";\n\n    I16 checked = high_dm as I16;\n    \"not printed: {checked}\\n\";\n}\n```"
  },
  {
   "id": "cu-201-02:run-it",
   "edition": "CU-201.2",
   "title": "run it",
   "clauses": "",
   "url": "/university/201/02-types-and-conversions/#run-it",
   "internal": 0,
   "content": "## run it\n\n```text\n$ cint run downlink.ci\nlow:     32767\nwrapped: -32768\nhandled: 32767\nfault[E_NARROW]: the value does not fit the destination type\n  --> downlink.ci:15:27\n   |\n15 |     I16 checked = high_dm as I16;\n   |                           ^ as.checked.i64.i16\n   |\n   = operation: as.checked.i64.i16\n   = operand-count: 1\n   = operand: I64 32768\n   = exact:   32768\n   = limit:   I16 32767\n   ...\n```\n\n3276700 mm is 32767 dm, `I16.max`, and fits. 3276800 mm is 32768 dm, one past `I16.max`. The program converts that value three ways, and each line says what it wants at the edge."
  },
  {
   "id": "cu-201-02:the-three-conversions",
   "edition": "CU-201.2",
   "title": "the three conversions",
   "clauses": "",
   "url": "/university/201/02-types-and-conversions/#the-three-conversions",
   "internal": 0,
   "content": "## the three conversions\n\n| Form | When the value fits | When it does not |\n|---|---|---|\n| `x as T` | the value | fault `E_NARROW` |\n| `x as% T` | the value | wraps: the low bits of `x`, read as `T` |\n| `x as? T catch v` | the value | `v`, chosen by the program |\n\n`as` is the default. `as%` is for formats and hashes where only the low bits matter. `as?` turns the out-of-range case into an ordinary error, and `catch` gives the value to use instead."
  },
  {
   "id": "cu-201-02:no-implicit-conversions",
   "edition": "CU-201.2",
   "title": "no implicit conversions",
   "clauses": "",
   "url": "/university/201/02-types-and-conversions/#no-implicit-conversions",
   "internal": 0,
   "content": "## no implicit conversions\n\ncint never converts between types on its own, not even to a wider type:\n\n```ci\nI64 big = 40_000;\nI16 small = big;\n```\n\n```text\nerror[C2001]: type mismatch\n  --> narrow_error.ci:2:13\n   |\n 2 | I16 small = big;\n   |             ^\n   |\n```\n\nThe same message comes from `I64 wide = b;` when `b` is a `U8`, although every `U8` fits an `I64`. Each conversion is written, so each one is a place you can see and search for."
  },
  {
   "id": "cu-201-02:literals-take-their-type-from-where-they-are-use",
   "edition": "CU-201.2",
   "title": "literals take their type from where they are used",
   "clauses": "",
   "url": "/university/201/02-types-and-conversions/#literals-take-their-type-from-where-they-are-used",
   "internal": 0,
   "content": "## literals take their type from where they are used\n\nA literal has no type until its context gives it one. That includes the arithmetic around it:\n\n```ci\nI16 seconds_per_day = 24 * 60 * 60;\n```\n\n```text\nerror[C6001]: fault during constant evaluation\n  --> fold_error.ci:1:31\n   |\n 1 | I16 seconds_per_day = 24 * 60 * 60;\n   |                               ^\n   |\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> fold_error.ci:1:31\n   ...\n   = operation: mul.checked.i16\n   = operand-count: 2\n   = operand: I16 1440\n   = operand: I16 60\n   = exact:   86400\n   = limit:   I16 32767\n   ...\n```\n\nThe multiplication is done in `I16` because that is the destination, and the compiler evaluates constant expressions with the same checks as the running program. The error comes before anything runs, although the full report still ends with \"the program stopped\"."
  },
  {
   "id": "cu-201-02:elsewhere",
   "edition": "CU-201.2",
   "title": "elsewhere",
   "clauses": "",
   "url": "/university/201/02-types-and-conversions/#elsewhere",
   "internal": 0,
   "content": "## elsewhere\n\nThese results were measured on 2026-10-10, on Ubuntu 24.04 for x86-64:\n\n| Language | `32768` into 16 bits | `int16 x = 24 * 60 * 60` |\n|---|---|---|\n| C, GCC 13.3, `-O2 -Wall` | `(int16_t)32768` gives -32768 | compiles with the warning `changes value from '86400' to '20864'` and prints 20864 |\n| NumPy 2.5.3 | `np.array([32768]).astype(np.int16)` gives `[-32768]`; `np.int16(32768)` raises `OverflowError` | not applicable: Python has no typed variable declarations |"
  },
  {
   "id": "cu-201-02:walk-through",
   "edition": "CU-201.2",
   "title": "walk-through",
   "clauses": "",
   "url": "/university/201/02-types-and-conversions/#walk-through",
   "internal": 0,
   "content": "## walk-through\n\n**The integer types** are `I8`, `I16`, `I32`, `I64`, `I128`, `I256`, `I512` and `I1024`, and `U8` to `U512` for the unsigned ones. `T.min` and `T.max` give each range. `Bool` is its own type: `b as I64` gives 0 or 1, and like every other conversion it is written out.\n\n**Literals** come in four bases, with `_` as a separator anywhere between digits:\n\n```ci\nvoid main() {\n    U8 mask = 0b1010_0101;\n    U16 color = 0xFF_80;\n    I32 perms = 0o755;\n    I64 big = 1_000_000;\n    \"{mask} {color} {perms} {big}\\n\";\n    \"{mask:b} {color:x} {I16.min} {I16.max}\\n\";\n}\n```\n\n```text\n165 65408 493 1000000\n10100101 ff80 -32768 32767\n```\n\nA literal that cannot fit its type is a compile error, C2003. For example, `U8 b = 256;` is refused."
  },
  {
   "id": "cu-201-02:try-this",
   "edition": "CU-201.2",
   "title": "try this",
   "clauses": "",
   "url": "/university/201/02-types-and-conversions/#try-this",
   "internal": 0,
   "content": "## try this\n\n1. Change `high_mm` to `-3_276_900`. What do the three conversions give? Which one faults?\n2. Write a `U8` checksum of the bytes 200, 100 and 50, where the sum is meant to wrap. Which conversion, or which operator from [201-03](03-operators-at-the-edge.md), says that?"
  },
  {
   "id": "cu-201-02:reference",
   "edition": "CU-201.2",
   "title": "reference",
   "clauses": "",
   "url": "/university/201/02-types-and-conversions/#reference",
   "internal": 0,
   "content": "## reference\n\n[integer types]({{SPEC}}#integer-types), [literals]({{SPEC}}#literals), [conversions]({{SPEC}}#conversions), [constant evaluation]({{SPEC}}#constant-evaluation)\n\nNext: [201-03, operators at the edge](03-operators-at-the-edge.md)."
  },
  {
   "id": "cu-201-03:cu-201-2",
   "edition": "CU-201.2",
   "title": "CU-201.2",
   "clauses": "",
   "url": "/university/201/03-operators-at-the-edge/",
   "internal": 0,
   "content": "# 201-03: operators at the edge\n\n<a id=\"201-03\"></a>This is lesson 201-03 of CU-201.2, checked against cint 0.2.0.\n\n*You will see that the plain operators are checked, and write the wrapping or saturating spelling only where that is what the program means.*"
  },
  {
   "id": "cu-201-03:the-program",
   "edition": "CU-201.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/201/03-operators-at-the-edge/#the-program",
   "internal": 0,
   "content": "## the program\n\nThis program uses the 32-bit FNV-1a hash. Its multiply is meant to wrap, so the program writes `*%`:\n\n```ci\n// FNV-1a, a 32-bit hash. Hashes wrap on purpose, so the\n// multiply is written *% and says so.\nconst U32 FNV_OFFSET = 2_166_136_261;\nconst U32 FNV_PRIME = 16_777_619;\n\nU32 fnv1a[n](in U8[n] bytes) {\n    U32 h = FNV_OFFSET;\n    for i in 0..n {\n        h = h ^ (bytes[i] as U32);\n        h = h *% FNV_PRIME;\n    }\n    return h;\n}\n\nvoid main() {\n    U32 a = fnv1a(\"hello\");\n    U32 b = fnv1a(\"hellp\");\n    \"hello -> {a:x}\\n\";\n    \"hellp -> {b:x}\\n\";\n}\n```"
  },
  {
   "id": "cu-201-03:run-it",
   "edition": "CU-201.2",
   "title": "run it",
   "clauses": "",
   "url": "/university/201/03-operators-at-the-edge/#run-it",
   "internal": 0,
   "content": "## run it\n\n```text\n$ cint run fnv.ci\nhello -> 4f9f2cab\nhellp -> 5c9f4122\n```\n\nBoth values match a Python implementation of the published algorithm, which masks each product with `& 0xffffffff`."
  },
  {
   "id": "cu-201-03:the-same-hash-with-a-plain",
   "edition": "CU-201.2",
   "title": "the same hash with a plain `*`",
   "clauses": "",
   "url": "/university/201/03-operators-at-the-edge/#the-same-hash-with-a-plain",
   "internal": 0,
   "content": "## the same hash with a plain `*`\n\nChange `*%` to `*` and the first multiply faults:\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> fnv_checked.ci:10:15\n   |\n10 |         h = h * FNV_PRIME;\n   |               ^ mul.checked.u32\n   |\n   = operation: mul.checked.u32\n   = operand-count: 2\n   = operand: U32 2166136237\n   = operand: U32 16777619\n   = exact:   36342608486479703\n   = limit:   U32 4294967295\n   ...\n   = stack-depth: 1\n   = called from: fnv_checked.ci:16:13\n```\n\n`called from` gives the line in `main` that called `fnv1a`. In C, `uint32_t` arithmetic wraps by definition, so C versions of the two programs would read the same. In cint, the wrap is written where it is wanted, and every other multiply in a program stays checked."
  },
  {
   "id": "cu-201-03:three-families-of-operators",
   "edition": "CU-201.2",
   "title": "three families of operators",
   "clauses": "",
   "url": "/university/201/03-operators-at-the-edge/#three-families-of-operators",
   "internal": 0,
   "content": "## three families of operators\n\n| Family | Spelling | On overflow |\n|---|---|---|\n| checked | `+` `-` `*` `/` `<<` | faults |\n| wrapping | `+%` `-%` `*%` | keeps the low bits, never faults |\n| saturating | `+|` `-|` `*|` | stops at `T.min` or `T.max`, never faults |\n\nThis program prints four results:\n\n```ci\nU8 a = 10;\nU8 b = 20;\nU8 w = a -% b;\nU8 s = a -| b;\nI8 m = 100;\nI8 t = m *| 3;\nI8 u = m *% 3;\n\"{w} {s} {t} {u}\\n\";\n```\n\n```text\n246 0 127 44\n```\n\n10 - 20 wraps to 246 in `U8` and saturates to 0; 100 * 3 saturates to 127 in `I8` and wraps to 44 (300 - 256)."
  },
  {
   "id": "cu-201-03:saturating-pixels",
   "edition": "CU-201.2",
   "title": "saturating pixels",
   "clauses": "",
   "url": "/university/201/03-operators-at-the-edge/#saturating-pixels",
   "internal": 0,
   "content": "## saturating pixels\n\nBrightening an 8-bit pixel should stop at white, 255. That is what `+|` says:\n\n```ci\n// Brighten 8-bit pixels. A pixel past 255 should stop at 255,\n// so the add is written +| and saturates.\nvoid brighten[n](inout U8[n] px, U8 amount) {\n    for i in 0..n { px[i] = px[i] +| amount; }\n}\nvoid main() {\n    U8[6] px = [0, 64, 128, 192, 230, 255];\n    brighten(px, 40);\n    for i in 0..6 { \"{px[i]} \"; }\n    \"\\n\";\n}\n```\n\n```text\n40 104 168 232 255 255 \n```"
  },
  {
   "id": "cu-201-03:elsewhere",
   "edition": "CU-201.2",
   "title": "elsewhere",
   "clauses": "",
   "url": "/university/201/03-operators-at-the-edge/#elsewhere",
   "internal": 0,
   "content": "## elsewhere\n\nOn 2026-10-10, the same six pixels were brightened by 40 in other languages:\n\n| Language | Result |\n|---|---|\n| cint, `+|` | `40 104 168 232 255 255` |\n| NumPy 2.5.3, `uint8` array `+ np.uint8(40)` | `[ 40 104 168 232  14  39]`, with no warning |\n| C, GCC 13.3 `-O2`, `uint8_t` with `+=` | `40 104 168 232 14 39` |\n\nThe two bright pixels turn dark. A plain `+` in cint would fault on 230 + 40 instead; `+|` gives the answer the program wants."
  },
  {
   "id": "cu-201-03:shifts-are-checked-too",
   "edition": "CU-201.2",
   "title": "shifts are checked too",
   "clauses": "",
   "url": "/university/201/03-operators-at-the-edge/#shifts-are-checked-too",
   "internal": 0,
   "content": "## shifts are checked too\n\n```ci\nI32 one = 1;\nI32 x = one << 31;\n\"x={x}\\n\";\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> p29_shift_overflow.ci:2:13\n   |\n 2 | I32 x = one << 31;\n   |             ^ shl.checked.i32\n   |\n   = operation: shl.checked.i32\n   = operand-count: 2\n   = operand: I32 1\n   = operand: I64 31\n   = exact:   2147483648\n   = limit:   I32 2147483647\n   ...\n```\n\nA left shift is a multiply by a power of two, and it is checked the same way. In C, `1 << 31` on a 32-bit `int` is undefined behavior."
  },
  {
   "id": "cu-201-03:walk-through",
   "edition": "CU-201.2",
   "title": "walk-through",
   "clauses": "",
   "url": "/university/201/03-operators-at-the-edge/#walk-through",
   "internal": 0,
   "content": "## walk-through\n\n**Why checked is the default.** Most arithmetic in a program is not meant to wrap. Making the plain operators checked turns every unintended overflow in a plain operator into a fault at the operation that caused it. Intended wrapping and saturating stay visible as the `%` of `+%` and the `|` of `+|`.\n\n**Bitwise operators** `&`, `|` and `^` take two integers of one type, and `~` takes one. Unlike the operands of these, a shift's count can be of another integer type. `h ^ (bytes[i] as U32)` converts the byte first, because cint does not convert implicitly.\n\n**`in U8[n] bytes`** is a read-only view of `n` bytes, and `n` is a size parameter filled in at the call. A string literal passed to it is viewed as its bytes."
  },
  {
   "id": "cu-201-03:try-this",
   "edition": "CU-201.2",
   "title": "try this",
   "clauses": "",
   "url": "/university/201/03-operators-at-the-edge/#try-this",
   "internal": 0,
   "content": "## try this\n\n1. Write a 64-bit FNV-1a with offset 14695981039346656037 and prime 1099511628211. What does it give for \"hello\"?\n2. Darken the pixels by 40 with `-|`. What do the first two become?"
  },
  {
   "id": "cu-201-03:reference",
   "edition": "CU-201.2",
   "title": "reference",
   "clauses": "",
   "url": "/university/201/03-operators-at-the-edge/#reference",
   "internal": 0,
   "content": "## reference\n\n[checked operators]({{SPEC}}#checked-arithmetic), [wrapping and saturating operators]({{SPEC}}#wrapping-saturating), [shifts]({{SPEC}}#shifts), [views]({{SPEC}}#views)\n\nNext: [201-04, division and rounding](04-division-and-rounding.md)."
  },
  {
   "id": "cu-201-04:cu-201-2",
   "edition": "CU-201.2",
   "title": "CU-201.2",
   "clauses": "",
   "url": "/university/201/04-division-and-rounding/",
   "internal": 0,
   "content": "# 201-04: division and rounding\n\n<a id=\"201-04\"></a>This is lesson 201-04 of CU-201.2, checked against cint 0.2.0.\n\n*You will split a bill so the parts add up to the cent, and name the rounding rule wherever a result is not a whole number.*"
  },
  {
   "id": "cu-201-04:the-program",
   "edition": "CU-201.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/201/04-division-and-rounding/#the-program",
   "internal": 0,
   "content": "## the program\n\n```ci\n// Split a restaurant bill exactly, in cents, with an 18 percent tip.\nvoid main() {\n    I64 bill = 10_000;\n    I64 tip = muldiv(I64, bill, 18, 100, half_even);\n    I64 total = bill + tip;\n    I64 people = 3;\n    I64 share = total / people;\n    I64 left = total % people;\n    \"bill {bill:/100}, tip {tip:/100}, total {total:/100}\\n\";\n    for p in 1..=people {\n        I64 pays = share;\n        if (p <= left) { pays += 1; }\n        \"person {p} pays {pays:/100}\\n\";\n    }\n}\n```"
  },
  {
   "id": "cu-201-04:run-it",
   "edition": "CU-201.2",
   "title": "run it",
   "clauses": "",
   "url": "/university/201/04-division-and-rounding/#run-it",
   "internal": 0,
   "content": "## run it\n\n```text\n$ cint run bill.ci\nbill 100.00, tip 18.00, total 118.00\nperson 1 pays 39.34\nperson 2 pays 39.33\nperson 3 pays 39.33\n```\n\nThe three shares add up to 118.00 exactly. The cent that does not divide evenly goes to the first person, and the program says so in one line."
  },
  {
   "id": "cu-201-04:division-in-cint",
   "edition": "CU-201.2",
   "title": "division in cint",
   "clauses": "",
   "url": "/university/201/04-division-and-rounding/#division-in-cint",
   "internal": 0,
   "content": "## division in cint\n\n**`/` rounds toward negative infinity**, and `%` takes the sign of the divisor. Together they keep `a == (a / b) * b + a % b` for every division that does not fault. This is Python's rule, not C's.\n\n```ci\nvoid main() {\n    I64 a = -7;\n    I64 b = 2;\n    \"a / b      = {a / b}   a % b      = {a % b}\\n\";\n    \"div_trunc  = {div_trunc(a, b)}   rem_trunc  = {rem_trunc(a, b)}\\n\";\n    \"div_euclid = {div_euclid(a, b)}   rem_euclid = {rem_euclid(a, b)}\\n\";\n    \"floor {div_round(a, b, floor)}  ceil {div_round(a, b, ceil)}  trunc {div_round(a, b, trunc)}  away {div_round(a, b, away)}\\n\";\n    \"half_even {div_round(a, b, half_even)}  half_away {div_round(a, b, half_away)}  half_trunc {div_round(a, b, half_trunc)}  half_up {div_round(a, b, half_up)}  half_down {div_round(a, b, half_down)}\\n\";\n}\n```\n\n```text\na / b      = -4   a % b      = 1\ndiv_trunc  = -3   rem_trunc  = -1\ndiv_euclid = -4   rem_euclid = 1\nfloor -4  ceil -3  trunc -3  away -4\nhalf_even -4  half_away -4  half_trunc -3  half_up -3  half_down -4\n```\n\n- `div_trunc` and `rem_trunc` are C's division: toward zero.\n- `div_euclid` and `rem_euclid` keep the remainder between 0 and `|b| - 1`.\n- `div_round(a, b, mode)` rounds the exact quotient, -3.5 here, by a named mode. There are nine modes. Four round in one direction: `floor`, `ceil`, `trunc` and `away`. Five round to the nearest integer and differ only on ties: `half_even`, `half_away`, `half_trunc`, `half_up` and `half_down`.\n\nDivision by zero faults with `E_DIV_ZERO`. `I64.min / -1`, whose exact result is one past `I64.max`, faults with `E_OVERFLOW`."
  },
  {
   "id": "cu-201-04:muldiv",
   "edition": "CU-201.2",
   "title": "`muldiv`",
   "clauses": "",
   "url": "/university/201/04-division-and-rounding/#muldiv",
   "internal": 0,
   "content": "## `muldiv`\n\n`muldiv(I64, bill, 18, 100, half_even)` computes `bill * 18 / 100` with the product held exactly, rounds the quotient once by the mode and checks that the result fits `I64`. Writing `bill * 18 / 100` instead would round down and would fault if the product overflows even when the final result fits."
  },
  {
   "id": "cu-201-04:elsewhere",
   "edition": "CU-201.2",
   "title": "elsewhere",
   "clauses": "",
   "url": "/university/201/04-division-and-rounding/#elsewhere",
   "internal": 0,
   "content": "## elsewhere\n\nThe same division and the same ties were evaluated in other languages on 2026-10-10:\n\n| Language | `-7 / 2` | `-7 % 2` | rounding -3.5 | rounding 2.5 |\n|---|---|---|---|---|\n| cint | -4 | 1 | named: `half_even` gives -4, `half_up` gives -3 | named |\n| C, GCC 13.3 | -3 | -1 | `round(-3.5)` is -4, `rint(-3.5)` is -4 | `round(2.5)` is 3, `rint(2.5)` is 2 |\n| Python 3.13 | `-7 // 2` is -4 | 1 | `round(-3.5)` is -4 | `round(2.5)` is 2 |\n| JavaScript, Node 22.22.0 | `Math.trunc(-7 / 2)` is -3 | -1 | `Math.round(-3.5)` is -3 | `Math.round(2.5)` is 3 |\n\nPython's `round` rounds ties to even, and JavaScript's `Math.round` rounds them up. C's `round` rounds them away from zero, while `rint` follows a rounding mode set elsewhere in the program, by default to even. None of them names its rule at the call. In cint, a `div_round` or `muldiv` call carries the rule."
  },
  {
   "id": "cu-201-04:walk-through",
   "edition": "CU-201.2",
   "title": "walk-through",
   "clauses": "",
   "url": "/university/201/04-division-and-rounding/#walk-through",
   "internal": 0,
   "content": "## walk-through\n\n**Money in cents.** The bill is 10000 cents, an `I64`. Every amount stays an exact whole number of cents, and the only rounding, the tip's, is named in the call.\n\n**`{bill:/100}`** prints a value divided by 100 with two decimal places: 10000 prints as `100.00`. Only the printing divides; the value is unchanged.\n\n**The leftover cent.** `total % people` is 1, so one person pays one more cent. Any rule for who pays it is fine, as long as the program states it and the shares add up."
  },
  {
   "id": "cu-201-04:try-this",
   "edition": "CU-201.2",
   "title": "try this",
   "clauses": "",
   "url": "/university/201/04-division-and-rounding/#try-this",
   "internal": 0,
   "content": "## try this\n\n1. Split 100.00 seven ways. How many people pay an extra cent?\n2. Make the tip 15 percent of 99.99. Round it with `half_even`, then with `floor`, then with `ceil`. Which ones differ?"
  },
  {
   "id": "cu-201-04:reference",
   "edition": "CU-201.2",
   "title": "reference",
   "clauses": "",
   "url": "/university/201/04-division-and-rounding/#reference",
   "internal": 0,
   "content": "## reference\n\n[division]({{SPEC}}#division), [rounding modes]({{SPEC}}#rounding-modes), [muldiv]({{SPEC}}#muldiv), [print formats]({{SPEC}}#print-formats)\n\nNext: [201-05, tests and goldens](05-tests-and-goldens.md)."
  },
  {
   "id": "cu-201-05:cu-201-2",
   "edition": "CU-201.2",
   "title": "CU-201.2",
   "clauses": "",
   "url": "/university/201/05-tests-and-goldens/",
   "internal": 0,
   "content": "# 201-05: tests and goldens\n\n<a id=\"201-05\"></a>This is lesson 201-05 of CU-201.2, checked against cint 0.2.0.\n\n*You will write tests beside the code they check and save a golden of a run you have checked. Then you will see which mistakes each one catches.*"
  },
  {
   "id": "cu-201-05:the-program",
   "edition": "CU-201.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/201/05-tests-and-goldens/#the-program",
   "internal": 0,
   "content": "## the program\n\nThis is the bill split from [201-04](04-division-and-rounding.md), with its two calculations as functions and three tests at the end of the file:\n\n```ci\n// Split a bill in cents among people, with an 18 percent tip.\n// The cents that do not divide evenly go to the first people, one each.\n\nI64 tip(I64 bill) {\n    return muldiv(I64, bill, 18, 100, half_even);\n}\n\n// What person p (counting from 1) pays when total is split among people.\nI64 share(I64 total, I64 people, I64 p) {\n    I64 pays = total / people;\n    if (p <= total % people) {\n        pays += 1;\n    }\n    return pays;\n}\n\nvoid main() {\n    I64 bill = 10_000;\n    I64 total = bill + tip(bill);\n    I64 people = 3;\n    \"bill {bill:/100}, tip {tip(bill):/100}, total {total:/100}\\n\";\n    for p in 1..=people {\n        \"person {p} pays {share(total, people, p):/100}\\n\";\n    }\n}\n\ntest \"the shares add up to the total\" {\n    for people in 1..=12 {\n        I64 paid = 0;\n        for p in 1..=people {\n            paid += share(11_800, people, p);\n        }\n        assert(paid == 11_800);\n    }\n}\n\ntest \"a tip of half a cent rounds to even\" {\n    assert(tip(25) == 4);       // 4.5 cents rounds to 4\n    assert(tip(75) == 14);      // 13.5 cents rounds to 14\n}\n\ntest \"nobody to split among is a fault\" expect_fault E_DIV_ZERO {\n    _ = share(100, 0, 1);\n}\n```"
  },
  {
   "id": "cu-201-05:run-it-then-test-it",
   "edition": "CU-201.2",
   "title": "run it, then test it",
   "clauses": "",
   "url": "/university/201/05-tests-and-goldens/#run-it-then-test-it",
   "internal": 0,
   "content": "## run it, then test it\n\n```text\n$ cint run split.ci\nbill 100.00, tip 18.00, total 118.00\nperson 1 pays 39.34\nperson 2 pays 39.33\nperson 3 pays 39.33\n$ cint test split.ci\ntest split.ci:27 \"the shares add up to the total\" ... ok\ntest split.ci:37 \"a tip of half a cent rounds to even\" ... ok\ntest split.ci:42 \"nobody to split among is a fault\" ... ok\n3 of 3 tests passed\n```\n\n`cint run` runs `main` and ignores the tests. `cint test` runs each test and ignores `main`."
  },
  {
   "id": "cu-201-05:tests",
   "edition": "CU-201.2",
   "title": "tests",
   "clauses": "",
   "url": "/university/201/05-tests-and-goldens/#tests",
   "internal": 0,
   "content": "## tests\n\nA `test` block is a function with a name in quotes and no parameters, written in the same file as the code it checks. Each test starts from the program's initial state, so one test cannot change what another sees.\n\n- **`assert(condition)`** stops the test with a fault when the condition is false.\n- **`expect_fault CODE`** after the name turns the test around: it passes only when its body faults with that code. The third test passes because `share(100, 0, 1)` divides by zero.\n\nChange `tip` to the plain division `return bill * 18 / 100;` and test again:\n\n```text\n$ cint test split.ci\ntest split.ci:27 \"the shares add up to the total\" ... ok\ntest split.ci:37 \"a tip of half a cent rounds to even\" ... FAILED\nfault[E_ASSERT]: assertion failed\n  --> split.ci:39:12\n   |\n39 |     assert(tip(75) == 14);      // 13.5 cents rounds to 14\n   |            ^ assert.checked.bool\n   |\n   = operation: assert.checked.bool\n   = operand-count: 2\n   = operand: I64 13\n   = operand: I64 14\n   ...\ntest split.ci:42 \"nobody to split among is a fault\" ... ok\n2 of 3 tests passed\n```\n\nA failed assertion is a fault, with a fault report like any other. For a comparison, its two operands are the values of the two sides: `tip(75)` returned 13 where the test wanted 14. The first assertion in the same test still passed, because 4.5 rounds down to 4 under both rules. `cint test` exits with status 3 when a test fails, so a script or a build can stop on it."
  },
  {
   "id": "cu-201-05:goldens",
   "edition": "CU-201.2",
   "title": "goldens",
   "clauses": "",
   "url": "/university/201/05-tests-and-goldens/#goldens",
   "internal": 0,
   "content": "## goldens\n\nA test checks a case you chose. A **golden** checks a whole run: it is the saved output of a run that you checked by hand, and every run after it must match it byte for byte. Three rules govern a golden:\n\n1. Check the output by hand before you save it.\n2. Never edit a golden by hand.\n3. When a change is meant to alter the output, check the new output by hand. Save it as the new golden in a separate step, so the change and the new golden stay apart.\n\ncint supports two kinds of golden."
  },
  {
   "id": "cu-201-05:the-output-of-a-run",
   "edition": "CU-201.2",
   "title": "the output of a run",
   "clauses": "",
   "url": "/university/201/05-tests-and-goldens/#the-output-of-a-run",
   "internal": 0,
   "content": "### the output of a run\n\nThe output of `cint run`, saved to a file, is the simplest golden:\n\n```text\n$ cint run split.ci > split.golden\n```\n\nAfter a change, run again into another file and compare the two. A difference shows exactly which lines changed; [401-01](../401/01-ledger.md) works through an example.\n\nIn Windows PowerShell, `>` saves text in a different encoding from the one cint writes. Both files are saved the same way, so VS Code's **Select for Compare** still shows the lines that differ, and `fc.exe /b split.golden after.txt` still says whether the files match. Type `fc.exe` in full, since `fc` alone is the PowerShell alias for `Format-Custom`."
  },
  {
   "id": "cu-201-05:the-reference-s-record",
   "edition": "CU-201.2",
   "title": "the reference's record",
   "clauses": "",
   "url": "/university/201/05-tests-and-goldens/#the-reference-s-record",
   "internal": 0,
   "content": "### the reference's record\n\nThe reference, the Python program that defines what every cint program means, writes a record of a run. It is in the `ref` folder of the cint source. Point Python at that folder once per terminal, replacing `SOURCE` with the folder you unpacked cint into:\n\nOn macOS and Linux, type this:\n\n```text\n$ export PYTHONPATH=\"SOURCE/ref\"\n```\n\nIn Windows PowerShell, type this:\n\n```text\nPS> $env:PYTHONPATH = \"SOURCE\\ref\"\n```\n\nThen save the record:\n\n```text\n$ python3 -m cint_ref run split.ci > split.expect\n$ cat split.expect\ncase split\nsource reference\noutcome value\nstdout-bytes 97\nstdout-sha256 266f03fdb752d2d04bc11f2ee54c21d60e281857c78c96ccaa0fadd181a1b439\nfuel-consumed 9\n```\n\nIn Windows PowerShell, write the first command of that block as `cmd /c \"python -m cint_ref run split.ci > split.expect\"`, so the record is saved byte for byte.\n\nThe record holds how the run ended (`outcome value`: it finished) and the size and SHA-256 digest of everything it printed. It also holds `fuel-consumed`, a count charged at each call and at each pass through a loop, which comes out the same on the reference and on the compilers. For a run that faults, the record also holds every field of the fault report. `check` runs the program again and compares:\n\n```text\n$ python3 -m cint_ref check split.ci split.expect\n$ echo $?\n0\n```\n\nSilence and status 0 mean the run matches the record. In PowerShell, `$LASTEXITCODE` shows the status."
  },
  {
   "id": "cu-201-05:a-change-only-the-record-notices",
   "edition": "CU-201.2",
   "title": "a change only the record notices",
   "clauses": "",
   "url": "/university/201/05-tests-and-goldens/#a-change-only-the-record-notices",
   "internal": 0,
   "content": "## a change only the record notices\n\nNow compute the tip once and keep it in a variable. This change keeps the output the same but removes a call.\n\n```ci\n    I64 t = tip(bill);\n    I64 total = bill + t;\n    I64 people = 3;\n    \"bill {bill:/100}, tip {t:/100}, total {total:/100}\\n\";\n```\n\nRun it and compare with `split.golden`: the files match. The record disagrees:\n\n```text\n$ python3 -m cint_ref check split.ci split.expect\nsplit.expect: line 6 differs\n  expected: fuel-consumed 9\n  actual:   fuel-consumed 8\n```\n\nThe output is the same, byte for byte, but the fuel is 1 lower, because `tip` is called once instead of twice. A change in fuel means the program took a different path. Here a new path was the point of the change, so the record is out of date: check the output, then save a new record in a step of its own. When you did not mean to change the path, the same line warns that the program now takes a different path."
  },
  {
   "id": "cu-201-05:which-to-use",
   "edition": "CU-201.2",
   "title": "which to use",
   "clauses": "",
   "url": "/university/201/05-tests-and-goldens/#which-to-use",
   "internal": 0,
   "content": "## which to use\n\n| | Catches | Shows |\n|---|---|---|\n| A test | a wrong answer for a case you chose: an edge, a tie, a fault | which assertion failed, with both sides |\n| The output of a run | any change in what the program prints | which lines changed |\n| The reference's record | any change in the output, in how the run ended, in a field of a fault or in the path it took | the first line of the record that differs |\n\nA program you intend to keep has tests for its hard cases and a golden of its main run, and both live beside it in version control."
  },
  {
   "id": "cu-201-05:elsewhere",
   "edition": "CU-201.2",
   "title": "elsewhere",
   "clauses": "",
   "url": "/university/201/05-tests-and-goldens/#elsewhere",
   "internal": 0,
   "content": "## elsewhere\n\nSaved-output tests exist in most languages, as golden files, snapshot tests or approval tests. They are harder to keep where output is not the same from run to run. On 2026-10-10, running `python3 -c \"print({'apple', 'banana', 'cherry'})\"` five times with Python 3.13 on Ubuntu 24.04 printed the set in four different orders, because Python changes how it hashes strings each time it starts. A cint program has no such source of variation. One program, built by one release, prints the same bytes on every run and with each of the four C compilers used to check these lessons."
  },
  {
   "id": "cu-201-05:walk-through",
   "edition": "CU-201.2",
   "title": "walk-through",
   "clauses": "",
   "url": "/university/201/05-tests-and-goldens/#walk-through",
   "internal": 0,
   "content": "## walk-through\n\n**`for people in 1..=12`** inside a test checks twelve cases in one test. A test is ordinary code, so loops and helper functions work in it.\n\n**`paid`, not `sum`.** `sum` is a built-in function, and a local variable cannot take its name; the compiler says `error[C3001]: duplicate name`. `count`, `min` and `max` are taken the same way.\n\n**`_ = share(100, 0, 1);`** calls the function and discards its result. The test exists only for the fault."
  },
  {
   "id": "cu-201-05:try-this",
   "edition": "CU-201.2",
   "title": "try this",
   "clauses": "",
   "url": "/university/201/05-tests-and-goldens/#try-this",
   "internal": 0,
   "content": "## try this\n\n1. Add a test that splitting 1 cent among 3 people gives 1, 0 and 0.\n2. Change `main` to split among 4 people. Which goldens fail, and what does each one show?\n3. Save a record of a run that faults: set `bill` to `I64.max` in `main` and run the reference. Which fields does the record add, and which line of the program does it name?"
  },
  {
   "id": "cu-201-05:reference",
   "edition": "CU-201.2",
   "title": "reference",
   "clauses": "",
   "url": "/university/201/05-tests-and-goldens/#reference",
   "internal": 0,
   "content": "## reference\n\n[tests]({{SPEC}}#tests), [assert]({{SPEC}}#assert), [expect_fault]({{SPEC}}#expect-fault), [fault record]({{SPEC}}#fault-record), [golden outputs]({{SPEC}}#golden-outputs), [golden]({{GLOSSARY}}#golden)\n\nNext: [201-06, the workbench](06-workbench.md)."
  },
  {
   "id": "cu-201-06:cu-201-2",
   "edition": "CU-201.2",
   "title": "CU-201.2",
   "clauses": "",
   "url": "/university/201/06-workbench/",
   "internal": 0,
   "content": "# 201-06: the workbench\n\n<a id=\"201-06\"></a>This is lesson 201-06 of CU-201.2, checked against cint 0.2.0.\n\n*You will open a session on a module and ask it questions. Then you will run a year of interest in one command. You will find the first day the balance reached 1040.00 and walk through the operations of an entry that faulted.*\n\nThis lesson needs cint on your own computer, with the debugging tools from [setup](../setup.md)."
  },
  {
   "id": "cu-201-06:the-module",
   "edition": "CU-201.2",
   "title": "the module",
   "clauses": "",
   "url": "/university/201/06-workbench/#the-module",
   "internal": 0,
   "content": "## the module\n\nSave this as `savings.ci`:\n\n```ci\n// savings.ci: a savings balance in cents, with interest paid daily.\n\nexport I64 balance = 100_000;   // 1000.00\n\nI64 daily_interest(I64 cents, I64 basis_points) {\n    return muldiv(I64, cents, basis_points, 10_000 * 365, half_even);\n}\n\n// One day: add a day's interest at a yearly rate in basis points.\nexport void day(I64 basis_points) {\n    balance += daily_interest(balance, basis_points);\n}\n```\n\nEvery cint file is a module. This one has no `main`, so it does nothing on its own: other code uses what it exports. `balance` and `day` are exported; `daily_interest` is not. A basis point is a hundredth of a percent, so 450 basis points is 4.50 percent a year."
  },
  {
   "id": "cu-201-06:open-a-session",
   "edition": "CU-201.2",
   "title": "open a session",
   "clauses": "",
   "url": "/university/201/06-workbench/#open-a-session",
   "internal": 0,
   "content": "## open a session\n\nIn VS Code, open the folder that holds `savings.ci` and choose **Terminal > New Terminal**. Any other terminal in that folder works the same way. Type:\n\n```text\n$ cint workbench savings.ci\ncint workbench   profile cint-core-1   backend cpu-sir-interp   new session\nloaded savings (savings.ci)\nci[2]>\n```\n\n`cint repl` opens the same session. The first line says where entries run: `cpu-sir-interp` is the interpreter. The prompt counts **entries**, the things you type that run; loading the module was entry 1."
  },
  {
   "id": "cu-201-06:ask-it-questions",
   "edition": "CU-201.2",
   "title": "ask it questions",
   "clauses": "",
   "url": "/university/201/06-workbench/#ask-it-questions",
   "internal": 0,
   "content": "## ask it questions\n\nType an expression and the workbench answers with its exact value and its type:\n\n```text\nci[2]> savings.balance\n= 100000 : I64\nci[3]> :inspect savings.balance /scale 100\nsavings.balance : I64   shown with scale 100\n  exact   1000.0\n  raw     100000\nci[3]> savings.daily_interest(1, 2)\nerror[C3008]: undefined or unusable name\n  --> entry 3:1:9\n   |\n 1 | savings.daily_interest(1, 2)\n   |         ^\n   |\nci[4]>\n```\n\n- A name from the module is written with the module's name in front: `savings.balance`.\n- A line that starts with a colon is a **command**. Commands are not entries, so the count stays at 3. `:inspect` shows a value in other forms. `/scale 100` divides it by 100, so cents read as dollars, and `/all` adds hexadecimal, binary and the bytes in memory.\n- The session sees only what the module exports. `daily_interest` is not exported, so the third entry is an error, and an entry with an error still counts. A position inside an entry reads `entry 3:1:9`: entry 3, line 1, character 9."
  },
  {
   "id": "cu-201-06:run-a-year",
   "edition": "CU-201.2",
   "title": "run a year",
   "clauses": "",
   "url": "/university/201/06-workbench/#run-a-year",
   "internal": 0,
   "content": "## run a year\n\nA statement changes the module's state. Save the state first, then pay one day of interest:\n\n```text\nci[4]> :checkpoint start\ncheckpoint start   #1   revisions: savings@r1\nci[4]> savings.day(450);\nci[5]> savings.balance\n= 100012 : I64\n```\n\nA **checkpoint** is a saved copy of the state, under a name you choose, and `#1` is its number. `savings@r1` names the revision of the module it holds. Each time a module's code changes in a session, its revision number goes up. One day at 4.50 percent adds 12 cents.\n\nTo run the other 364 days, declare a function in the session and run it with `:run`:\n\n```text\nci[6]> export void d() { savings.day(450); }\nd : () -> void   revision session@r1\nci[7]> :run d() 364\nci[371]> savings.balance\n= 104629 : I64\nci[372]> :checkpoint year\ncheckpoint year   #2   revisions: session@r1, savings@r1\n```\n\n`:run` calls an exported function of the session, here `d`, as many times as you say, and each call is one entry. The session's own code has revisions too, so `d` is `session@r1`. The year ends at 1046.29. Day 1 was entry 4, and days 2 to 365 are entries 7 to 370, so from day 2 on, the entry number is 5 more than the day."
  },
  {
   "id": "cu-201-06:compare-two-states",
   "edition": "CU-201.2",
   "title": "compare two states",
   "clauses": "",
   "url": "/university/201/06-workbench/#compare-two-states",
   "internal": 0,
   "content": "## compare two states\n\n`:diff` compares the current state with a checkpoint, one name at a time:\n\n```text\nci[372]> :diff start\nbinding           status      differing   first canonical difference\nsavings.balance   differs     1           104629 here, 100000 in start\n```\n\nA **binding** is a name with its value. Only `balance` changed."
  },
  {
   "id": "cu-201-06:find-the-first-day",
   "edition": "CU-201.2",
   "title": "find the first day",
   "clauses": "",
   "url": "/university/201/06-workbench/#find-the-first-day",
   "internal": 0,
   "content": "## find the first day\n\nTo find the day the balance first reached 1040.00, run `:replay` with `--when`:\n\n```text\nci[372]> :replay start --when savings.balance >= 104_000\nsavings.balance >= 104_000 first holds at entry 322\nbisection: 11 probes over 367 boundaries; PRED is taken as monotone\n```\n\nEntry 322 is day 317. A **boundary** is the point after an entry, where the workbench can compare or test the state, and there are 367 of them since `start`. The workbench did not test the condition at every one. It replayed from the checkpoint to the middle, tested there and halved the range, 11 probes in all. This is called bisection. It works only when the condition stays true once it holds. That is what `PRED is taken as monotone` means. Here it does, because the balance only grows. For a condition that can turn false again, the answer may not be the first entry where it holds."
  },
  {
   "id": "cu-201-06:a-fault-in-the-session",
   "edition": "CU-201.2",
   "title": "a fault in the session",
   "clauses": "",
   "url": "/university/201/06-workbench/#a-fault-in-the-session",
   "internal": 0,
   "content": "## a fault in the session\n\nPut the balance near the largest `I64` and pay a day of interest:\n\n```text\nci[372]> savings.balance = I64.max - 100;\nci[373]> savings.day(450);\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> savings.ci:11:13\n   |\n11 |     balance += daily_interest(balance, basis_points);\n   |             ^ add.checked.i64\n   |\n   = operation: add.checked.i64\n   = operand-count: 2\n   = operand: I64 9223372036854775707\n   = operand: I64 1137128059338260\n   = exact:   9224509164914113967\n   = limit:   I64 9223372036854775807\n   = revision: 03b315aa3c24f675b5fd489839960d132c9a000f478a1cb8310eee016fb5609f\n   = source-map: none\n   = address: none\n   = stack-depth: 1\n   = called from: entry 373:1:9\n   = fuel-consumed: 3 (not part of the fault record)\n   = state: no store completed in this entry; context reset\n   = noncanonical: not part of the fault record\n   = stack-source: entry 373:1:9\n   |\n 1 | savings.day(450);\n   |         ^\n   |\n   = workbench-position: entry 373\n   = site: day#5\n   = backend: cpu-sir-interp\nci[374]> savings.balance\n= 9223372036854775707 : I64\n```\n\nThis is the layout that `cint run` prints. The lines from `operation` to `stack-depth` are the fault record, and every way of running the program reports the same values in them. The lines after `= noncanonical` are not part of the record. They say where the workbench found the fault: the source of each call, the entry, the operation's place in `day` and where the entry ran.\n\nThe interest was computed, but adding it to the balance went past the limit. `no store completed in this entry` means the entry changed nothing: `balance` still holds the value from before it. `context reset` means the session cleared the fault so that the next entry can run."
  },
  {
   "id": "cu-201-06:a-fault-in-the-session-p1",
   "edition": "CU-201.2",
   "title": "a fault in the session (part 2)",
   "clauses": "",
   "url": "/university/201/06-workbench/#a-fault-in-the-session",
   "internal": 0,
   "content": "`:trace` replays an entry and lists every counted operation it made, in order. `:trace fault` picks the last entry that faulted:\n\n```text\nci[375]> :trace fault\nentry 373   savings.day(450);   evaluator cpu-sir-interp, by replay\n  ord  position           operation              operands                 value\n    0  entry 373:1:9      call                   450\n    1  savings.ci:11:16   call                   9223372036854775707, 450\n    2  savings.ci:6:52    mul.checked.i64        10000, 365               3650000\n    3  savings.ci:6:12    muldiv.checked.i64.i64.half_even 9223372036854775707, 450, 3650000 1137128059338260\n    -  savings.ci:11:16   return                                          1137128059338260\n    4  savings.ci:11:13   add.checked.i64        9223372036854775707, 1137128059338260 E_OVERFLOW\n```\n\nRead it from the top: the call to `day`, the call to `daily_interest`, the multiplication `10_000 * 365`, the `muldiv`, the return and the addition that faulted. Each row holds the operands the operation saw and the value it gave. The row marked `-` is the return, which is listed but not counted. Every plain operator is checked, including the multiplication `10_000 * 365`."
  },
  {
   "id": "cu-201-06:go-back",
   "edition": "CU-201.2",
   "title": "go back",
   "clauses": "",
   "url": "/university/201/06-workbench/#go-back",
   "internal": 0,
   "content": "## go back\n\n`:restore` makes a checkpoint the current state again:\n\n```text\nci[375]> :restore year\nsaved current state as auto-1\nrestored year   #2\nci[375]> savings.balance\n= 104629 : I64\n```\n\nBefore it restores `year`, the workbench saves the current state as a checkpoint named `auto-1`, which you can restore in turn.\n\n`:undo` goes back one entry:\n\n```text\nci[376]> savings.balance = 0;\nci[377]> :undo\nsaved current state as auto-2\nback to the state before entry 376\nci[377]> savings.balance\n= 104629 : I64\n```"
  },
  {
   "id": "cu-201-06:check-the-interpreter-against-c",
   "edition": "CU-201.2",
   "title": "check the interpreter against C",
   "clauses": "",
   "url": "/university/201/06-workbench/#check-the-interpreter-against-c",
   "internal": 0,
   "content": "## check the interpreter against C\n\nThe session runs entries in the interpreter. `--check cpu-c17` runs each call a second time in your C compiler's build of the module and compares the two:\n\n```text\nci[378]> :run d() 3 --check cpu-c17\ncheck: cpu-sir-interp and cpu-c17 agree at 3 boundaries\nci[381]> savings.balance\n= 104668 : I64\n```\n\nAfter each of the 3 calls, the interpreter and the compiled C held the same state. The first `--check` of a module also prints a line as it builds the module with your C compiler, and later sessions reuse that build. If they ever differ, `:run` stops at the first call where they do. Such a difference is a defect in cint. Report it with the session."
  },
  {
   "id": "cu-201-06:go-to-any-entry",
   "edition": "CU-201.2",
   "title": "go to any entry",
   "clauses": "",
   "url": "/university/201/06-workbench/#go-to-any-entry",
   "internal": 0,
   "content": "## go to any entry\n\n`:goto` makes the state at the end of any entry current, by replay:\n\n```text\nci[382]> :goto 322\nsaved current state as auto-3\nat the end of entry 322, reached by replay\nlater entries go on branch entry-322, from auto-4\nci[382]> savings.balance\n= 104005 : I64\nci[383]> :goto 321\nsaved current state as auto-5\nat the end of entry 321, reached by replay\nlater entries go on branch entry-321, from auto-6\nci[383]> savings.balance\n= 103992 : I64\n```\n\nAt the end of day 316 the balance was 1039.92, and at the end of day 317 it was 1040.05, which agrees with the answer of `--when`. Each `:goto` saves two checkpoints: the state you left, as `auto-3`, and the state it reached, as `auto-4`. An entry typed now starts a **branch**, a second line of entries from this point, and the entries of the year stay as they were. Entry numbers keep counting across branches, so the prompt still says 382. `:goto fault` goes to the end of the last entry that faulted.\n\nTo leave, type `:quit --yes`. A plain `:quit` warns you first, because an unsaved session is lost when it ends. A second `:quit` ends it. `:save FOLDER` keeps a session to reopen with `:open FOLDER`."
  },
  {
   "id": "cu-201-06:why-it-can-go-back",
   "edition": "CU-201.2",
   "title": "why it can go back",
   "clauses": "",
   "url": "/university/201/06-workbench/#why-it-can-go-back",
   "internal": 0,
   "content": "## why it can go back\n\nEvery entry gives the same result each time it runs: the same values, the same output, the same fault at the same operation. The workbench therefore does not record what the machine did. It keeps the checkpoints and the entries typed since, and it reaches any point by replaying from the nearest checkpoint. The checks in this lesson rest on the same fact: replaying entry 373 for `:trace` faulted at the same operation with the same operands, and so will every replay of it."
  },
  {
   "id": "cu-201-06:elsewhere",
   "edition": "CU-201.2",
   "title": "elsewhere",
   "clauses": "",
   "url": "/university/201/06-workbench/#elsewhere",
   "internal": 0,
   "content": "## elsewhere\n\nIn C, going back takes a debugger that records the run as it goes, such as GDB's `record` command, rr on Linux or Time Travel Debugging in WinDbg on Windows. GDB's `checkpoint` command can also save a copy of the running process to return to. Python's debugger, pdb, has no way to run backward."
  },
  {
   "id": "cu-201-06:walk-through",
   "edition": "CU-201.2",
   "title": "walk-through",
   "clauses": "",
   "url": "/university/201/06-workbench/#walk-through",
   "internal": 0,
   "content": "## walk-through\n\n**`export void d() { savings.day(450); }`** is declared in the session, not in `savings.ci`. The session is a module of its own, and `:run` calls its exports.\n\n**`10_000 * 365`** turns a yearly rate into one day's interest. A rate in basis points is a share of 10,000, and a year has 365 days, so `muldiv` multiplies the balance by the rate and divides by both at once. It rounds a tie to even and cannot overflow in between.\n\n**`I64.max - 100`** is 9223372036854775707, the largest `I64` less 100."
  },
  {
   "id": "cu-201-06:try-this",
   "edition": "CU-201.2",
   "title": "try this",
   "clauses": "",
   "url": "/university/201/06-workbench/#try-this",
   "internal": 0,
   "content": "## try this\n\n1. After `:run d() 364`, ask `:replay start --changed savings.balance`, which names the last entry since `start` that changed `balance`. Which entry does it name, and why that one?\n2. Find the first day the balance reaches 1045.00, then check it with two `:goto` commands.\n3. Type `:restore start`, declare `d` again with 9000 basis points (90 percent a year) and run it 365 times. The year at 4.50 percent gained 46.29. Is the gain at 90 percent more or less than twenty times that, and why?"
  },
  {
   "id": "cu-201-06:reference",
   "edition": "CU-201.2",
   "title": "reference",
   "clauses": "",
   "url": "/university/201/06-workbench/#reference",
   "internal": 0,
   "content": "## reference\n\n[the workbench]({{SPEC}}#workbench), [checkpoints]({{SPEC}}#checkpoints), [replay]({{SPEC}}#replay), [fault record]({{SPEC}}#fault-record), [muldiv]({{SPEC}}#muldiv)\n\nNext: [201-07, debugging by comparison](07-debugging-by-comparison.md)."
  },
  {
   "id": "cu-201-07:cu-201-2",
   "edition": "CU-201.2",
   "title": "CU-201.2",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/",
   "internal": 0,
   "content": "# 201-07: debugging by comparison\n\n<a id=\"201-07\"></a>This is lesson 201-07 of CU-201.2, checked against cint 0.2.0.\n\n*You will compare runs to find a bug. You will make one change at a time against a golden, read two fault reports side by side and check three ways of running one program against each other.*"
  },
  {
   "id": "cu-201-07:the-method",
   "edition": "CU-201.2",
   "title": "the method",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#the-method",
   "internal": 0,
   "content": "## the method\n\nA cint program run twice by one release prints the same bytes and, when it faults, the same fault report. So a run is a fixed thing you can compare, and a difference between two runs points at a cause. The steps run in this order:\n\n| Step | What you do | With |\n|---|---|---|\n| 1 | Reproduce: run the program twice and compare. | `cint run` and `diff` |\n| 2 | Keep a golden of a run you checked. | the output, and the reference's record ([201-05](05-tests-and-goldens.md)) |\n| 3 | Change one thing, run again and compare with the golden. | `diff` |\n| 4 | Read the first difference; the ones after it often follow from it. | `diff` |\n| 5 | Read two fault reports as data. | the fault report |\n| 6 | Read the lines that identify the run: `revision` and `fuel-consumed`. | the fault report and the record |\n| 7 | Check that the ways of running the program agree. | `cint run`, `cint debug` and the reference |\n| 8 | Locate the operation that faulted and keep the case. | `cint debug locate --save-case` |\n\nWhen the code is a module, the workbench of [201-06](06-workbench.md) adds rewinding and bisection to steps 4 and 8."
  },
  {
   "id": "cu-201-07:the-program",
   "edition": "CU-201.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#the-program",
   "internal": 0,
   "content": "## the program\n\nAdler-32 is the checksum inside every zlib stream, including the image data of PNG files. It keeps two sums, `a` and `b`, and takes both remainders by 65,521 after every byte:\n\n```ci\n// adler.ci: the Adler-32 checksum, which zlib and PNG files use.\n\nconst U32 MOD = 65_521;\n\nU32 adler32[n](in U8[n] data) {\n    U32 a = 1;\n    U32 b = 0;\n    for i in 0..n {\n        a = (a + (data[i] as U32)) % MOD;\n        b = (b + a) % MOD;\n    }\n    return (b << 16) | a;\n}\n\nvoid main() {\n    U8[20_000] letters;\n    U8[20_000] high;\n    for i in 0..20_000 {\n        letters[i] = 97;    // the letter a\n        high[i] = 255;      // the largest byte\n    }\n    U32 w = adler32(\"Wikipedia\");\n    \"Wikipedia     {w:x}\\n\";\n    U32 l = adler32(letters);\n    \"20000 a       {l:x}\\n\";\n    U32 h = adler32(high);\n    \"20000 x 255   {h:x}\\n\";\n}\n```\n\n```text\n$ cint run adler.ci\nWikipedia     11e60398\n20000 a       62f99bd4\n20000 x 255   9f51d664\n```\n\nPython's `zlib.adler32` gives the same three values."
  },
  {
   "id": "cu-201-07:steps-1-and-2-reproduce-then-keep-a-golden",
   "edition": "CU-201.2",
   "title": "steps 1 and 2: reproduce, then keep a golden",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#steps-1-and-2-reproduce-then-keep-a-golden",
   "internal": 0,
   "content": "## steps 1 and 2: reproduce, then keep a golden\n\n```text\n$ cint run adler.ci > run1.txt\n$ cint run adler.ci > run2.txt\n$ diff run1.txt run2.txt\n$ cint run adler.ci > golden.txt\n$ python3 -m cint_ref run adler.ci > adler.expect\n```\n\n`diff` prints nothing: the two runs are the same, byte for byte. If two runs of one program by one release ever differ, that is a defect in cint. Check the three values by hand, here against zlib, and save the golden and the reference's record. In PowerShell on Windows, compare the two files with `fc.exe /b run1.txt run2.txt`, which says `no differences encountered` when they match. Save the record with `cmd /c`, as in [201-05](05-tests-and-goldens.md). Type `fc.exe` in full, since `fc` alone is the PowerShell alias for `Format-Custom`. To see which lines differ, use VS Code's **Select for Compare**, as in [401-01](../401/01-ledger.md)."
  },
  {
   "id": "cu-201-07:step-3-one-change",
   "edition": "CU-201.2",
   "title": "step 3: one change",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#step-3-one-change",
   "internal": 0,
   "content": "## step 3: one change\n\nzlib does not take the remainders after every byte. It adds up a block of bytes first and takes the remainders once per block, which saves work. Replace `adler32` with this version:\n\n```ci\n// Take the remainders once per block, not once per byte. zlib uses\n// 5552, the largest block after which b still fits in a U32.\nconst I64 BLOCK = 5_552;\n\nU32 adler32[n](in U8[n] data) {\n    U32 a = 1;\n    U32 b = 0;\n    I64 start = 0;\n    while (start < n) {\n        I64 end = start + BLOCK;\n        if (end > n) {\n            end = n;\n        }\n        for i in start..end {\n            a += data[i] as U32;\n            b += a;\n        }\n        a %= MOD;\n        b %= MOD;\n        start = end;\n    }\n    return (b << 16) | a;\n}\n```\n\nRun it into a new file and compare:\n\n```text\n$ cint run adler.ci > after.txt\n$ diff golden.txt after.txt\n$ python3 -m cint_ref check adler.ci adler.expect\nadler.expect: line 6 differs\n  expected: fuel-consumed 60013\n  actual:   fuel-consumed 60022\n```\n\nThe output matches the golden. The record shows that the path changed, which is what the change was for. The first version takes two remainders for every byte, 80,018 in all, and the block version takes two for every block, 18 in all. Fuel is charged at each call and at each pass through a loop, not for each operation, so the block version's 9 passes through `while` add 9. Fuel measures the path a run takes, not its speed. Save the new record in a step of its own."
  },
  {
   "id": "cu-201-07:step-4-a-second-change-and-the-first-difference",
   "edition": "CU-201.2",
   "title": "step 4: a second change, and the first difference",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#step-4-a-second-change-and-the-first-difference",
   "internal": 0,
   "content": "## step 4: a second change, and the first difference\n\nNow raise `BLOCK` to `8_192` and leave the comment as it was. Run and compare again:\n\n```text\n$ cint run adler.ci > after.txt\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> adler.ci:20:15\n   |\n20 |             b += a;\n   |               ^ add.checked.u32\n   |\n   = operation: add.checked.u32\n   = operand-count: 2\n   = operand: U32 4294283833\n   = operand: U32 1480021\n   = exact:   4295763854\n   = limit:   U32 4294967295\n   = revision: 4d94cdfe0404d5729f9866a699d45a763db38646e80ce3f71a1a3132eb1b6099\n   = source-map: none\n   = address: none\n   = stack-depth: 1\n   = called from: adler.ci:40:13\n   = fuel-consumed: 45822 (not part of the fault record)\n   = state: the program stopped; stdout holds what it wrote before the fault\n$ diff golden.txt after.txt\n3d2\n< 20000 x 255   9f51d664\n```\n\nThe fault report appears in the terminal and not in `after.txt`, because cint writes it to a separate stream, standard error. The output stops after line 2, so the first difference is line 3: the third message never finished. The report says why. Adding `a` to `b` at line 20 went past the largest `U32`, 4294967295, while the call at line 40 computed the checksum of the third message.\n\nThe operands say where in the message. `a` started at 1 and grows by 255 with each byte, so `a` = 1480021 = 1 + 255 \u00d7 5804: the sum broke on byte 5804 of the third message, in its first block. A block of 8192 bytes of 255 is more than `b` can hold."
  },
  {
   "id": "cu-201-07:step-5-two-fault-reports-as-data",
   "edition": "CU-201.2",
   "title": "step 5: two fault reports as data",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#step-5-two-fault-reports-as-data",
   "internal": 0,
   "content": "## step 5: two fault reports as data\n\nChange the third message to 20,000 bytes of 200 (`high[i] = 200;`) and run again. The report starts the same way:\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> adler.ci:20:15\n   |\n20 |             b += a;\n   |               ^ add.checked.u32\n   |\n   = operation: add.checked.u32\n   = operand-count: 2\n   = operand: U32 4294842753\n   = operand: U32 1310801\n   = exact:   4296153554\n   ...\n```\n\nThe code, the operation and the position are the same, and the operands are new. Now `a` = 1310801 = 1 + 200 \u00d7 6554, so the smaller bytes took 6554 of them to break the sum. Read two reports this way:\n\n| Two reports with | Mean |\n|---|---|\n| the same code, operation, position and operands | the same fault, reproduced |\n| the same position and new operands | the same bug, reached by new data |\n| a new position | a new fault, to read on its own |\n\nPut the 255 back."
  },
  {
   "id": "cu-201-07:step-6-the-lines-that-identify-a-run",
   "edition": "CU-201.2",
   "title": "step 6: the lines that identify a run",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#step-6-the-lines-that-identify-a-run",
   "internal": 0,
   "content": "## step 6: the lines that identify a run\n\nAdd a comment line at the top of `adler.ci` and run again:\n\n```text\n  --> adler.ci:21:15\n   ...\n   = revision: 4d94cdfe0404d5729f9866a699d45a763db38646e80ce3f71a1a3132eb1b6099\n   ...\n   = called from: adler.ci:41:13\n   = fuel-consumed: 45822 (not part of the fault record)\n```\n\nEvery position moved down one line, and the `revision` stayed the same. The revision is a digest of the compiled program. A comment or a blank line does not change it, while renaming a variable or changing a value does. The module's name is part of it too, so keep editing `adler.ci` instead of saving copies under new names. When a report moves, the revision says whether the code changed or only moved. The fuel is the same too: the run took the same path to the same fault."
  },
  {
   "id": "cu-201-07:step-7-three-ways-to-run-it",
   "edition": "CU-201.2",
   "title": "step 7: three ways to run it",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#step-7-three-ways-to-run-it",
   "internal": 0,
   "content": "## step 7: three ways to run it\n\n`cint run` compiles the program to C and runs it with your C compiler. `cint debug locate`, in step 8, runs it in the interpreter. The reference runs it in Python. All three must agree, and here they do. This is the reference's record of the faulting run:\n\n```text\n$ python3 -m cint_ref run adler.ci > fault.expect\n$ cat fault.expect\ncase adler\nsource reference\noutcome fault\nstdout-bytes 46\nstdout-sha256 5f8d699b8acfd3a2c790a21a2df45c68e91fab8e3482b95125864a5490a056b5\nfuel-consumed 45822\nfault.code E_OVERFLOW\nfault.operation add.checked.u32\nfault.operand U32 4294283833\nfault.operand U32 1480021\nfault.exact 4295763854\nfault.limit U32 4294967295\nfault.position adler.ci:20:15\nfault.revision self\nfault.address none\nfault.stack-depth 1\n```\n\nIt holds the same code, operation, operands, position and fuel as the compiled run. The reference writes `self` where the compiled run prints the revision's digest. If two of the three ever disagree, the program is not the problem: that is a defect in cint, and the case of step 8 is what to report.\n\nFor code you run in the workbench, `cint debug diff` makes the same check from the terminal. It takes a case of calls to exported functions, like one saved in a session, and refuses a case of a whole program such as `overflow.case`. In the session of 201-06, `:checkpoint s`, then `:run d() 3`, then `:save-case three.case` saves the three calls as a case. `cint debug diff` runs it in your C compiler's build and in the interpreter and compares the two after every entry:\n\n```text\n$ cint debug diff three.case\ncase       three.case   3 boundaries   density entry\nreference  cpu-c17\ncandidate  cpu-sir-interp\nboundaries 3 of 3 compared\noutcome    agree\n```"
  },
  {
   "id": "cu-201-07:step-7-three-ways-to-run-it-p1",
   "edition": "CU-201.2",
   "title": "step 7: three ways to run it (part 2)",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#step-7-three-ways-to-run-it",
   "internal": 0,
   "content": "In this output, `reference` names the side the other is compared against, here the C build, and not the Python reference. `cint debug diff` exits with status 0 when the two agree and 3 when they do not."
  },
  {
   "id": "cu-201-07:step-8-locate-the-operation-and-keep-the-case",
   "edition": "CU-201.2",
   "title": "step 8: locate the operation and keep the case",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#step-8-locate-the-operation-and-keep-the-case",
   "internal": 0,
   "content": "## step 8: locate the operation and keep the case\n\n`cint debug locate` runs the program in the interpreter, replays it to the fault and lists the last operations before it. `--save-case` keeps the run. The first lines say what it searched. A whole program is one entry, so its run has one boundary, at its end, and the fault is there. The count of trace events is every operation the interpreter replayed, and the workbench's `:trace` lists them all.\n\n```text\n$ cint debug locate adler.ci --save-case overflow.case\nprogram    adler.ci   evaluator cpu-sir-interp, recorded as the case overflow.case\ntarget     boundary 1 of 1, the program entry: the first fault, reproduced by replay\nbracket    the initial state; then boundary 1\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> adler.ci:20:15\n   ...\nthe last 20 counted operations of boundary 1, of 189084 trace events (:trace shows them all)\n  ord  position           operation              operands                 value\n   ...\n189072                     add.wrap.i64           5801, 1                  5802\n189073  adler.ci:19:22     index.checked.u8       5802\n189074  adler.ci:19:26     as.checked.u8.u32      255                      255\n189075  adler.ci:19:15     add.checked.u32        1479511, 255             1479766\n189076  adler.ci:20:15     add.checked.u32        4292804067, 1479766      4294283833\n189077                     add.wrap.i64           5802, 1                  5803\n189078  adler.ci:19:22     index.checked.u8       5803\n189079  adler.ci:19:26     as.checked.u8.u32      255                      255\n189080  adler.ci:19:15     add.checked.u32        1479766, 255             1480021\n189081  adler.ci:20:15     add.checked.u32        4294283833, 1480021      E_OVERFLOW\n```"
  },
  {
   "id": "cu-201-07:step-8-locate-the-operation-and-keep-the-case-p1",
   "edition": "CU-201.2",
   "title": "step 8: locate the operation and keep the case (part 2)",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#step-8-locate-the-operation-and-keep-the-case",
   "internal": 0,
   "content": "Each byte is five rows. The loop counts `i` up by one in the rows with no position. Then it reads `data[i]`, widens it to `U32` and adds it to `a`, and last it adds `a` to `b`. `b` climbs toward the limit, 4292804067, then 4294283833, and the next addition faults. The index is 5803, counted from 0, which is byte 5804, as step 4 worked out from the operands.\n\n`overflow.case` holds the program's source and its run. Copy it to another folder and `cint debug locate overflow.case` reproduces the same fault from the case alone, without `adler.ci`. It is the file to attach to a bug report."
  },
  {
   "id": "cu-201-07:the-fix",
   "edition": "CU-201.2",
   "title": "the fix",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#the-fix",
   "internal": 0,
   "content": "## the fix\n\nPut `BLOCK` back to `5_552`, run and compare with the golden: the output matches. zlib's source gives 5_552 as the largest block length *n* for which 255*n*(*n* + 1)/2 + (*n* + 1)(65,521 - 1) is at most 2<sup>32</sup> - 1. The expression is the largest `b` can reach after a block of bytes of 255 when `a` and `b` start just below 65,521."
  },
  {
   "id": "cu-201-07:elsewhere",
   "edition": "CU-201.2",
   "title": "elsewhere",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#elsewhere",
   "internal": 0,
   "content": "## elsewhere\n\nThe same function in C, with `uint32_t` sums and a block of 8192, built with GCC 13.3 and `-O2 -Wall -Wextra` on Ubuntu 24.04 for x86-64, gives no warning and exits with status 0. It prints `9caed664` for the third message where Adler-32 is `9f51d664`, because `uint32_t` arithmetic wraps. Clang has a check for this, `-fsanitize=unsigned-integer-overflow`, which is off unless a build turns it on. Built with Clang 18.1 and that check in its trapping form, the program stopped at the third message. Without such a check, only a golden or a test against a known value catches the wrong checksum. Written in Python, the same function gives the right checksum with a block of any size, because Python's integers have no fixed size."
  },
  {
   "id": "cu-201-07:walk-through",
   "edition": "CU-201.2",
   "title": "walk-through",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#walk-through",
   "internal": 0,
   "content": "## walk-through\n\n**`data[i] as U32`** widens a byte to `U32`. Widening never fails, and the trace shows it as its own operation, `as.checked.u8.u32`.\n\n**`(b << 16) | a`** puts `b` in the top 16 bits and `a` in the bottom 16. Both are below 65,521 at this point, so the shift cannot overflow.\n\n**`while (start < n)`** walks the data a block at a time. The `if` shortens the last block, so `end` never passes `n`."
  },
  {
   "id": "cu-201-07:try-this",
   "edition": "CU-201.2",
   "title": "try this",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#try-this",
   "internal": 0,
   "content": "## try this\n\n1. With `BLOCK` at `8_192`, change `b += a;` to `b +%= a;`, which wraps as C does. The program runs to the end. Which line of the golden differs, and which line of the record?\n2. Find the largest `BLOCK` for which this program runs without a fault. Is it safe for every message? Compare it with 5552.\n3. Run `cint debug locate` on the version with bytes of 200 and compare its last operations with the version with 255."
  },
  {
   "id": "cu-201-07:reference",
   "edition": "CU-201.2",
   "title": "reference",
   "clauses": "",
   "url": "/university/201/07-debugging-by-comparison/#reference",
   "internal": 0,
   "content": "## reference\n\n[fault record]({{SPEC}}#fault-record), [revision]({{SPEC}}#revision), [fuel]({{SPEC}}#fuel), [cases]({{SPEC}}#cases), [wrapping and saturating operators]({{SPEC}}#wrapping-saturating), [golden]({{GLOSSARY}}#golden)\n\nNext: [201-08, control flow](08-control-flow.md)."
  },
  {
   "id": "cu-201-08:cu-201-2",
   "edition": "CU-201.2",
   "title": "CU-201.2",
   "clauses": "",
   "url": "/university/201/08-control-flow/",
   "internal": 0,
   "content": "# 201-08: control flow\n\n<a id=\"201-08\"></a>This is lesson 201-08 of CU-201.2, checked against cint 0.2.0.\n\n*You will write cint's loops and branches and see where they differ from C: braces are required, `switch` never falls through by accident and a loop counter faults instead of wrapping.*"
  },
  {
   "id": "cu-201-08:the-program",
   "edition": "CU-201.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/201/08-control-flow/#the-program",
   "internal": 0,
   "content": "## the program\n\nThe Collatz rule halves an even number and turns an odd number n into 3n + 1. Every positive whole number checked so far reaches 1 when the rule is repeated, and nobody has proved that all do. This program counts the steps:\n\n```ci\n// Collatz paths: the steps a start takes to reach 1,\n// halving each even number and tripling each odd one, plus one.\n\nI64 next(I64 n) {\n    if (n % 2 == 0) {\n        return n / 2;\n    }\n    return 3 * n + 1;\n}\n\nI64 steps_to_one(I64 start) {\n    I64 n = start;\n    I64 taken = 0;\n    while (n != 1) {\n        n = next(n);\n        taken++;\n    }\n    return taken;\n}\n\nvoid main() {\n    // Starts 1, 10, 100, 1000: the range form has no step, so this is a C-form loop.\n    for (I64 start = 1; start <= 1_000; start *= 10) {\n        \"{start:>4} takes {steps_to_one(start)} steps\\n\";\n    }\n\n    // Sort the starts below 1000 by how long they take.\n    I64 quick = 0;\n    I64 middling = 0;\n    I64 slow = 0;\n    for start in 1..1_000 {\n        switch (steps_to_one(start)) {\n            case 0..=19:\n                quick++;\n            case 20..=99:\n                middling++;\n            default:\n                slow++;\n        }\n    }\n    \"below 1000: {quick} quick, {middling} middling, {slow} slow\\n\";\n\n    // The first start whose path climbs past 100,000.\n    I64 found = 0;\n    I64 first_over = 0;\n    starts: for start in 1..1_000 {\n        I64 n = start;\n        while (n != 1) {\n            n = next(n);\n            if (n > 100_000) {\n                found = start;\n                first_over = n;\n                break starts;\n            }\n        }\n    }\n    \"first past 100000: {found}, first goes over 100000 at {first_over}\\n\";\n}\n```"
  },
  {
   "id": "cu-201-08:run-it",
   "edition": "CU-201.2",
   "title": "run it",
   "clauses": "",
   "url": "/university/201/08-control-flow/#run-it",
   "internal": 0,
   "content": "## run it\n\n```text\n$ cint run collatz.ci\n   1 takes 0 steps\n  10 takes 6 steps\n 100 takes 25 steps\n1000 takes 111 steps\nbelow 1000: 133 quick, 618 middling, 248 slow\nfirst past 100000: 703, first goes over 100000 at 148444\n```\n\nThe same rule written in Python 3.13 on Ubuntu 24.04 prints the same six lines."
  },
  {
   "id": "cu-201-08:if-and-while",
   "edition": "CU-201.2",
   "title": "`if` and `while`",
   "clauses": "",
   "url": "/university/201/08-control-flow/#if-and-while",
   "internal": 0,
   "content": "## `if` and `while`\n\n`if`, `else if`, `else` and `while` read as they do in C, with one rule C does not have: every body needs its braces, even a body of one statement.\n\n```ci\nvoid main() {\n    I64 c = 3;\n    if (c > 2) \"big\\n\";\n}\n```\n\n```text\nerror[C1043]: missing parentheses or braces\n  --> braces.ci:3:16\n   |\n 3 |     if (c > 2) \"big\\n\";\n   |                ^\n   |\n```\n\nAn assignment is a statement, not a value, so `if (x = 5)` is an error where C would assign and test:\n\n```ci\nvoid main() {\n    I64 x = 3;\n    if (x = 5) {\n        \"five\\n\";\n    }\n}\n```\n\n```text\nerror[C1041]: assignment in a condition\n  --> assign.ci:3:9\n   |\n 3 |     if (x = 5) {\n   |         ^\n   |\n```\n\n`taken++;` is a statement too, and a checked one: at the largest value of its type it faults. It cannot appear inside an expression, so `a[i++]` is an error. cint 0.2.0 has no `do`-`while` loop; write a `while` loop instead."
  },
  {
   "id": "cu-201-08:two-kinds-of-for",
   "edition": "CU-201.2",
   "title": "two kinds of `for`",
   "clauses": "",
   "url": "/university/201/08-control-flow/#two-kinds-of-for",
   "internal": 0,
   "content": "## two kinds of `for`\n\nThe range form counts through a range of `I64` values:\n\n- `for i in 0..n` runs `i` from 0 up to n - 1.\n- `for i in 1..=n` runs `i` from 1 up to n, including n.\n\nThe bounds are computed once, before the first pass, and the body cannot assign to `i` (error C2052). An empty range, such as `5..5`, runs the body no times. cint 0.2.0 does not support a step on the range form, so any other step needs the C form:\n\n```ci\nfor (I64 start = 1; start <= 1_000; start *= 10) {\n```\n\nThe C form has the three parts C has: a declaration, a condition and an update. The update can be any statement without a block, such as `start *= 10`. Its variable can be assigned in the body.\n\nBecause `++` is checked, a C-form loop cannot run past the end of its type:\n\n```ci\nvoid main() {\n    I64 steps = 0;\n    for (I8 i = 0; i <= 127; i++) {\n        steps++;\n    }\n    \"{steps}\\n\";\n}\n```\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> i8loop.ci:3:31\n   |\n 3 |     for (I8 i = 0; i <= 127; i++) {\n   |                               ^ add.checked.i8\n   |\n   = operation: add.checked.i8\n   = operand-count: 2\n   = operand: I8 127\n   = operand: I8 1\n   = exact:   128\n   = limit:   I8 127\n   ...\n```\n\n`i <= 127` is always true for an `I8`, so this loop can never end on its condition. In cint it faults when `i++` tries to step past 127, after 128 passes."
  },
  {
   "id": "cu-201-08:switch",
   "edition": "CU-201.2",
   "title": "`switch`",
   "clauses": "",
   "url": "/university/201/08-control-flow/#switch",
   "internal": 0,
   "content": "## `switch`\n\nA `switch` tests one integer against cases. Each case holds constants, ranges written with `..=` or a list of both, such as `case 1..=4, 9:`. A case's body ends at the next `case`, so the program's three counters never mix. Where one body should go on into the next, it says so with `fallthrough;`:\n\n```ci\nI64 code = 6;\nswitch (code) {\n    case 0:\n        \"ok\\n\";\n    case 1..=4, 9:\n        \"warning {code}\\n\";\n    case 5..=8:\n        \"error {code}\\n\";\n        fallthrough;\n    case 10:\n        \"logged\\n\";\n    default:\n        \"unknown {code}\\n\";\n}\n```\n\nThis prints `error 6` and then `logged`.\n\nFour `switch` mistakes are errors:\n\n| Written | Error | Why |\n|---|---|---|\n| `case 1:` with no body, followed by `case 2:` | C4023 | This is C's way to share a body. Write `case 1, 2:`. |\n| `case 1..5:` | C4022 | A case range must include its end, so it is written `1..=5`. |\n| a `switch` that leaves out some values | C4020 | Every value must have a case, or the `switch` needs a `default`. |\n| the same value in two cases | C4021 | Only one case may claim a value. This is an error in C too. |\n\n`break;` inside a `switch` leaves the `switch`, as in C."
  },
  {
   "id": "cu-201-08:labels",
   "edition": "CU-201.2",
   "title": "labels",
   "clauses": "",
   "url": "/university/201/08-control-flow/#labels",
   "internal": 0,
   "content": "## labels\n\nTo leave more than one loop at once, label the outer loop and name the label:\n\n```ci\nstarts: for start in 1..1_000 {\n    ...\n            break starts;\n```\n\n`break starts;` leaves the `for` loop and the `while` loop inside it, so the search stops at 703. `continue starts;` would go on to the next start. Without a label, `break` and `continue` apply to the innermost loop. cint has no `goto`."
  },
  {
   "id": "cu-201-08:elsewhere",
   "edition": "CU-201.2",
   "title": "elsewhere",
   "clauses": "",
   "url": "/university/201/08-control-flow/#elsewhere",
   "internal": 0,
   "content": "## elsewhere\n\nThe same `int8_t` loop in C, built with GCC 13.3 and `-O2 -Wall -Wextra` on Ubuntu 24.04 for x86-64, warns that `i <= 127` is always true. Built with `-Wall` alone it gives no warning. Either way the program ran until it was stopped after 10 seconds, because `i++` wraps to -128 and the condition never fails.\n\nIn C, a `case` with no `break` falls into the next one, and missing a `break` is a common mistake. GCC and Clang can warn about it with `-Wimplicit-fallthrough`. In cint, falling through is something you write."
  },
  {
   "id": "cu-201-08:walk-through",
   "edition": "CU-201.2",
   "title": "walk-through",
   "clauses": "",
   "url": "/university/201/08-control-flow/#walk-through",
   "internal": 0,
   "content": "## walk-through\n\n**`I64 next(I64 n)`** returns early with `return n / 2;` for an even number, so the last line handles only odd ones.\n\n**`3 * n + 1`** is checked, as every plain operator is. No start below 1000 climbs anywhere near the limit of `I64`, but a path that did would fault instead of wrapping into a wrong path.\n\n**`{start:>4}`** prints `start` right-aligned in four characters, which lines up the first four rows.\n\n**`I64 taken`** cannot be named `count`, because `count` is a built-in function and a local variable cannot take its name."
  },
  {
   "id": "cu-201-08:try-this",
   "edition": "CU-201.2",
   "title": "try this",
   "clauses": "",
   "url": "/university/201/08-control-flow/#try-this",
   "internal": 0,
   "content": "## try this\n\n1. Change the first loop to start at 1 and multiply by 3 up to 2187. How many steps does 2187 take?\n2. Change the `switch` so that starts taking exactly 111 steps count in a fourth counter. Does it matter where the new case goes? Why?\n3. Change `break starts;` to `break;`. What does the program print now, and why?"
  },
  {
   "id": "cu-201-08:reference",
   "edition": "CU-201.2",
   "title": "reference",
   "clauses": "",
   "url": "/university/201/08-control-flow/#reference",
   "internal": 0,
   "content": "## reference\n\n[if]({{SPEC}}#if), [while]({{SPEC}}#while), [for]({{SPEC}}#for), [switch]({{SPEC}}#switch), [break and continue]({{SPEC}}#break-continue), [checked arithmetic]({{SPEC}}#checked-arithmetic), [print formats]({{SPEC}}#print-formats)\n\nNext: [201-09, functions](09-functions.md)."
  },
  {
   "id": "cu-201-09:cu-201-2",
   "edition": "CU-201.2",
   "title": "CU-201.2",
   "clauses": "",
   "url": "/university/201/09-functions/",
   "internal": 0,
   "content": "# 201-09: functions\n\n<a id=\"201-09\"></a>This is lesson 201-09 of CU-201.2, checked against cint 0.2.0.\n\n*You will pass numbers and arrays to functions, write a recursive function, read the call stack in a fault report and meet the limit on how deep calls can go.*"
  },
  {
   "id": "cu-201-09:the-program",
   "edition": "CU-201.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/201/09-functions/#the-program",
   "internal": 0,
   "content": "## the program\n\nThe harmonic number H(n) is 1 + 1/2 + 1/3 + ... + 1/n. This program adds it up as an exact fraction and keeps the fraction in lowest terms with Euclid's algorithm:\n\n```ci\n// Exact sums of fractions, reduced with Euclid's algorithm.\n\n// Euclid: gcd(a, b) is gcd(b, a % b), and gcd(a, 0) is a.\nI64 gcd(I64 a, I64 b) {\n    if (b == 0) {\n        return a;\n    }\n    return gcd(b, a % b);\n}\n\n// Add 1/k to the fraction f[0]/f[1] and reduce it to lowest terms.\nvoid add_unit(inout I64[2] f, I64 k) {\n    I64 num = f[0] * k + f[1];\n    I64 den = f[1] * k;\n    I64 g = gcd(num, den);\n    f[0] = num / g;\n    f[1] = den / g;\n}\n\nvoid main() {\n    \"gcd(1071, 462) = {gcd(1071, 462)}\\n\";\n    I64[2] h;\n    h[0] = 0;\n    h[1] = 1;\n    for k in 1..=50 {\n        add_unit(h, k);\n        if (k % 10 == 0) {\n            \"H({k}) = {h[0]}/{h[1]}\\n\";\n        }\n    }\n}\n```"
  },
  {
   "id": "cu-201-09:run-it",
   "edition": "CU-201.2",
   "title": "run it",
   "clauses": "",
   "url": "/university/201/09-functions/#run-it",
   "internal": 0,
   "content": "## run it\n\n```text\n$ cint run harmonic.ci\ngcd(1071, 462) = 21\nH(10) = 7381/2520\nH(20) = 55835135/15519504\nH(30) = 9304682830147/2329089562800\nH(40) = 2078178381193813/485721041551200\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> harmonic.ci:13:20\n   |\n13 |     I64 num = f[0] * k + f[1];\n   |                    ^ mul.checked.i64\n   |\n   = operation: mul.checked.i64\n   = operand-count: 2\n   = operand: I64 532145396070491417\n   = operand: I64 44\n   = exact:   23414397427101622348\n   = limit:   I64 9223372036854775807\n   = revision: 32960ad2bbac044b12ed41dcf78b45746985bc46b3eb99160afef5baf46c7225\n   = source-map: none\n   = address: none\n   = stack-depth: 1\n   = called from: harmonic.ci:26:9\n   = fuel-consumed: 920 (not part of the fault record)\n   = state: the program stopped; stdout holds what it wrote before the fault\n```\n\nThe four fractions agree with `fractions.Fraction` in Python 3.13 on Ubuntu 24.04. Then the program stopped while adding 1/44."
  },
  {
   "id": "cu-201-09:reading-the-call-stack",
   "edition": "CU-201.2",
   "title": "reading the call stack",
   "clauses": "",
   "url": "/university/201/09-functions/#reading-the-call-stack",
   "internal": 0,
   "content": "## reading the call stack\n\nThe fault happened inside `add_unit`, at line 13. `stack-depth: 1` says one call was in progress below `main`, and `called from: harmonic.ci:26:9` says where it was made: the line `add_unit(h, k);` in `main`. When calls are nested deeper, the report has one `called from` line for each call, starting from the call made in `main`.\n\nThe operands tell the rest. The first is the numerator of H(43), 532145396070491417, and the second is 44. Their product, 23414397427101622348, is more than twice the largest `I64`, so `f[0] * k` could not be computed."
  },
  {
   "id": "cu-201-09:parameters",
   "edition": "CU-201.2",
   "title": "parameters",
   "clauses": "",
   "url": "/university/201/09-functions/#parameters",
   "internal": 0,
   "content": "## parameters\n\nA number passed to a function is copied. When `gcd` calls itself with `gcd(b, a % b)`, its new `a` and `b` are new copies, and the caller's variables are unchanged.\n\nAn array is passed as a **view** of the caller's array, with a mode that says what the function may do with it:\n\n- `in I64[2] f` lets the function read the array but not write it; a write is error C2060.\n- `inout I64[2] f` lets it read and write the caller's array. `add_unit` writes the new fraction into `h` this way.\n\nA number cannot be passed `inout`: `void exchange(inout I64 a, inout I64 b)` is error C2064. To give back one number, return it. To give back several, pass an array `inout` or return a struct, as lab [401-01](../401/01-ledger.md) does.\n\nA function's name cannot be the name of a built-in function. `swap` is a built-in function, so a function called `swap` is error C3001, like a variable called `sum`."
  },
  {
   "id": "cu-201-09:a-smaller-way-to-add",
   "edition": "CU-201.2",
   "title": "a smaller way to add",
   "clauses": "",
   "url": "/university/201/09-functions/#a-smaller-way-to-add",
   "internal": 0,
   "content": "## a smaller way to add\n\nThe program multiplies both denominators together and only then divides out the common part, so its numbers grow faster than the answer does. Adding over the least common denominator keeps them smaller. Replace `add_unit` with this version:\n\n```ci\n// Add 1/k to the fraction f[0]/f[1], over the least common denominator.\nvoid add_unit(inout I64[2] f, I64 k) {\n    I64 den = f[1] / gcd(f[1], k) * k;\n    I64 num = f[0] * (den / f[1]) + den / k;\n    I64 g = gcd(num, den);\n    f[0] = num / g;\n    f[1] = den / g;\n}\n```\n\nIt gets three numbers further and faults while adding 1/47:\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> harmonic.ci:13:35\n   |\n13 |     I64 den = f[1] / gcd(f[1], k) * k;\n   |                                   ^ mul.checked.i64\n   |\n   = operation: mul.checked.i64\n   = operand-count: 2\n   = operand: I64 1345655451257488800\n   = operand: I64 47\n   = exact:   63245806209101973600\n   = limit:   I64 9223372036854775807\n   ...\n```\n\nThis time the `exact` line is the answer itself. 63245806209101973600 is the denominator of H(47), and it does not fit in an `I64`. No way of arranging the arithmetic can hold H(47) in this type. A wider type can hold it, and [301-04](../301/04-big-exact-numbers.md) carries the sum to H(100) in `I256`."
  },
  {
   "id": "cu-201-09:recursion-and-the-depth-limit",
   "edition": "CU-201.2",
   "title": "recursion and the depth limit",
   "clauses": "",
   "url": "/university/201/09-functions/#recursion-and-the-depth-limit",
   "internal": 0,
   "content": "## recursion and the depth limit\n\n`gcd` calls itself until `b` is 0. Euclid's algorithm takes at most five steps for each decimal digit of the smaller number, so for any two `I64` values it calls itself fewer than 100 times.\n\nEvery program has a limit on how deep calls can go: 256 calls in progress at once, counting `main`. A recursion that goes deeper faults with `E_DEPTH`:\n\n```ci\nI64 sum_to(I64 n) {\n    if (n == 0) {\n        return 0;\n    }\n    return n + sum_to(n - 1);\n}\nvoid main() {\n    \"{sum_to(100)}\\n\";\n    \"{sum_to(100_000)}\\n\";\n}\n```\n\n`sum_to(100)` returns 5050, and `sum_to(100_000)` faults. `sum_to(254)` is the largest call that runs without a fault.\n\n```text\nfault[E_DEPTH]: call depth limit exceeded\n  --> deep.ci:5:16\n   |\n 5 |     return n + sum_to(n - 1);\n   |                ^ call.enter\n   |\n   = operation: call.enter\n   = operand-count: 0\n   = exact:   none\n   = limit:   I64 256\n   ...\n   = stack-depth: 255\n   = called from: deep.ci:9:7\n   = called from: deep.ci:5:16\n   ...\n```\n\n`main` counts as one of the 256, so `stack-depth` stops at 255, and the report lists those 255 calls, with one `called from` line for each. A loop computes the same sum without adding to the call depth. Recursion suits work that shrinks by at least half every step or two, such as Euclid's algorithm or a binary search, because then the depth grows with the number of digits and not with the number itself."
  },
  {
   "id": "cu-201-09:elsewhere",
   "edition": "CU-201.2",
   "title": "elsewhere",
   "clauses": "",
   "url": "/university/201/09-functions/#elsewhere",
   "internal": 0,
   "content": "## elsewhere\n\nThe first version of the program in C, with `int64_t`, built with GCC 13.3 and `-O2 -Wall -Wextra` on Ubuntu 24.04 for x86-64, gave no warning and exited with status 0. Its last line was `H(50) = -396549522021549939/211166340108011552`: a negative sum of positive fractions. Signed overflow in C is undefined behavior, so the C standard places no requirement on what the program does next.\n\n`fractions.Fraction` in Python 3.13 on Ubuntu 24.04 has integers of any size, so it computes H(50) exactly. Python limits recursion instead: `sum_to(100_000)` written in Python stopped with `RecursionError: maximum recursion depth exceeded`. C has no depth limit of its own. A recursion deep enough to use up the stack can crash the program, unless the compiler turns the recursion into a loop. With GCC 13.3 or Clang 18.1 on the same machine, `sum_to(100000000)` in C crashed with a segmentation fault at `-O0` and printed 5000000050000000 at `-O2`."
  },
  {
   "id": "cu-201-09:walk-through",
   "edition": "CU-201.2",
   "title": "walk-through",
   "clauses": "",
   "url": "/university/201/09-functions/#walk-through",
   "internal": 0,
   "content": "## walk-through\n\n**`if (b == 0) { return a; }`** is the case that stops the recursion. Every recursive function needs one, and every chain of calls must reach it.\n\n**`I64[2] h;`** declares an array of two numbers, both 0. `h[0] = 0;` changes nothing and is there so the starting fraction reads plainly, and `h[1] = 1;` makes it 0/1.\n\n**`f[1] / gcd(f[1], k) * k`** divides before it multiplies. Written as `f[1] * k / gcd(f[1], k)`, the product would overflow sooner.\n\n**`num` and `den`** are local to each call of `add_unit`, so each call starts with its own `num` and `den`."
  },
  {
   "id": "cu-201-09:try-this",
   "edition": "CU-201.2",
   "title": "try this",
   "clauses": "",
   "url": "/university/201/09-functions/#try-this",
   "internal": 0,
   "content": "## try this\n\n1. Print every H(k) instead of every tenth one. What is the last harmonic number each version of `add_unit` prints?\n2. Write `lcm(a, b)` as a function that calls `gcd`, and use it in `add_unit`.\n3. Rewrite `sum_to` with a loop and check that it gives 5050 for 100 and 5000050000 for 100,000."
  },
  {
   "id": "cu-201-09:reference",
   "edition": "CU-201.2",
   "title": "reference",
   "clauses": "",
   "url": "/university/201/09-functions/#reference",
   "internal": 0,
   "content": "## reference\n\n[functions]({{SPEC}}#functions), [parameters and views]({{SPEC}}#views), [recursion and depth]({{SPEC}}#call-depth), [fault record]({{SPEC}}#fault-record), [checked arithmetic]({{SPEC}}#checked-arithmetic)\n\nNext: lab [401-02, hunting an overflow](../401/02-hunting-an-overflow.md)."
  },
  {
   "id": "cu-201-overview:cu-201-2",
   "edition": "CU-201.2",
   "title": "CU-201.2",
   "clauses": "",
   "url": "/university/201/",
   "internal": 0,
   "content": "# 201: cint for programmers\n\nThis page is CU-201.2, edition 2 of 201: cint for programmers, checked against cint 0.2.0 and released on {{RELEASE_DATE}}.\n\nThis edition is current. Every program in it was run on cint 0.2.0 with each of GCC, Clang, MSVC and Apple Clang, and every output comes from those runs. Each \"elsewhere\" result names the language version that printed it. The text of this edition does not change after its release. Corrections that change nothing a reader would see are listed in [ERRATA.md](../ERRATA.md). A new edition is published when a release changes what a lesson shows or when lessons are added. Lesson identifiers are the same in every edition and are never reused.\n\n201 is for people who program in C, Python or a language like them. Readers who know C or Python may want to read [cint for C programmers](../from-c.md) or [cint for Python and NumPy programmers](../from-python.md) first. 201 skips what a variable is and starts from what cint does differently. Each lesson ends with links to the parts of the [specification]({{SPEC}}) it uses."
  },
  {
   "id": "cu-201-overview:lessons",
   "edition": "CU-201.2",
   "title": "lessons",
   "clauses": "",
   "url": "/university/201/#lessons",
   "internal": 0,
   "content": "## lessons\n\n| Lesson | Title | You build |\n|---|---|---|\n| [201-00](00-start-here.md) | start here | one program, run with the four commands |\n| [201-01](01-numbers-that-hold.md) | numbers that hold | the rice on a chessboard |\n| [201-02](02-types-and-conversions.md) | types and conversions | an altitude in a 16-bit field |\n| [201-03](03-operators-at-the-edge.md) | operators at the edge | a 32-bit hash and a pixel brightener |\n| [201-04](04-division-and-rounding.md) | division and rounding | a bill split exactly |\n| [201-05](05-tests-and-goldens.md) | tests and goldens | tests and a saved output for the bill split |\n| [201-06](06-workbench.md) | the workbench | a year of savings, rewound and searched |\n| [201-07](07-debugging-by-comparison.md) | debugging by comparison | a checksum bug found one change at a time |\n| [201-08](08-control-flow.md) | control flow | Collatz paths sorted by length |\n| [201-09](09-functions.md) | functions | exact harmonic sums |"
  },
  {
   "id": "cu-201-overview:changes-since-the-previous-edition",
   "edition": "CU-201.2",
   "title": "changes since the previous edition",
   "clauses": "",
   "url": "/university/201/#changes-since-the-previous-edition",
   "internal": 0,
   "content": "## changes since the previous edition\n\nCU-201.2 replaces CU-201.1, which stays readable.\n\n- Lessons 201-05 to 201-09 are new. Lessons 201-05 to 201-07 teach testing and debugging: tests and goldens, the workbench and debugging by comparison.\n- Every lesson's first line names CU-201.2.\n- 201-00: the interpreter paragraph links to 201-06.\n- 201-01: the comparison of runs links to 201-07.\n- 201-04: the page ends with a link to 201-05.\n\nNo program's output changed."
  },
  {
   "id": "cu-301-01:cu-301-1",
   "edition": "CU-301.1",
   "title": "CU-301.1",
   "clauses": "",
   "url": "/university/301/01-when-64-bits-are-not-enough/",
   "internal": 0,
   "content": "# 301-01: when 64 bits are not enough\n\n<a id=\"301-01\"></a>This is lesson 301-01 of CU-301.1, checked against cint 0.2.0.\n\n*You will watch a product of two 64-bit numbers outgrow `I64`, compute it exactly in `I128` with `mul_full` and meet the integer types that go up to 1024 bits.*"
  },
  {
   "id": "cu-301-01:the-program",
   "edition": "CU-301.1",
   "title": "the program",
   "clauses": "",
   "url": "/university/301/01-when-64-bits-are-not-enough/#the-program",
   "internal": 0,
   "content": "## the program\n\nFermat's test checks whether a number m could be prime. If m is an odd prime, then 2 to the power m - 1, divided by m, leaves a remainder of 1. A remainder other than 1 proves that m is not prime: it is composite, a product of smaller numbers. The power is far too large to compute, so the program keeps only the remainder after each multiplication:\n\n```ci\n// Fermat's test: if m is prime, then 2 to the power m - 1,\n// divided by m, leaves 1. A remainder other than 1 proves m composite.\n\n// a * b % m, for a and b below m.\nI64 mul_mod(I64 a, I64 b, I64 m) {\n    return a * b % m;\n}\n\n// base to the power exp, modulo m, by repeated squaring.\nI64 pow_mod(I64 base, I64 exp, I64 m) {\n    I64 result = 1;\n    I64 b = base % m;\n    I64 e = exp;\n    while (e > 0) {\n        if (e % 2 == 1) {\n            result = mul_mod(result, b, m);\n        }\n        b = mul_mod(b, b, m);\n        e /= 2;\n    }\n    return result;\n}\n\nvoid main() {\n    I64[3] tests = [1_000_000_007, 2_305_843_009_213_693_951, 2_305_843_009_213_693_953];\n    for i in 0..3 {\n        I64 m = tests[i];\n        \"{m:>19}: remainder {pow_mod(2, m - 1, m)}\\n\";\n    }\n}\n```\n\nThe first number, 1000000007, is a prime often used in programming contests. The second is 2<sup>61</sup> - 1, which is also prime. The third is 2<sup>61</sup> + 1, which 3 divides."
  },
  {
   "id": "cu-301-01:run-it",
   "edition": "CU-301.1",
   "title": "run it",
   "clauses": "",
   "url": "/university/301/01-when-64-bits-are-not-enough/#run-it",
   "internal": 0,
   "content": "## run it\n\n```text\n$ cint run fermat.ci\n         1000000007: remainder 1\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> fermat.ci:6:14\n   |\n 6 |     return a * b % m;\n   |              ^ mul.checked.i64\n   |\n   = operation: mul.checked.i64\n   = operand-count: 2\n   = operand: I64 4294967296\n   = operand: I64 4294967296\n   = exact:   18446744073709551616\n   = limit:   I64 9223372036854775807\n   = revision: c9b0d558c225959442c702c2a4e5015ffb1547a735342e30e49711666e8e56f3\n   = source-map: none\n   = address: none\n   = stack-depth: 2\n   = called from: fermat.ci:28:30\n   = called from: fermat.ci:18:13\n   = fuel-consumed: 97 (not part of the fault record)\n   = state: the program stopped; stdout holds what it wrote before the fault\n```\n\nThe first test passes. For 1000000007, every product of two numbers below it is about 10<sup>18</sup> at most, far below `I64.max`. The second test squares `b` again and again: 2, 4, 16, 256, 65536, 4294967296. The next square is 2<sup>64</sup>, and the fault record shows it as the exact result. A number below 2<sup>61</sup> times another can need up to 122 bits, and `I64` has 63 bits for the value and one for the sign."
  },
  {
   "id": "cu-301-01:the-fix-an-exact-128-bit-product",
   "edition": "CU-301.1",
   "title": "the fix: an exact 128-bit product",
   "clauses": "",
   "url": "/university/301/01-when-64-bits-are-not-enough/#the-fix-an-exact-128-bit-product",
   "internal": 0,
   "content": "## the fix: an exact 128-bit product\n\n`mul_full` multiplies two `I64` values and returns the exact product as an `I128`, which can never overflow. The remainder is then small enough to convert back:\n\n```ci\n// a * b % m, for a and b below m, through the exact 128-bit product.\nI64 mul_mod(I64 a, I64 b, I64 m) {\n    I128 product = mul_full(a, b);\n    return (product % (m as I128)) as I64;\n}\n```\n\nNothing else in the program changes:\n\n```text\n$ cint run fermat.ci\n         1000000007: remainder 1\n2305843009213693951: remainder 1\n2305843009213693953: remainder 4\n```\n\nBoth primes leave 1. The remainder 4 proves that 2305843009213693953 is not prime, as expected, since 3 divides it. A remainder of 1 does not by itself prove a number prime, because some composite numbers also leave 1. The smallest is 341, which is 11 times 31. Programs that need certainty use a stronger test, such as Miller-Rabin with a fixed set of bases, and it needs this same exact product."
  },
  {
   "id": "cu-301-01:the-wide-integer-types",
   "edition": "CU-301.1",
   "title": "the wide integer types",
   "clauses": "",
   "url": "/university/301/01-when-64-bits-are-not-enough/#the-wide-integer-types",
   "internal": 0,
   "content": "## the wide integer types\n\ncint 0.2.0 has signed integers in eight sizes, from `I8` up. This table shows `I64` and the wider ones. Each wider type holds every value of the narrower ones:\n\n| Type | Largest value | Digits in the largest value |\n|---|---|---|\n| `I64` | 9223372036854775807 | 19 |\n| `I128` | 170141183460469231731687303715884105727 | 39 |\n| `I256` | 5789604461865809771... | 77 |\n| `I512` | 6703903964971298549... | 154 |\n| `I1024` | 8988465674311579538... | 308 |\n\nEach `T.max` above was printed by cint. `I128` to `I1024` are called the wide types. They take the same operators as `I64`, and every plain operator on them is checked the same way.\n\ncint 0.2.0 also has the unsigned wide types `U128`, `U256` and `U512`. `mul_full` of two `U64` values gives a `U128`:\n\n```ci\nvoid main() {\n    U64 a = U64.max;\n    U128 square = mul_full(a, a);\n    \"{a} squared is {square}\\n\";\n    \"U128 runs up to {U128.max}\\n\";\n}\n```\n\n```text\n18446744073709551615 squared is 340282366920938463426481119284349108225\nU128 runs up to 340282366920938463463374607431768211455\n```"
  },
  {
   "id": "cu-301-01:widths-never-mix-silently",
   "edition": "CU-301.1",
   "title": "widths never mix silently",
   "clauses": "",
   "url": "/university/301/01-when-64-bits-are-not-enough/#widths-never-mix-silently",
   "internal": 0,
   "content": "## widths never mix silently\n\nAn `I64` value does not become an `I128` on its own. Each of these lines is refused with error C2001, type mismatch:\n\n```ci\nI128 product = a * a;      // a * a is an I64 product, and it may already have overflowed\n\"{product % m}\\n\";         // product is I128 and m is I64\n```\n\nConvert a value with `as` to widen it. `(a as I128) * (a as I128)` computes the same exact product as `mul_full(a, a)`. Widening never fails, since every `I64` value is an `I128` value.\n\nNarrowing can fail, and `as` checks it. Converting an `I128` that holds 2<sup>63</sup> to `I64` faults:\n\n```text\nfault[E_NARROW]: the value does not fit the destination type\n  --> narrow.ci:5:11\n   |\n 5 |     \"{big as I64}\\n\";\n   |           ^ as.checked.i128.i64\n   |\n   = operation: as.checked.i128.i64\n   = operand-count: 1\n   = operand: I128 9223372036854775808\n   = exact:   9223372036854775808\n   = limit:   I64 9223372036854775807\n   ...\n```\n\nIn `mul_mod`, `(product % (m as I128)) as I64` cannot fault, because a remainder after dividing by m is always less than m, and m is an `I64`."
  },
  {
   "id": "cu-301-01:a-wider-type-moves-the-edge",
   "edition": "CU-301.1",
   "title": "a wider type moves the edge",
   "clauses": "",
   "url": "/university/301/01-when-64-bits-are-not-enough/#a-wider-type-moves-the-edge",
   "internal": 0,
   "content": "## a wider type moves the edge\n\n`I128` has an edge of its own. Doubling 1 in an `I128` faults at the 127th doubling:\n\n```text\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> over128.ci:4:16\n   |\n 4 |         grains *= 2;\n   |                ^ mul.checked.i128\n   |\n   = operation: mul.checked.i128\n   = operand-count: 2\n   = operand: I128 85070591730234615865843651857942052864\n   = operand: I128 2\n   = exact:   170141183460469231731687303715884105728\n   = limit:   I128 170141183460469231731687303715884105727\n   ...\n```\n\nPick the narrowest type that holds every value the program can reach, as `mul_mod` does: its inputs stay in `I64`, and only the product needs `I128`. A wide value takes more memory and each operation on it does more work."
  },
  {
   "id": "cu-301-01:refused-on-wide-types-in-0-2-0",
   "edition": "CU-301.1",
   "title": "refused on wide types in 0.2.0",
   "clauses": "",
   "url": "/university/301/01-when-64-bits-are-not-enough/#refused-on-wide-types-in-0-2-0",
   "internal": 0,
   "content": "## refused on wide types in 0.2.0\n\nA few forms that work on `I64` are refused on the wide types in cint 0.2.0, with error C9102, not yet supported:\n\n- A `switch` cannot test a wide value.\n- `as?`, the conversion that returns an error instead of faulting, cannot convert from a wide type.\n- The built-ins that return an error instead of faulting, such as `add_result`, do not take wide values.\n- `muldiv` cannot give a wide result from narrow operands.\n\nIn place of a `switch`, compare with `if` and `else if`. In place of the others, convert a value that is known to fit to `I64` first, or widen the operands with `as`."
  },
  {
   "id": "cu-301-01:elsewhere",
   "edition": "CU-301.1",
   "title": "elsewhere",
   "clauses": "",
   "url": "/university/301/01-when-64-bits-are-not-enough/#elsewhere",
   "internal": 0,
   "content": "## elsewhere\n\nThe same test was written in C with `uint64_t` and `a * b % m`. It was built with GCC 13.3 and with Clang 18.1, using `-O2 -Wall -Wextra` on Ubuntu 24.04 for x86-64. Neither gave a warning, and both builds printed:\n\n```text\n         1000000007: remainder 1\n2305843009213693951: remainder 0\n2305843009213693953: remainder 0\n```\n\nUnsigned arithmetic in C wraps without an error, so the products lost their high bits. A remainder of 0 would mean m divides a power of 2, which no odd number above 1 does. The program called a prime composite, and nothing signaled it. Computing the product as `unsigned __int128`, an extension that GCC and Clang provide on 64-bit targets, printed 1, 1 and 4, as cint does.\n\n`__int128` is signed and unchecked. A C program that doubled an `__int128` 128 times, built with the same compilers, printed that the result was zero at `-O0` and positive at `-O2`, with no warning at either. Signed overflow in C is undefined behavior, so the C standard places no requirement on what the program does. C23 adds `_BitInt(N)` for integers of a chosen width. Clang 18.1 built a `_BitInt(256)` program, and GCC 13.3 did not recognize `_BitInt`. GCC's release notes list it as new in GCC 14.\n\nPython's `int` has no fixed size. `pow(2, m - 1, m)` in Python 3.13 on the same machine printed 1, 1 and 4."
  },
  {
   "id": "cu-301-01:walk-through",
   "edition": "CU-301.1",
   "title": "walk-through",
   "clauses": "",
   "url": "/university/301/01-when-64-bits-are-not-enough/#walk-through",
   "internal": 0,
   "content": "## walk-through\n\n**`mul_full(a, b)`** takes two values of the same type and returns their exact product in the type twice as wide: `I64` to `I128`, `I128` to `I256`, `I256` to `I512` and `I512` to `I1024`.\n\n**`m as I128`** widens `m` so that `%` has two operands of one type.\n\n**`e % 2 == 1`** tests the lowest bit of the exponent. Repeated squaring multiplies `result` by `b` for each 1 bit, so about 120 multiplications cover an exponent near 2<sup>61</sup>.\n\n**`I64[3] tests`** is declared inside `main`, since an array cannot be declared at the top level of a program in cint 0.2.0."
  },
  {
   "id": "cu-301-01:try-this",
   "edition": "CU-301.1",
   "title": "try this",
   "clauses": "",
   "url": "/university/301/01-when-64-bits-are-not-enough/#try-this",
   "internal": 0,
   "content": "## try this\n\n1. Add 9223372036854775783, the largest prime below 2<sup>63</sup>, to `tests` in the version with `mul_full`. The array and the loop then need a length of 4. Does the product still fit, and what does the new line print?\n2. Replace `mul_full(a, b)` with `(a as I128) * (b as I128)`. Does any output change?\n3. The first version is safe for every m up to some size. What is the largest such m, and why?\n\n<details>\n<summary>answer to 3</summary>\n\nEvery product in the program multiplies two numbers below m, so the largest is (m - 1)<sup>2</sup>. It fits in an `I64` while m - 1 is at most 3037000499, the integer square root of `I64.max`. So the first version is safe for every m up to 3037000500.\n</details>"
  },
  {
   "id": "cu-301-01:reference",
   "edition": "CU-301.1",
   "title": "reference",
   "clauses": "",
   "url": "/university/301/01-when-64-bits-are-not-enough/#reference",
   "internal": 0,
   "content": "## reference\n\n[integer types]({{SPEC}}#integer-types), [wide integers]({{SPEC}}#wide-integers), [mul_full]({{SPEC}}#mul-full), [conversions]({{SPEC}}#conversions), [checked arithmetic]({{SPEC}}#checked-arithmetic)\n\nNext: [301-04, big exact numbers](04-big-exact-numbers.md)."
  },
  {
   "id": "cu-301-04:cu-301-1",
   "edition": "CU-301.1",
   "title": "CU-301.1",
   "clauses": "",
   "url": "/university/301/04-big-exact-numbers/",
   "internal": 0,
   "content": "# 301-04: big exact numbers\n\n<a id=\"301-04\"></a>This is lesson 301-04 of CU-301.1, checked against cint 0.2.0.\n\n*You will compute 100 factorial and a binomial coefficient to the last digit in `I1024`, see why each conversion is written where the value is used and find the first factorial that does not fit.*"
  },
  {
   "id": "cu-301-04:the-program",
   "edition": "CU-301.1",
   "title": "the program",
   "clauses": "",
   "url": "/university/301/04-big-exact-numbers/#the-program",
   "internal": 0,
   "content": "## the program\n\nThe factorial of n, written `n!`, multiplies every whole number from 1 to n. The binomial coefficient \"n choose k\" counts the ways to pick k things from n: there are 2598960 different five-card hands in a deck of 52. Both grow far past `I64`:\n\n```ci\n// Big exact numbers: factorials, binomial coefficients and a digit count.\n\n// n factorial, exact in I1024.\nI1024 factorial(I64 n) {\n    I1024 f = 1;\n    for k in 1..=n {\n        f *= k as I1024;\n    }\n    return f;\n}\n\n// n choose k: the number of ways to pick k things from n.\nI1024 choose(I64 n, I64 k) {\n    I1024 c = 1;\n    for i in 1..=k {\n        c = c * ((n - k + i) as I1024) / (i as I1024);\n    }\n    return c;\n}\n\n// The number of decimal digits in x, for x above 0.\nI64 digits(I1024 x) {\n    I1024 rest = x;\n    I64 n = 0;\n    while (rest > 0) {\n        rest /= 10;\n        n += 1;\n    }\n    return n;\n}\n\nvoid main() {\n    I1024 f = factorial(100);\n    \"100! = {f}\\n\";\n    \"100! has {digits(f)} digits\\n\";\n    \"52 choose 5 = {choose(52, 5)}\\n\";\n    \"100 choose 50 = {choose(100, 50)}\\n\";\n    \"170! has {digits(factorial(170))} digits\\n\";\n    \"171! has {digits(factorial(171))} digits\\n\";\n}\n```"
  },
  {
   "id": "cu-301-04:run-it",
   "edition": "CU-301.1",
   "title": "run it",
   "clauses": "",
   "url": "/university/301/04-big-exact-numbers/#run-it",
   "internal": 0,
   "content": "## run it\n\n```text\n$ cint run bignum.ci\n100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000\n100! has 158 digits\n52 choose 5 = 2598960\n100 choose 50 = 100891344545564193334812497256\n170! has 307 digits\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> bignum.ci:7:11\n   |\n 7 |         f *= k as I1024;\n   |           ^ mul.checked.i1024\n   |\n   = operation: mul.checked.i1024\n   = operand-count: 2\n   ...\n   = operand: I1024 171\n   ...\n   = stack-depth: 1\n   = called from: bignum.ci:39:23\n   = fuel-consumed: 969 (not part of the fault record)\n   = state: the program stopped; stdout holds what it wrote before the fault\n```\n\nThe first `...` stands for three lines that hold numbers of more than 300 digits: `170!`, the exact `171!` and `I1024.max`. The second stands for the revision, source-map and address lines. Each value printed above agrees with `math.factorial` and `math.comb` in Python 3.13 on Ubuntu 24.04, digit for digit."
  },
  {
   "id": "cu-301-04:what-happened",
   "edition": "CU-301.1",
   "title": "what happened",
   "clauses": "",
   "url": "/university/301/04-big-exact-numbers/#what-happened",
   "internal": 0,
   "content": "## what happened\n\n**`I1024` holds numbers up to about 8.99 times 10<sup>307</sup>.** `100!` has 158 digits, so it fits. `170!` has 307 digits and still fits. `171!` is 171 times larger, with 310 digits, and the multiplication that makes it faults. The record names the operands, `170!` and 171, both as `I1024` values, and gives the exact product in full.\n\n**The conversion is written at the multiplication.** `f` is an `I1024` and `k` is an `I64`, and cint never mixes two widths on its own. Leave out the conversion and the program is refused before it runs:\n\n```text\nerror[C2001]: type mismatch\n  --> noas.ci:4:14\n   |\n 4 |         f *= k;\n   |              ^\n   |\n```\n\n`k as I1024` widens `k` at the one place it meets `f`. The conversion is visible on the line where the two widths meet, so a reader does not have to look elsewhere to find it.\n\n**`choose` divides exactly at every step.** After step i, `c` holds (n - k + i) choose i, which is a whole number. So the multiplication comes first, and the division that follows leaves no remainder. Dividing first, as in `c * ((n - k + i) / i)`, would round away part of the answer at most steps.\n\n**`digits` works on a local variable.** A parameter cannot be assigned in cint, so `x /= 10` inside `digits` is error C2060. The function puts `x` into the local `rest` and divides that."
  },
  {
   "id": "cu-301-04:carrying-the-harmonic-sum-further",
   "edition": "CU-301.1",
   "title": "carrying the harmonic sum further",
   "clauses": "",
   "url": "/university/301/04-big-exact-numbers/#carrying-the-harmonic-sum-further",
   "internal": 0,
   "content": "## carrying the harmonic sum further\n\nLesson [201-09](../201/09-functions.md) added 1 + 1/2 + 1/3 and so on as an exact fraction in `I64`. Its second version, which adds over the least common denominator, stopped at 1/47, because the denominator of H(47) is 63245806209101973600, too large for `I64`. The second version goes on to 100 with `I256` in place of `I64` in `gcd`, `add_unit` and `h`, and with `k as I256` at the call:\n\n```text\n$ cint run harmonic256.ci\nH(47) = 280682601097106968469/63245806209101973600\nH(100) = 14466636279520351160221518043104131447711/2788815009188499086581352357412492142272\n```\n\nThe denominator of H(100) has 40 digits. Run on, the same program prints H(170) and faults while adding 1/179, when a denominator times 179 passes `I256.max`."
  },
  {
   "id": "cu-301-04:elsewhere",
   "edition": "CU-301.1",
   "title": "elsewhere",
   "clauses": "",
   "url": "/university/301/04-big-exact-numbers/#elsewhere",
   "internal": 0,
   "content": "## elsewhere\n\nThe same factorial loop in C with `double`, built with GCC 13.3 and `-O2 -Wall -Wextra` on Ubuntu 24.04 for x86-64, printed `100!` as a number of 158 digits whose first 15 digits are right. The exact `100!` ends in 24 zeros, and the `double` version ends in 813248. `171!` printed as `inf`. The same `double` loop for 100 choose 50 printed 100891344545564219663900999680, right in its first 15 digits and wrong after them. A `double` holds 53 binary digits, which is about 16 decimal digits, so most larger whole numbers in it are rounded.\n\nPython's `int` grows to any size, so `math.factorial(171)` and much larger values are exact. It has no fault for a value outside a chosen type, because it has no fixed types. In cint the program states a fixed width, and every plain operator is checked against it."
  },
  {
   "id": "cu-301-04:walk-through",
   "edition": "CU-301.1",
   "title": "walk-through",
   "clauses": "",
   "url": "/university/301/04-big-exact-numbers/#walk-through",
   "internal": 0,
   "content": "## walk-through\n\n**`I1024 factorial(I64 n)`** takes a small count and returns a large value. A function's parameter and return types need not match.\n\n**`f *= k as I1024`** is the same as `f = f * (k as I1024)`. The conversion applies to `k` alone, and the result is then multiplied into `f`, so no parentheses are needed.\n\n**`while (rest > 0)`** compares an `I1024` with the literal 0. The literal takes the type of `rest`, so no conversion is written.\n\n**`{f}`** prints all 158 digits. Printing works the same for every integer type."
  },
  {
   "id": "cu-301-04:try-this",
   "edition": "CU-301.1",
   "title": "try this",
   "clauses": "",
   "url": "/university/301/04-big-exact-numbers/#try-this",
   "internal": 0,
   "content": "## try this\n\n1. Print 100 choose k for k from 0 to 100. Which k gives the largest value?\n2. Add the digits of `100!` together. A parameter cannot be assigned, so work on a copy, as `digits` does. What is the sum?\n3. Write a loop that multiplies an `I512` by 1, 2, 3 and so on, printing each number after it multiplies, until it faults. Which is the largest factorial an `I512` holds?\n\n<details>\n<summary>answer to 2</summary>\n\nThe digits of `100!` add up to 648. This is one way, for x above 0:\n\n```ci\nI64 digit_total(I1024 x) {\n    I1024 rest = x;\n    I64 total = 0;\n    while (rest > 0) {\n        total += (rest % 10) as I64;\n        rest /= 10;\n    }\n    return total;\n}\n```\n\n`rest % 10` is an `I1024` between 0 and 9, so converting it to `I64` cannot fault. A local called `sum` would be refused, because `sum` is the name of a built-in function.\n</details>"
  },
  {
   "id": "cu-301-04:reference",
   "edition": "CU-301.1",
   "title": "reference",
   "clauses": "",
   "url": "/university/301/04-big-exact-numbers/#reference",
   "internal": 0,
   "content": "## reference\n\n[wide integers]({{SPEC}}#wide-integers), [conversions]({{SPEC}}#conversions), [checked arithmetic]({{SPEC}}#checked-arithmetic), [division]({{SPEC}}#division), [print formats]({{SPEC}}#print-formats)\n\nBack to [301: wider numbers](README.md)."
  },
  {
   "id": "cu-301-overview:cu-301-1",
   "edition": "CU-301.1",
   "title": "CU-301.1",
   "clauses": "",
   "url": "/university/301/",
   "internal": 0,
   "content": "# 301: wider numbers\n\nThis page is CU-301.1, edition 1 of 301: wider numbers, checked against cint 0.2.0 and released on {{RELEASE_DATE}}.\n\nThis edition is current. Every program in it was run on cint 0.2.0 with each of GCC, Clang, MSVC and Apple Clang, and every output comes from those runs. Each \"elsewhere\" result names the language version that printed it. The text of this edition does not change after its release. Corrections that change nothing a reader would see are listed in [ERRATA.md](../ERRATA.md). A new edition is published when a release changes what a lesson shows or when lessons are added. Lesson identifiers are the same in every edition and are never reused.\n\n301 is for readers who have finished [201](../201/README.md) up to 201-09. It takes cint past 64 bits, to integers of 128 to 1024 bits and the exact products that need them. Each lesson ends with links to the parts of the [specification]({{SPEC}}) it uses."
  },
  {
   "id": "cu-301-overview:lessons",
   "edition": "CU-301.1",
   "title": "lessons",
   "clauses": "",
   "url": "/university/301/#lessons",
   "internal": 0,
   "content": "## lessons\n\n| Lesson | Title | You build |\n|---|---|---|\n| [301-01](01-when-64-bits-are-not-enough.md) | when 64 bits are not enough | a primality test whose products need 128 bits |\n| [301-04](04-big-exact-numbers.md) | big exact numbers | 100 factorial and binomial coefficients, to the last digit |\n\nThe identifiers 301-02, 301-03 and 301-05 are reserved."
  },
  {
   "id": "cu-301-overview:changes-since-the-previous-edition",
   "edition": "CU-301.1",
   "title": "changes since the previous edition",
   "clauses": "",
   "url": "/university/301/#changes-since-the-previous-edition",
   "internal": 0,
   "content": "## changes since the previous edition\n\nThis is the first edition."
  },
  {
   "id": "cu-401-01:cu-401-2",
   "edition": "CU-401.2",
   "title": "CU-401.2",
   "clauses": "",
   "url": "/university/401/01-ledger/",
   "internal": 0,
   "content": "# 401-01: an exact ledger\n\n<a id=\"401-01\"></a>This is lab 401-01 of CU-401.2, checked against cint 0.2.0.\n\n*You will keep a bank ledger in whole cents, pay a day of interest rounded by a stated rule, refuse an overdraft as an error and stop on an overflow. Then you will save a checked copy of the ledger's output, called a golden. The golden catches a mistake the tests miss, and the tests catch a mistake the golden misses.*\n\nTake it after [201-04](../201/04-division-and-rounding.md). The walk-through explains the parts of the language the program uses that 201-00 to 201-04 do not cover."
  },
  {
   "id": "cu-401-01:the-program",
   "edition": "CU-401.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/401/01-ledger/#the-program",
   "internal": 0,
   "content": "## the program\n\n```ci\n// ledger.ci: an exact bank ledger. Money is whole cents in I64.\n\nerror LedgerError { overdrawn, unknown_kind }\n\n// The kinds of entry, as typed constants.\nconst U8 DEPOSIT = 0;\nconst U8 WITHDRAW = 1;\nconst U8 INTEREST = 2;\n\nstruct Entry {\n    U8 kind;\n    I64 cents;                  // the amount; for interest, the yearly rate in basis points\n}\n\n// One day of interest at a yearly rate in basis points, rounded half to even, to the cent.\nI64 daily_interest(I64 balance, I64 basis_points) {\n    return muldiv(I64, balance, basis_points, 10_000 * 365, half_even);\n}\n\n// Apply one entry. Overdrawing is an expected error; overflow is a fault.\nLedgerError!I64 apply(I64 balance, Entry e) {\n    switch (e.kind) {\n        case DEPOSIT:\n            return balance + e.cents;\n        case WITHDRAW:\n            if (e.cents > balance) {\n                return LedgerError.overdrawn;\n            }\n            return balance - e.cents;\n        case INTEREST:\n            return balance + daily_interest(balance, e.cents);\n        default:\n            return LedgerError.unknown_kind;\n    }\n}\n\nvoid print_kind(U8 kind) {\n    switch (kind) {\n        case DEPOSIT: \"deposit \";\n        case WITHDRAW: \"withdraw\";\n        case INTEREST: \"interest\";\n        default: \"unknown \";\n    }\n}"
  },
  {
   "id": "cu-401-01:the-program-p1",
   "edition": "CU-401.2",
   "title": "the program (part 2)",
   "clauses": "",
   "url": "/university/401/01-ledger/#the-program",
   "internal": 0,
   "content": "void main() {\n    Entry[5] book;\n    book[0] = Entry(DEPOSIT, 125_000);\n    book[1] = Entry(WITHDRAW, 40_050);\n    book[2] = Entry(INTEREST, 450);     // 4.50 percent a year, for one day\n    book[3] = Entry(WITHDRAW, 200_000); // more than the balance: rejected\n    book[4] = Entry(DEPOSIT, 99);\n    I64 balance = 0;\n    for i in 0..5 {\n        Entry e = book[i];\n        I64 next = apply(balance, e) catch (err) {\n            switch (err) {\n                case .overdrawn: \"{i}: rejected, overdrawn\\n\";\n                case .unknown_kind: \"{i}: rejected, unknown kind\\n\";\n            }\n            continue;\n        };\n        balance = next;\n        \"{i}: \";\n        print_kind(e.kind);\n        \" {e.cents:>8} -> {balance:/100}\\n\";\n    }\n    \"final balance: {balance:/100}\\n\";\n}\n\ntest \"interest ties round to even\" {\n    assert(daily_interest(1_825_000, 1) == 0);  // exactly half a cent: rounds to 0\n    assert(daily_interest(5_475_000, 1) == 2);  // exactly 1.5 cents: rounds to 2\n}\n\ntest \"an overdraft is an error\" {\n    I64 after = apply(100, Entry(WITHDRAW, 101)) catch -1;\n    assert(after == -1);\n}\n\ntest \"an overflow is a fault\" expect_fault E_OVERFLOW {\n    _ = apply(I64.max, Entry(DEPOSIT, 1));\n}\n```"
  },
  {
   "id": "cu-401-01:run-it",
   "edition": "CU-401.2",
   "title": "run it",
   "clauses": "",
   "url": "/university/401/01-ledger/#run-it",
   "internal": 0,
   "content": "## run it\n\n```text\n$ cint run ledger.ci\n0: deposit    125000 -> 1250.00\n1: withdraw    40050 -> 849.50\n2: interest      450 -> 849.60\n3: rejected, overdrawn\n4: deposit        99 -> 850.59\nfinal balance: 850.59\n```\n\nOne day of interest on 849.50 (84950 cents) at 4.50 percent a year is 84950 \u00d7 450 / 3650000 cents, about 10.47 cents. `half_even` rounds it to 10, and the balance becomes 849.60. Entry 3 asks for 2000.00 from a balance of 849.60, so `apply` returns the error `overdrawn`. The loop prints a line and moves on, and the balance does not change."
  },
  {
   "id": "cu-401-01:test-it",
   "edition": "CU-401.2",
   "title": "test it",
   "clauses": "",
   "url": "/university/401/01-ledger/#test-it",
   "internal": 0,
   "content": "## test it\n\n```text\n$ cint test ledger.ci\ntest ledger.ci:71 \"interest ties round to even\" ... ok\ntest ledger.ci:76 \"an overdraft is an error\" ... ok\ntest ledger.ci:81 \"an overflow is a fault\" ... ok\n3 of 3 tests passed\n```\n\nThe first test checks two ties, where a rounding rule matters: an exact half cent rounds to the even neighbor, 0, and an exact cent and a half rounds to 2. The third test passes because the deposit faults: `expect_fault E_OVERFLOW` says a fault with that code is the expected result."
  },
  {
   "id": "cu-401-01:errors-and-faults",
   "edition": "CU-401.2",
   "title": "errors and faults",
   "clauses": "",
   "url": "/university/401/01-ledger/#errors-and-faults",
   "internal": 0,
   "content": "## errors and faults\n\nThe ledger has two different ways to fail.\n\n- **An overdraft is an error.** It is something a ledger expects: a customer asks for more than the balance. `apply` returns it as a value of type `LedgerError!I64`, and the caller decides what to do with it, here with `catch`.\n- **An overflow is a fault.** A balance past `I64.max`, about 92 quadrillion dollars, means the program is wrong. No caller can catch it. The program stops at the operation and prints a fault report."
  },
  {
   "id": "cu-401-01:keep-a-golden",
   "edition": "CU-401.2",
   "title": "keep a golden",
   "clauses": "",
   "url": "/university/401/01-ledger/#keep-a-golden",
   "internal": 0,
   "content": "## keep a golden\n\nA *golden* is a saved output that you have checked by hand and that later runs must match byte for byte. The output above is right: you checked the interest and the rejected entry. Save it:\n\n```text\n$ cint run ledger.ci > golden.txt\n```\n\nNow make a mistake. Change the interest entry's rate from `450` to `45` and run again into a second file:\n\n```text\n$ cint run ledger.ci > after.txt\n```\n\nCompare the two files. In VS Code, right-click `golden.txt` in the Explorer and choose **Select for Compare**, then right-click `after.txt` and choose **Compare with Selected**. In a terminal on macOS or Linux, use `diff`:\n\n```text\n$ diff golden.txt after.txt\n3c3\n< 2: interest      450 -> 849.60\n---\n> 2: interest       45 -> 849.51\n5,6c5,6\n< 4: deposit        99 -> 850.59\n< final balance: 850.59\n---\n> 4: deposit        99 -> 850.50\n> final balance: 850.50\n```\n\nIn PowerShell on Windows, `fc.exe /b golden.txt after.txt` says whether the two files match, and VS Code's compare shows the lines that differ. Type `fc.exe` in full, since `fc` alone means something else in PowerShell.\n\n**Read the first line that differs.** Line 3 is the first difference, and it names entry 2. Every later difference follows from it: the balance after entry 2 is 9 cents short, so every balance after it is too. The first differing line points at the change; the lines after it are consequences.\n\nThe tests still pass with the typo, because none of them reads `book`. That is one thing a golden is for: it checks the whole run, including data no test looks at.\n\nPut `450` back and check that the run matches the golden again. `diff` prints nothing when the files are the same."
  },
  {
   "id": "cu-401-01:a-mistake-only-the-tests-catch",
   "edition": "CU-401.2",
   "title": "a mistake only the tests catch",
   "clauses": "",
   "url": "/university/401/01-ledger/#a-mistake-only-the-tests-catch",
   "internal": 0,
   "content": "## a mistake only the tests catch\n\nNow make a different change. Replace the body of `daily_interest` with a plain division that looks as if it does the same thing:\n\n```ci\n    return balance * basis_points / (10_000 * 365);\n```\n\nRun it and compare with the golden. There is no difference: 10.47 cents rounds down to 10, the same result as rounding to the nearest cent. The tests disagree:\n\n```text\n$ cint test ledger.ci\ntest ledger.ci:71 \"interest ties round to even\" ... FAILED\nfault[E_ASSERT]: assertion failed\n  --> ledger.ci:73:12\n   |\n73 |     assert(daily_interest(5_475_000, 1) == 2);  // exactly 1.5 cents: rounds to 2\n   |            ^ assert.checked.bool\n   |\n   = operation: assert.checked.bool\n   = operand-count: 2\n   = operand: I64 1\n   = operand: I64 2\n   ...\ntest ledger.ci:76 \"an overdraft is an error\" ... ok\ntest ledger.ci:81 \"an overflow is a fault\" ... ok\n2 of 3 tests passed\n```\n\nThe two operands are the two sides of the comparison: the function returned 1 where the test wanted 2, because `/` rounds down. A golden holds what one run printed; a test holds a case chosen because it is hard. A program you intend to keep needs both. Put `muldiv` back."
  },
  {
   "id": "cu-401-01:when-it-faults",
   "edition": "CU-401.2",
   "title": "when it faults",
   "clauses": "",
   "url": "/university/401/01-ledger/#when-it-faults",
   "internal": 0,
   "content": "## when it faults\n\nChange the last entry to deposit the largest `I64`:\n\n```ci\n    book[4] = Entry(DEPOSIT, I64.max);\n```\n\n```text\n$ cint run ledger.ci\n0: deposit    125000 -> 1250.00\n1: withdraw    40050 -> 849.50\n2: interest      450 -> 849.60\n3: rejected, overdrawn\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> ledger.ci:24:28\n   |\n24 |             return balance + e.cents;\n   |                            ^ add.checked.i64\n   |\n   = operation: add.checked.i64\n   = operand-count: 2\n   = operand: I64 84960\n   = operand: I64 9223372036854775807\n   = exact:   9223372036854860767\n   = limit:   I64 9223372036854775807\n   ...\n   = stack-depth: 1\n   = called from: ledger.ci:56:20\n```\n\nThe four lines before the fault are the program's output up to that point. The fault report goes to standard error, not standard output, so `cint run ledger.ci > after.txt` saves the four lines and the report still appears in the terminal. `cint run` exits with status 1.\n\nRun it again. With the same cint release, the report is the same, byte for byte, every time and on every computer: the same operation, the same operands and the same line. That makes a fault report a golden too. Save it and fix the program. When a fault comes back after a later change, compare the new report with the saved one to see whether it is the same fault or a new one. [201-07](../201/07-debugging-by-comparison.md) builds this into a method."
  },
  {
   "id": "cu-401-01:walk-through",
   "edition": "CU-401.2",
   "title": "walk-through",
   "clauses": "",
   "url": "/university/401/01-ledger/#walk-through",
   "internal": 0,
   "content": "## walk-through\n\n**`const U8 DEPOSIT = 0;`** gives each kind of entry a name with a type. `switch (e.kind)` matches against the names, and `default` takes any other value, which `apply` returns as `unknown_kind`.\n\n**`Entry[5] book;`** declares five entries, all zero, and the lines after it fill them in.\n\n**`catch (err) { ... continue; }`** handles the error where `apply` is called. `err` holds which error it was, and the `switch` prints a line for each. `continue` goes on to the next entry, so the line `I64 next = ...` never completes for a rejected entry.\n\n**`apply(100, Entry(WITHDRAW, 101)) catch -1`** is the short form: if `apply` returns an error, the whole expression is -1.\n\n**`{e.cents:>8}`** prints the amount right-aligned in 8 characters, and **`{balance:/100}`** prints cents as dollars with two decimal places.\n\n**A basis point is a hundredth of a percent.** That makes 450 basis points 4.50 percent. Dividing by 10,000 turns basis points into a fraction, and by 365 a yearly rate into a daily one. `muldiv` multiplies before it divides, holds the product exactly and rounds once."
  },
  {
   "id": "cu-401-01:extend-it",
   "edition": "CU-401.2",
   "title": "extend it",
   "clauses": "",
   "url": "/university/401/01-ledger/#extend-it",
   "internal": 0,
   "content": "## extend it\n\n1. Add a `FEE` kind that takes a fixed 2.50 from the balance and is refused as `overdrawn` when the balance is smaller. Save a new golden only after you have checked the new output by hand.\n2. Add a test for a withdrawal of exactly the balance. Should it be accepted?\n3. Pay 365 days of interest on 1000.00 at 4.50 percent, compounding daily, and print the balance at the end. Then round each day with `floor` instead of `half_even`. How much less does the account earn in a year?"
  },
  {
   "id": "cu-401-01:reference",
   "edition": "CU-401.2",
   "title": "reference",
   "clauses": "",
   "url": "/university/401/01-ledger/#reference",
   "internal": 0,
   "content": "## reference\n\n[error sets]({{SPEC}}#error-sets), [catch]({{SPEC}}#catch), [structs]({{SPEC}}#structs), [muldiv]({{SPEC}}#muldiv), [rounding modes]({{SPEC}}#rounding-modes), [tests]({{SPEC}}#tests), [fault record]({{SPEC}}#fault-record), [golden]({{GLOSSARY}}#golden)\n\nNext: [401-02, hunting an overflow](02-hunting-an-overflow.md)."
  },
  {
   "id": "cu-401-02:cu-401-2",
   "edition": "CU-401.2",
   "title": "CU-401.2",
   "clauses": "",
   "url": "/university/401/02-hunting-an-overflow/",
   "internal": 0,
   "content": "# 401-02: hunting an overflow\n\n<a id=\"401-02\"></a>This is lab 401-02 of CU-401.2, checked against cint 0.2.0.\n\n*You will summarize a month of temperature readings until a sum overflows two calls below `main`. Then you will find the reading where it broke and try three fixes. An exact check will show that the program's first output was wrong.*\n\nTake it after [201-09](../201/09-functions.md). It uses the method of [201-07](../201/07-debugging-by-comparison.md) from start to end."
  },
  {
   "id": "cu-401-02:the-program",
   "edition": "CU-401.2",
   "title": "the program",
   "clauses": "",
   "url": "/university/401/02-hunting-an-overflow/#the-program",
   "internal": 0,
   "content": "## the program\n\nA sensor sends a temperature once a minute, in hundredths of a degree Celsius, and the program reports each day's low, high, mean and spread. The spread is the standard deviation: the square root of the mean of the squared distances from the mean.\n\n```ci\n// weather.ci: a month of temperature readings, one a minute,\n// summarized day by day. A reading is in hundredths of a degree\n// Celsius, as the sensor sends it.\n\nconst I64 DAYS = 30;\nconst I64 PER_DAY = 1_440;\n\n// The reading at minute m of day d. It stands in for a file of real\n// readings: a base that warms a little each day, a daily swing that\n// peaks at 2 PM and a small, repeatable wobble.\nI32 reading(I64 d, I64 m) {\n    I64 base = 400 + 60 * d;\n    I64 from_peak = m - 840;\n    if (from_peak < 0) {\n        from_peak = -from_peak;\n    }\n    I64 swing = 600 - from_peak * 600 / 720;\n    I64 wobble = (d * PER_DAY + m) * 7_919 % 61 - 30;\n    return (base + swing + wobble) as I32;\n}\n\nI32 sum_of_squares[n](in I32[n] xs) {\n    I32 total = 0;\n    for i in 0..n {\n        total += xs[i] * xs[i];\n    }\n    return total;\n}\n\nvoid summarize(I64 d) {\n    I32[1_440] day;\n    I32 low = I32.max;\n    I32 high = I32.min;\n    I32 total = 0;\n    for m in 0..PER_DAY {\n        day[m] = reading(d, m);\n        if (day[m] < low) {\n            low = day[m];\n        }\n        if (day[m] > high) {\n            high = day[m];\n        }\n        total += day[m];\n    }\n    I32 mean = total / 1_440;\n    I32 variance = sum_of_squares(day) / 1_440 - mean * mean;\n    I32 spread = isqrt(variance);\n    \"day {d:>2}: low {low:/100}, high {high:/100}, mean {mean:/100}, spread {spread:/100}\\n\";\n}\n\nvoid main() {\n    for d in 1..=DAYS {\n        summarize(d);\n    }\n}\n```\n\n`variance` uses the formula from statistics books: the mean of the squares, less the square of the mean."
  },
  {
   "id": "cu-401-02:step-1-run-it-and-keep-what-it-printed",
   "edition": "CU-401.2",
   "title": "step 1: run it, and keep what it printed",
   "clauses": "",
   "url": "/university/401/02-hunting-an-overflow/#step-1-run-it-and-keep-what-it-printed",
   "internal": 0,
   "content": "## step 1: run it, and keep what it printed\n\n```text\n$ cint run weather.ci > golden.txt\nfault[E_OVERFLOW]: the exact result is outside the type's range\n  --> weather.ci:25:15\n   |\n25 |         total += xs[i] * xs[i];\n   |               ^ add.checked.i32\n   |\n   = operation: add.checked.i32\n   = operand-count: 2\n   = operand: I32 2146711192\n   = operand: I32 1201216\n   = exact:   2147912408\n   = limit:   I32 2147483647\n   = revision: c92d9c049c47774f269b91122ebc997629c7f7b431d5bd0b41b36a292759d57f\n   = source-map: none\n   = address: none\n   = stack-depth: 2\n   = called from: weather.ci:53:9\n   = called from: weather.ci:46:20\n   = fuel-consumed: 38831 (not part of the fault record)\n   = state: the program stopped; stdout holds what it wrote before the fault\n$ cat golden.txt\nday  1: low 3.40, high 10.84, mean 7.52, spread 1.87\nday  2: low 4.00, high 11.42, mean 8.12, spread 1.87\nday  3: low 4.60, high 12.07, mean 8.72, spread 1.87\nday  4: low 5.19, high 12.63, mean 9.32, spread 1.87\nday  5: low 5.79, high 13.30, mean 9.91, spread 1.93\nday  6: low 6.39, high 13.86, mean 10.52, spread 1.87\nday  7: low 6.98, high 14.42, mean 11.12, spread 1.88\nday  8: low 7.58, high 15.09, mean 11.71, spread 1.93\n```\n\nA golden should be checked by hand before it is saved. The lows, highs and means are easy to check against `reading`. The spreads are not, so this lab saves them unchecked, to show what that costs."
  },
  {
   "id": "cu-401-02:step-2-read-the-call-stack",
   "edition": "CU-401.2",
   "title": "step 2: read the call stack",
   "clauses": "",
   "url": "/university/401/02-hunting-an-overflow/#step-2-read-the-call-stack",
   "internal": 0,
   "content": "## step 2: read the call stack\n\nThe report names three places, from the outside in:\n\n1. `called from: weather.ci:53:9` is `summarize(d);` in `main`.\n2. `called from: weather.ci:46:20` is the call to `sum_of_squares` in `summarize`.\n3. `--> weather.ci:25:15` is the `+=` inside `sum_of_squares`, where the fault happened.\n\n`stack-depth: 2` counts the two calls below `main`. The output stops after day 8, so the fault came while summarizing day 9. The first operand is the running total of squares, 2146711192, and the second is one more square, 1201216, which is 1096 \u00d7 1096. Together they pass the largest `I32`, 2147483647."
  },
  {
   "id": "cu-401-02:step-3-locate-the-reading",
   "edition": "CU-401.2",
   "title": "step 3: locate the reading",
   "clauses": "",
   "url": "/university/401/02-hunting-an-overflow/#step-3-locate-the-reading",
   "internal": 0,
   "content": "## step 3: locate the reading\n\nThe report says which addition broke, but not at which minute. `cint debug locate` replays the run and shows the operations before the fault:\n\n```text\n$ cint debug locate weather.ci --save-case hot.case\nprogram    weather.ci   evaluator cpu-sir-interp, recorded as the case hot.case\ntarget     boundary 1 of 1, the program entry: the first fault, reproduced by replay\nbracket    the initial state; then boundary 1\nfault[E_OVERFLOW]: the exact result is outside the type's range\n   ...\nthe last 20 counted operations of boundary 1, of 357848 trace events (:trace shows them all)\n  ord  position           operation              operands                 value\n   ...\n344862                     add.wrap.i64           1360, 1                  1361\n344863  weather.ci:25:20   index.checked.i32      1361\n344864  weather.ci:25:28   index.checked.i32      1361\n344865  weather.ci:25:24   mul.checked.i32        1108, 1108               1227664\n344866  weather.ci:25:15   add.checked.i32        2145483528, 1227664      2146711192\n344867                     add.wrap.i64           1361, 1                  1362\n344868  weather.ci:25:20   index.checked.i32      1362\n344869  weather.ci:25:28   index.checked.i32      1362\n344870  weather.ci:25:24   mul.checked.i32        1096, 1096               1201216\n344871  weather.ci:25:15   add.checked.i32        2146711192, 1201216      E_OVERFLOW\n```\n\nThe lines with no position are the `for` loop moving `i` to the next index. The loop stops at its bound long before `i` could leave `I64`, so that step is recorded as a wrapping addition that cannot fault."
  },
  {
   "id": "cu-401-02:step-3-locate-the-reading-p1",
   "edition": "CU-401.2",
   "title": "step 3: locate the reading (part 2)",
   "clauses": "",
   "url": "/university/401/02-hunting-an-overflow/#step-3-locate-the-reading",
   "internal": 0,
   "content": "The index is 1362, so the reading that broke the sum was minute 1362 of day 9, at 10:42 PM: 10.96 degrees. There is nothing odd about it. The squares of day 9's readings average about 1.55 million, and 1,440 of them add up to more than an `I32` holds. The fault is where the total crossed the limit, not where the data was unusual. Keep `hot.case` for exercise 3 of extend it."
  },
  {
   "id": "cu-401-02:step-4-three-fixes",
   "edition": "CU-401.2",
   "title": "step 4: three fixes",
   "clauses": "",
   "url": "/university/401/02-hunting-an-overflow/#step-4-three-fixes",
   "internal": 0,
   "content": "## step 4: three fixes"
  },
  {
   "id": "cu-401-02:fix-1-a-wider-total",
   "edition": "CU-401.2",
   "title": "fix 1: a wider total",
   "clauses": "",
   "url": "/university/401/02-hunting-an-overflow/#fix-1-a-wider-total",
   "internal": 0,
   "content": "### fix 1: a wider total\n\nMake the total an `I64`, and square each reading as an `I64`:\n\n```ci\nI64 sum_of_squares[n](in I32[n] xs) {\n    I64 total = 0;\n    for i in 0..n {\n        I64 x = xs[i] as I64;\n        total += x * x;\n    }\n    return total;\n}\n```\n\nIn `summarize`, the variance becomes an `I64` too:\n\n```ci\n    I64 variance = sum_of_squares(day) / 1_440 - (mean as I64) * (mean as I64);\n    I32 spread = isqrt(variance) as I32;\n```\n\n```text\n$ cint run weather.ci > after.txt\n$ diff golden.txt after.txt\n8a9,30\n> day  9: low 8.18, high 15.65, mean 12.32, spread 1.88\n> day 10: low 8.77, high 16.30, mean 12.92, spread 1.87\n> day 11: low 9.37, high 16.88, mean 13.51, spread 1.94\n...\n> day 29: low 20.21, high 27.63, mean 24.31, spread 2.00\n> day 30: low 20.81, high 28.23, mean 24.92, spread 1.88\n```\n\nThe first eight days are unchanged and the month is complete. The fault is gone."
  },
  {
   "id": "cu-401-02:fix-2-subtract-the-mean-first",
   "edition": "CU-401.2",
   "title": "fix 2: subtract the mean first",
   "clauses": "",
   "url": "/university/401/02-hunting-an-overflow/#fix-2-subtract-the-mean-first",
   "internal": 0,
   "content": "### fix 2: subtract the mean first\n\nPut the `I32` version back. This time, square each reading's distance from the mean instead of the reading itself. The distances are a few hundred at most, so their squares are small:\n\n```ci\nI32 sum_of_squared_deviations[n](in I32[n] xs, I32 mean) {\n    I32 total = 0;\n    for i in 0..n {\n        I32 dev = xs[i] - mean;\n        total += dev * dev;\n    }\n    return total;\n}\n```\n\n```ci\n    I32 variance = sum_of_squared_deviations(day, mean) / 1_440;\n    I32 spread = isqrt(variance);\n```\n\n```text\n$ cint run weather.ci > after.txt\n$ diff golden.txt after.txt\n5c5\n< day  5: low 5.79, high 13.30, mean 9.91, spread 1.93\n---\n> day  5: low 5.79, high 13.30, mean 9.91, spread 1.87\n7,8c7,30\n< day  7: low 6.98, high 14.42, mean 11.12, spread 1.88\n< day  8: low 7.58, high 15.09, mean 11.71, spread 1.93\n---\n> day  7: low 6.98, high 14.42, mean 11.12, spread 1.87\n> day  8: low 7.58, high 15.09, mean 11.71, spread 1.87\n> day  9: low 8.18, high 15.65, mean 12.32, spread 1.87\n...\n```\n\nThis fix changes days the overflow never touched. Days 5, 7 and 8 now read 1.87, and so does every other day."
  },
  {
   "id": "cu-401-02:which-spread-is-right",
   "edition": "CU-401.2",
   "title": "which spread is right",
   "clauses": "",
   "url": "/university/401/02-hunting-an-overflow/#which-spread-is-right",
   "internal": 0,
   "content": "### which spread is right\n\nNeither `cint run` nor the reference can say which formula is right, because each computes exactly what its program says. So check with exact arithmetic outside cint. `fractions.Fraction` in Python 3.13 on Ubuntu 24.04 computes each day's variance with no rounding at all. Its square root, rounded down to hundredths as `isqrt` rounds, is 1.87 on all 30 days.\n\nSo fix 2 is right on every day. Fix 1 is wrong on 20 of the 30, and the first program was already wrong on days 5, 7 and 8. The cause is the formula. `mean` is rounded down to a whole hundredth, and the formula squares it: an error of less than 1 in `mean` becomes an error of up to about 2 \u00d7 `mean` in `mean * mean`. As the days warm, the error grows. Subtracting the mean first keeps every number small, so the sum stays inside `I32`. It also changes what the rounding costs. With the distances from the rounded `mean`, the rounding adds only its own square to the variance, and that square is less than 1.\n\nThe golden was wrong from the start, and that went unnoticed because the spreads were never checked. Now that fix 2 is checked, save a new golden from it as a separate change."
  },
  {
   "id": "cu-401-02:fix-3-report-instead-of-stopping",
   "edition": "CU-401.2",
   "title": "fix 3: report instead of stopping",
   "clauses": "",
   "url": "/university/401/02-hunting-an-overflow/#fix-3-report-instead-of-stopping",
   "internal": 0,
   "content": "### fix 3: report instead of stopping\n\nPut the first version back once more. This fix keeps the `I32` total, but turns the overflow into an error that the program handles. `add_result` returns the sum, or the error `overflow` when the sum does not fit, and `try` passes that error up to the caller:\n\n```ci\nArithError!I32 sum_of_squares[n](in I32[n] xs) {\n    I32 total = 0;\n    for i in 0..n {\n        total = try add_result(total, xs[i] * xs[i]);\n    }\n    return total;\n}\n```\n\n```ci\n    I32 squares = sum_of_squares(day) catch (err) {\n        \"day {d:>2}: too large to summarize in I32\\n\";\n        return;\n    };\n    I32 variance = squares / 1_440 - mean * mean;\n```\n\n```text\n$ cint run weather.ci\n...\nday  8: low 7.58, high 15.09, mean 11.71, spread 1.93\nday  9: too large to summarize in I32\nday 10: too large to summarize in I32\n...\nday 30: too large to summarize in I32\n```\n\nThe program finishes and exits with status 0, but it answers nothing after day 8, and days 5, 7 and 8 are still wrong. Turning a fault into an error is the right fix when some inputs are truly out of range. Here the readings are ordinary and only the total is too narrow, so the error hides the problem."
  },
  {
   "id": "cu-401-02:what-each-fix-changes",
   "edition": "CU-401.2",
   "title": "what each fix changes",
   "clauses": "",
   "url": "/university/401/02-hunting-an-overflow/#what-each-fix-changes",
   "internal": 0,
   "content": "## what each fix changes\n\nThe reference's record of each version shows what it changed:\n\n| | Outcome | Output | Fuel | Spreads right |\n|---|---|---|---|---|\n| The first program | fault on day 9 | 8 days | 38831 | 5 of 8 |\n| Fix 1, a wider total | value | 30 days | 129691 | 10 of 30 |\n| Fix 2, the mean first | value | 30 days | 129691 | 30 of 30 |\n| Fix 3, an error | value | 8 days and 22 refusals | 114436 | 5 of 8 |\n\nFixes 1 and 2 have the same fuel, because they make the same calls and the same passes through their loops. Fuel follows the path a run takes, not the arithmetic on it. The outputs differ, and only the exact check showed which was right."
  },
  {
   "id": "cu-401-02:walk-through",
   "edition": "CU-401.2",
   "title": "walk-through",
   "clauses": "",
   "url": "/university/401/02-hunting-an-overflow/#walk-through",
   "internal": 0,
   "content": "## walk-through\n\n**`I32 reading(I64 d, I64 m)`** computes in `I64` and converts once at the end with `as I32`. If a reading ever left the range of `I32`, that conversion would fault there.\n\n**`from_peak * 600 / 720`** multiplies before it divides. Dividing first would make `600 / 720` zero, and the swing would disappear: every minute would read as if it were 2 PM.\n\n**`isqrt(variance)`** is the integer square root, rounded down. It takes an integer and returns one of the same type.\n\n**`ArithError!I32`** is the type of a value that is either an `I32` or an `ArithError`. A **result form** is a built-in such as `add_result`, `sub_result` or `mul_result` that returns its answer or an `ArithError` where the plain operator would fault.\n\n**`try add_result(...)`** returns the error from `sum_of_squares` at once, when there is one, and otherwise gives the sum.\n\n**`catch (err) { ... return; }`** runs its block when `sum_of_squares` returns an error. The block prints a line and leaves `summarize` early, so the day gets no summary and the month goes on."
  },
  {
   "id": "cu-401-02:extend-it",
   "edition": "CU-401.2",
   "title": "extend it",
   "clauses": "",
   "url": "/university/401/02-hunting-an-overflow/#extend-it",
   "internal": 0,
   "content": "## extend it\n\n1. Store the readings as `I16`, as many sensors send them, and change the types to match. Which fixes need a wider type for the squares, and why?\n2. Change `reading` so that each day swings twice as far. Does fix 2 still fit in `I32`? Work out the largest distance from the mean before you run it.\n3. Copy `hot.case` to a folder without `weather.ci` and run `cint debug locate hot.case` there. Does it reproduce the fault, and do its last operations match step 3?"
  },
  {
   "id": "cu-401-02:reference",
   "edition": "CU-401.2",
   "title": "reference",
   "clauses": "",
   "url": "/university/401/02-hunting-an-overflow/#reference",
   "internal": 0,
   "content": "## reference\n\n[fault record]({{SPEC}}#fault-record), [conversions]({{SPEC}}#conversions), [isqrt]({{SPEC}}#isqrt), [result forms]({{SPEC}}#result-forms), [error sets]({{SPEC}}#error-sets), [catch]({{SPEC}}#catch), [golden]({{GLOSSARY}}#golden)\n\nBack to [401: labs](README.md)."
  },
  {
   "id": "cu-401-overview:cu-401-2",
   "edition": "CU-401.2",
   "title": "CU-401.2",
   "clauses": "",
   "url": "/university/401/",
   "internal": 0,
   "content": "# 401: labs\n\nThis page is CU-401.2, edition 2 of 401: labs, checked against cint 0.2.0 and released on {{RELEASE_DATE}}.\n\nThis edition is current. Every program in it was run on cint 0.2.0 with each of GCC, Clang, MSVC and Apple Clang, and every output comes from those runs. The text of this edition does not change after its release. Corrections that change nothing a reader would see are listed in [ERRATA.md](../ERRATA.md). A new edition is published when a release changes what a lab shows or when labs are added. Lab identifiers are the same in every edition and are never reused.\n\nA lab is one program, larger than a lesson's, built in steps with its tests and its saved outputs. Each lab names the lessons it builds on; take them first."
  },
  {
   "id": "cu-401-overview:labs",
   "edition": "CU-401.2",
   "title": "labs",
   "clauses": "",
   "url": "/university/401/#labs",
   "internal": 0,
   "content": "## labs\n\n| Lab | Title | You build | After |\n|---|---|---|---|\n| [401-01](01-ledger.md) | an exact ledger | a bank ledger in whole cents, with tests and a saved, checked output | 201-04 |\n| [401-02](02-hunting-an-overflow.md) | hunting an overflow | a fault traced to its cause and fixed three ways | 201-09 |"
  },
  {
   "id": "cu-401-overview:changes-since-the-previous-edition",
   "edition": "CU-401.2",
   "title": "changes since the previous edition",
   "clauses": "",
   "url": "/university/401/#changes-since-the-previous-edition",
   "internal": 0,
   "content": "## changes since the previous edition\n\nCU-401.2 replaces CU-401.1, which stays readable.\n\n- Lab 401-02 is new.\n- Every lab's first line names CU-401.2.\n- 401-01: the fault section links to 201-07, and the page ends with a link to 401-02.\n\nNo program's output changed."
  },
  {
   "id": "cu-000-errata:cu-000-2",
   "edition": "CU-000.2",
   "title": "CU-000.2",
   "clauses": "",
   "url": "/university/errata/",
   "internal": 0,
   "content": "# errata\n\nThis page lists corrections to released editions of the cint university courses that change nothing a reader would see when running a program: a typo fixed, a broken link repaired or a sentence made clearer. The edition's own text is not edited; its corrections are listed here, numbered per edition (`CU-101.1 E1`, `CU-101.1 E2`). A correction that changes an output, a message a lesson shows or a rule a lesson cites is published in a new edition, not as an erratum.\n\nEach entry gives the erratum's name, the lesson, the text as published, the corrected text and the date it was listed."
  },
  {
   "id": "cu-000-errata:cu-000-1",
   "edition": "CU-000.2",
   "title": "CU-000.1",
   "clauses": "",
   "url": "/university/errata/#cu-000-1",
   "internal": 0,
   "content": "## CU-000.1\n\nThis edition has no errata."
  },
  {
   "id": "cu-000-errata:cu-101-1",
   "edition": "CU-000.2",
   "title": "CU-101.1",
   "clauses": "",
   "url": "/university/errata/#cu-101-1",
   "internal": 0,
   "content": "## CU-101.1\n\nThis edition has no errata."
  },
  {
   "id": "cu-000-errata:cu-201-1",
   "edition": "CU-000.2",
   "title": "CU-201.1",
   "clauses": "",
   "url": "/university/errata/#cu-201-1",
   "internal": 0,
   "content": "## CU-201.1\n\nThis edition has no errata."
  },
  {
   "id": "cu-000-errata:cu-401-1",
   "edition": "CU-000.2",
   "title": "CU-401.1",
   "clauses": "",
   "url": "/university/errata/#cu-401-1",
   "internal": 0,
   "content": "## CU-401.1\n\nThis edition has no errata."
  },
  {
   "id": "cu-000-errata:cu-000-2-2",
   "edition": "CU-000.2",
   "title": "CU-000.2",
   "clauses": "",
   "url": "/university/errata/#cu-000-2",
   "internal": 0,
   "content": "## CU-000.2\n\nThis edition has no errata."
  },
  {
   "id": "cu-000-errata:cu-101-2",
   "edition": "CU-000.2",
   "title": "CU-101.2",
   "clauses": "",
   "url": "/university/errata/#cu-101-2",
   "internal": 0,
   "content": "## CU-101.2\n\nThis edition has no errata."
  },
  {
   "id": "cu-000-errata:cu-201-2",
   "edition": "CU-000.2",
   "title": "CU-201.2",
   "clauses": "",
   "url": "/university/errata/#cu-201-2",
   "internal": 0,
   "content": "## CU-201.2\n\nThis edition has no errata."
  },
  {
   "id": "cu-000-errata:cu-301-1",
   "edition": "CU-000.2",
   "title": "CU-301.1",
   "clauses": "",
   "url": "/university/errata/#cu-301-1",
   "internal": 0,
   "content": "## CU-301.1\n\nThis edition has no errata."
  },
  {
   "id": "cu-000-errata:cu-401-2",
   "edition": "CU-000.2",
   "title": "CU-401.2",
   "clauses": "",
   "url": "/university/errata/#cu-401-2",
   "internal": 0,
   "content": "## CU-401.2\n\nThis edition has no errata."
  },
  {
   "id": "cu-from-c:cu-000-2",
   "edition": "CU-000.2",
   "title": "CU-000.2",
   "clauses": "",
   "url": "/university/from-c/",
   "internal": 0,
   "content": "# cint for C programmers\n\n<a id=\"from-c\"></a>This page is part of CU-000.2, checked against cint 0.2.0.\n\n*Read this before [201](201/README.md) if you know C. It lists what carries over, what changes and the lesson that shows each change running.*"
  },
  {
   "id": "cu-from-c:what-carries-over",
   "edition": "CU-000.2",
   "title": "what carries over",
   "clauses": "",
   "url": "/university/from-c/#what-carries-over",
   "internal": 0,
   "content": "## what carries over\n\nMuch of cint reads like C. Functions are declared with the return type first, statements end with a semicolon and blocks are in braces. `if`, `else`, `while`, `break`, `continue` and `return` keep their meaning, and so does the C form of `for`. `switch` looks the same and differs in the ways listed below. Comments are written with `//`. Integer types say their width in the name: `I8` to `I1024` are signed and `U8` to `U512` are unsigned. `I32` is C's `int32_t` and `U8` is `uint8_t`. cint compiles a program to C17, and [201-00](201/00-start-here.md) shows the C it makes."
  },
  {
   "id": "cu-from-c:what-changes",
   "edition": "CU-000.2",
   "title": "what changes",
   "clauses": "",
   "url": "/university/from-c/#what-changes",
   "internal": 0,
   "content": "## what changes"
  },
  {
   "id": "cu-from-c:what-changes-p1",
   "edition": "CU-000.2",
   "title": "what changes (part 2)",
   "clauses": "",
   "url": "/university/from-c/#what-changes",
   "internal": 0,
   "content": "| In C | In cint | Shown in |\n|---|---|---|\n| Signed overflow is undefined behavior. | Every plain operator is checked. A result that does not fit stops the program with a fault that names the operation, the operands and the exact result. | [201-01](201/01-numbers-that-hold.md) |\n| Unsigned arithmetic wraps without a sign of it. | Plain unsigned operators are checked too. Wrapping is written as an operator of its own, such as `+%`, and saturating as `+|`. | [201-03](201/03-operators-at-the-edge.md) |\n| A shift by the width of the type or more is undefined. | A shift that loses bits faults. | [201-03](201/03-operators-at-the-edge.md) |\n| Integer promotion and implicit conversions happen everywhere. | No conversion happens on its own, not even to a wider type. `as` converts and faults if the value does not fit. `as%` keeps the low bits and `as?` hands the failure to the program. | [201-02](201/02-types-and-conversions.md) |\n| `/` rounds toward zero, and `%` takes the sign of the dividend. | `/` rounds toward negative infinity, and `%` takes the sign of the divisor, as in Python. `div_trunc` and `rem_trunc` give C's results. | [201-04](201/04-division-and-rounding.md) |\n| A rounding rule is set somewhere else, or implied. | Each rounded division names its rule, such as `div_round(a, b, half_even)`. | [201-04](201/04-division-and-rounding.md) |\n| An array index is not checked. | Every index is checked, and one past the end faults with `E_BOUNDS`. | [101-12](101/12-lists.md) |\n| A function takes a pointer and a length. | A function takes a view of an array, `in I64[n]` to read it or `inout I64[n]` to change it, and the length travels with it. | [201-07](201/07-debugging-by-comparison.md), [201-09](201/09-functions.md) |\n| A deep recursion can crash when the stack runs out, unless the compiler turns it into a loop. The depth depends on the machine. | At most 256 calls can b"
  },
  {
   "id": "cu-from-c:the-same-program-on-every-compiler",
   "edition": "CU-000.2",
   "title": "the same program on every compiler",
   "clauses": "",
   "url": "/university/from-c/#the-same-program-on-every-compiler",
   "internal": 0,
   "content": "## the same program on every compiler\n\nA C program that overflows can print one thing at `-O0` and another at `-O2`, and [301-01](301/01-when-64-bits-are-not-enough.md) shows one doing exactly that. A cint program prints the same bytes on GCC, Clang, MSVC and Apple Clang. When it faults, it prints the same fault record on each of them, field for field. So one saved output checks a run on any of those compilers, as [201-05](201/05-tests-and-goldens.md) shows."
  },
  {
   "id": "cu-from-c:where-to-start",
   "edition": "CU-000.2",
   "title": "where to start",
   "clauses": "",
   "url": "/university/from-c/#where-to-start",
   "internal": 0,
   "content": "## where to start\n\nStart with [201-00](201/00-start-here.md). It sets up cint and shows the four commands and the C that a small program becomes."
  },
  {
   "id": "cu-from-python:cu-000-2",
   "edition": "CU-000.2",
   "title": "CU-000.2",
   "clauses": "",
   "url": "/university/from-python/",
   "internal": 0,
   "content": "# cint for Python and NumPy programmers\n\n<a id=\"from-python\"></a>This page is part of CU-000.2, checked against cint 0.2.0.\n\n*Read this before [201](201/README.md) if you know Python. It lists what carries over, what changes and the lesson that shows each change running.*"
  },
  {
   "id": "cu-from-python:what-carries-over",
   "edition": "CU-000.2",
   "title": "what carries over",
   "clauses": "",
   "url": "/university/from-python/#what-carries-over",
   "internal": 0,
   "content": "## what carries over\n\n`for i in 0..n` counts from 0 to n - 1, as `for i in range(n)` does. `/` on integers rounds toward negative infinity and `%` takes the sign of the divisor, which is Python's rule for `//` and `%`. A string with `{name}` inside prints the value of `name`, much as an f-string does. Tests can live in the same file as the code, and `cint test` runs them."
  },
  {
   "id": "cu-from-python:what-changes",
   "edition": "CU-000.2",
   "title": "what changes",
   "clauses": "",
   "url": "/university/from-python/#what-changes",
   "internal": 0,
   "content": "## what changes"
  },
  {
   "id": "cu-from-python:what-changes-p1",
   "edition": "CU-000.2",
   "title": "what changes (part 2)",
   "clauses": "",
   "url": "/university/from-python/#what-changes",
   "internal": 0,
   "content": "| In Python or NumPy | In cint | Shown in |\n|---|---|---|\n| `int` grows to any size. | Every integer has a fixed width, from `I8` to `I1024`. A result that does not fit stops the program with a fault that names the operation, the operands and the exact result. | [201-01](201/01-numbers-that-hold.md), [301-01](301/01-when-64-bits-are-not-enough.md) |\n| A NumPy `int64` array wraps without a warning, and an `int64` scalar warns and carries on with the wrapped value. | Arrays and single values are checked the same way. Wrapping is written as an operator of its own, such as `+%`. | [201-01](201/01-numbers-that-hold.md), [201-03](201/03-operators-at-the-edge.md) |\n| `astype(np.int16)` keeps the low bits of a value that does not fit. | `as I16` faults when the value does not fit. `as% I16` keeps the low bits when that is the intent. | [201-02](201/02-types-and-conversions.md) |\n| A variable takes whatever type is assigned to it. | Each variable is declared with its type, and no value changes type on its own. | [201-02](201/02-types-and-conversions.md) |\n| `round` rounds ties to even, without saying so at the call. | Each rounded division names its rule, such as `div_round(a, b, half_even)`. | [201-04](201/04-division-and-rounding.md) |\n| `float` is the default for fractions. | There is no floating-point type. Every value in these courses is an integer. | |\n| Indentation marks a block. | Braces mark a block, and every body needs them. | [201-08](201/08-control-flow.md) |\n| A deep recursion stops with `RecursionError`. | At most 256 calls can be in progress at once, counting `main`, and one more faults with `E_DEPTH`. | [201-09](201/09-functions.md) |\n| A list grows and shrinks. | An array has a fixed length, and every index is checked. | [101-12](101/12-lists.md) |\n| A function can change a list it is given. | A function says what it may do with an array: `in` to read it, `in"
  },
  {
   "id": "cu-from-python:why-the-fixed-widths",
   "edition": "CU-000.2",
   "title": "why the fixed widths",
   "clauses": "",
   "url": "/university/from-python/#why-the-fixed-widths",
   "internal": 0,
   "content": "## why the fixed widths\n\nPython's integers never run out of room, so a sum or product of them is never cut short. A fixed width matches the data that sensors, files, images and network packets carry. In NumPy the price of a fixed width is a wrong answer when a value outgrows it, with a warning for a single value and none for an array. In cint the price is a fault at the exact operation, with the numbers that caused it. When a program needs more room, a wider type such as `I128` or `I1024` holds it. It needs an `as` wherever it meets a narrower value, as [301-04](301/04-big-exact-numbers.md) shows with 100 factorial."
  },
  {
   "id": "cu-from-python:the-same-output-on-every-compiler",
   "edition": "CU-000.2",
   "title": "the same output on every compiler",
   "clauses": "",
   "url": "/university/from-python/#the-same-output-on-every-compiler",
   "internal": 0,
   "content": "## the same output on every compiler\n\nA cint program prints the same bytes on every compiler cint supports, and a fault prints the same record on each of them. [201-05](201/05-tests-and-goldens.md) builds a way of testing on this: save a program's output once and compare every run after it against the saved copy."
  },
  {
   "id": "cu-from-python:where-to-start",
   "edition": "CU-000.2",
   "title": "where to start",
   "clauses": "",
   "url": "/university/from-python/#where-to-start",
   "internal": 0,
   "content": "## where to start\n\nStart with [201-00](201/00-start-here.md). It sets up cint and shows its four commands."
  },
  {
   "id": "cu-000-index:cu-000-2",
   "edition": "CU-000.2",
   "title": "CU-000.2",
   "clauses": "",
   "url": "/university/",
   "internal": 0,
   "content": "# cint university\n\ncint university teaches the cint language through short lessons, each built around one program that runs in your browser or on your computer. Every output in a lesson was printed by the cint release named at the top of that lesson."
  },
  {
   "id": "cu-000-index:courses",
   "edition": "CU-000.2",
   "title": "courses",
   "clauses": "",
   "url": "/university/#courses",
   "internal": 0,
   "content": "## courses\n\n| Course | For | Edition | Checked against |\n|---|---|---|---|\n| [101: first programs](101/README.md) | People who have never programmed | CU-101.2 | cint 0.2.0 |\n| [201: cint for programmers](201/README.md) | People who program in C, Python or a language like them | CU-201.2 | cint 0.2.0 |\n| [301: wider numbers](301/README.md) | Readers who finished 201 up to 201-09 | CU-301.1 | cint 0.2.0 |\n| [401: labs](401/README.md) | Graduates of 101 or 201 | CU-401.2 | cint 0.2.0 |\n\nA newcomer starts with 101 and a programmer with 201. A programmer who knows C or Python can first read [cint for C programmers](from-c.md) or [cint for Python and NumPy programmers](from-python.md). These pages list what changes and where each change is shown. Each lab lists the lessons it builds on. To run programs outside the browser, first [set up cint on your computer](setup.md)."
  },
  {
   "id": "cu-000-index:editions",
   "edition": "CU-000.2",
   "title": "editions",
   "clauses": "",
   "url": "/university/#editions",
   "internal": 0,
   "content": "## editions\n\nThe courses are published in editions, the same way the cint specification is.\n\n- **Names.** An edition is named `CU-NNN.E`: `CU` for cint university, the course number `NNN` and the edition number `E`. `CU-101.1` is the first edition of 101. This page, the setup page and the two pages for programmers form course 000, whose current edition is `CU-000.2`.\n- **Tied to a release.** Each edition names the cint release it was checked against. Every program in it was run on that release with each of GCC, Clang, MSVC and Apple Clang. Every output block comes from those runs.\n- **Frozen text.** Once released, an edition's text does not change. A correction that changes nothing a reader would see when running a program, such as a typo fixed or a sentence made clearer, is listed in [ERRATA.md](ERRATA.md). It is written `CU-101.1 E1`. The edition keeps its number.\n- **New editions.** A course gets a new edition when a release changes a program's output, a message a lesson shows or a rule a lesson cites in that course. No other course does. A course that gains lessons also gets a new edition. Each edition is complete in itself: no lesson in it links to an unpublished lesson. Each new edition ends with a list of what changed since the edition before it, lesson by lesson. Earlier editions stay readable beside the new one.\n- **Stable identifiers.** Each lesson has an identifier, such as `101-05`, and a named link anchor, both the same in every edition and never reused. A lesson's place in the course belongs to its edition and may change; its identifier does not. Link to a lesson by its identifier."
  },
  {
   "id": "cu-000-index:current-editions",
   "edition": "CU-000.2",
   "title": "current editions",
   "clauses": "",
   "url": "/university/#current-editions",
   "internal": 0,
   "content": "## current editions\n\n| Edition | Title | First released in |\n|---|---|---|\n| CU-000.2 | cint university, setup and the pages for programmers | cint 0.2.0 |\n| CU-101.2 | 101: first programs | cint 0.2.0 |\n| CU-201.2 | 201: cint for programmers | cint 0.2.0 |\n| CU-301.1 | 301: wider numbers | cint 0.2.0 |\n| CU-401.2 | 401: labs | cint 0.2.0 |\n\nThe earlier editions, CU-000.1, CU-101.1, CU-201.1 and CU-401.1, stay readable beside these."
  },
  {
   "id": "cu-000-index:changes-since-the-previous-edition",
   "edition": "CU-000.2",
   "title": "changes since the previous edition",
   "clauses": "",
   "url": "/university/#changes-since-the-previous-edition",
   "internal": 0,
   "content": "## changes since the previous edition\n\nCU-000.2 replaces CU-000.1.\n\n- Two pages are new: [cint for C programmers](from-c.md) and [cint for Python and NumPy programmers](from-python.md).\n- The courses section points programmers who know C or Python to those two pages.\n- This page lists course 301 and the new editions of 101, 201 and 401.\n- The setup page is unchanged."
  },
  {
   "id": "cu-000-setup:cu-000-2",
   "edition": "CU-000.2",
   "title": "CU-000.2",
   "clauses": "",
   "url": "/university/setup/",
   "internal": 0,
   "content": "# set up cint on your computer\n\nEvery program in cint university runs in your browser at [integerc.dev](https://integerc.dev), with nothing to install. This page sets up the other way: cint on your own computer, an editor to write programs in and a terminal to run them.\n\nYou need three things:\n\n- **Python 3.12 or later.** The build scripts are written in Python.\n- **A C compiler.** cint turns your program into C, then uses this compiler to build it. On Windows that is Microsoft's C compiler (MSVC), on macOS it is Apple Clang and on Linux it is GCC or Clang.\n- **The cint source**, downloaded from {{SOURCE_URL}} and unpacked into a folder."
  },
  {
   "id": "cu-000-setup:build-cint",
   "edition": "CU-000.2",
   "title": "build cint",
   "clauses": "",
   "url": "/university/setup/#build-cint",
   "internal": 0,
   "content": "## build cint\n\nPick the steps for your system. Each one ends with the `cint` command and its debugging tools in a folder called `cint` in your home folder."
  },
  {
   "id": "cu-000-setup:windows",
   "edition": "CU-000.2",
   "title": "Windows",
   "clauses": "",
   "url": "/university/setup/#windows",
   "internal": 0,
   "content": "### Windows\n\n1. Install Python from [python.org](https://www.python.org/downloads/). On the installer's first screen, select **Add python.exe to PATH**.\n2. Install **Build Tools for Visual Studio** from [visualstudio.microsoft.com](https://visualstudio.microsoft.com/downloads/). In the installer, choose the workload **Desktop development with C++**.\n3. In File Explorer, right-click the folder where you unpacked cint and choose **Open in Terminal**. Then run these two commands:\n\n   ```text\n   python tools\\cint_bootstrap.py --leg msvc --out \"$HOME\\cint\"\n   python tools\\cint_tools.py --leg msvc --out \"$HOME\\cint\"\n   ```\n\n4. Add the new folder to your PATH, so that `cint` works from any folder. Open the Start menu and search for **Edit environment variables for your account**. Select **Path** and choose **Edit**, then **New**. Type the folder's full path, for example `C:\\Users\\ada\\cint`, then close and reopen any open terminals.\n\nThe build finds the C compiler on its own. You do not need a \"Developer Command Prompt\"."
  },
  {
   "id": "cu-000-setup:macos",
   "edition": "CU-000.2",
   "title": "macOS",
   "clauses": "",
   "url": "/university/setup/#macos",
   "internal": 0,
   "content": "### macOS\n\n1. Open **Terminal** and install Apple's command line tools, which include Apple Clang:\n\n   ```text\n   xcode-select --install\n   ```\n\n2. Install Python 3.12 or later from [python.org](https://www.python.org/downloads/). The command line tools include an older Python that is too old for the build.\n3. In Terminal, go to the folder where you unpacked cint and run these two commands:\n\n   ```text\n   python3 tools/cint_bootstrap.py --leg apple-clang --out ~/cint\n   python3 tools/cint_tools.py --leg apple-clang --out ~/cint\n   ```\n\n4. Add the folder to your PATH, then open a new Terminal window:\n\n   ```text\n   echo 'export PATH=\"$HOME/cint:$PATH\"' >> ~/.zprofile\n   ```"
  },
  {
   "id": "cu-000-setup:linux",
   "edition": "CU-000.2",
   "title": "Linux",
   "clauses": "",
   "url": "/university/setup/#linux",
   "internal": 0,
   "content": "### Linux\n\nThese commands are for Ubuntu 24.04 or later and Debian 13 or later; older releases come with a Python older than 3.12. Other distributions have the same packages under similar names.\n\n1. Install the compiler and Python:\n\n   ```text\n   sudo apt install gcc python3\n   ```\n\n2. Go to the folder where you unpacked cint and run these two commands:\n\n   ```text\n   python3 tools/cint_bootstrap.py --leg gcc --out ~/cint\n   python3 tools/cint_tools.py --leg gcc --out ~/cint\n   ```\n\n3. Add the folder to your PATH, then open a new terminal:\n\n   ```text\n   echo 'export PATH=\"$HOME/cint:$PATH\"' >> ~/.bashrc\n   ```\n\nThe first command builds `cint`. It runs in three steps and prints a line for each. First, a small compiler written in C is built. That compiler translates the cint compiler, which is written in cint, into C. Then your C compiler builds that C into the `cint` command.\n\nThe second command builds five debugging tools into the same folder. Each one runs as a `cint` command:\n\n- `cint workbench` opens an interactive session that can rewind a run. `cint repl` opens the same session.\n- `cint debug` locates, replays and compares faults.\n- `cint explain` shows what the compiler knows about each function.\n- `cint interp` is the interpreter, which runs a program without a C compiler.\n\nTimed once by the wall clock, on a four-core Intel Xeon at 2.10 GHz running Ubuntu 24.04 with GCC 13.3, the first command took 45 seconds and the second 36 seconds."
  },
  {
   "id": "cu-000-setup:write-and-run-a-program-in-vs-code",
   "edition": "CU-000.2",
   "title": "write and run a program in VS Code",
   "clauses": "",
   "url": "/university/setup/#write-and-run-a-program-in-vs-code",
   "internal": 0,
   "content": "## write and run a program in VS Code\n\n[VS Code](https://code.visualstudio.com) is a free editor for Windows, macOS and Linux, and it is the editor these lessons use in their steps.\n\n1. Install VS Code and open it.\n2. Choose **File > Open Folder**, make a new folder called `cint-programs` and open it.\n3. Choose **File > New File**, name it `hello.ci` and type:\n\n   ```ci\n   \"Hello, world\\n\";\n   ```\n\n   Save it with Ctrl+S (Cmd+S on macOS).\n4. Choose **Terminal > New Terminal**. A terminal opens at the bottom of the window, already in your folder. Type:\n\n   ```text\n   cint run hello.ci\n   ```\n\n   and press Enter. The terminal prints:\n\n   ```text\n   Hello, world\n   ```\n\nIf the terminal says it cannot find `cint`, close VS Code and open it again, so that it reads the new PATH."
  },
  {
   "id": "cu-000-setup:color-for-cint-programs",
   "edition": "CU-000.2",
   "title": "color for cint programs",
   "clauses": "",
   "url": "/university/setup/#color-for-cint-programs",
   "internal": 0,
   "content": "### color for cint programs\n\nVS Code does not know cint, but cint looks enough like C that C's colors fit most of a program: comments, text in quotes, numbers and words such as `if`, `for` and `return`. Type names such as `I64` stay uncolored. To turn this on, open the Command Palette (Ctrl+Shift+P, or Cmd+Shift+P on macOS), choose **Preferences: Open User Settings (JSON)** and add this line inside the outer braces:\n\n```json\n\"files.associations\": { \"*.ci\": \"c\" }\n```"
  },
  {
   "id": "cu-000-setup:run-with-one-key",
   "edition": "CU-000.2",
   "title": "run with one key",
   "clauses": "",
   "url": "/university/setup/#run-with-one-key",
   "internal": 0,
   "content": "### run with one key\n\nYou can make Ctrl+Shift+B (Cmd+Shift+B on macOS) run whatever file is open. In your `cint-programs` folder, make a folder called `.vscode` and in it a file called `tasks.json`:\n\n```json\n{\n  \"version\": \"2.0.0\",\n  \"tasks\": [\n    {\n      \"label\": \"cint run\",\n      \"type\": \"shell\",\n      \"command\": \"cint\",\n      \"args\": [\"run\", \"${file}\"],\n      \"group\": { \"kind\": \"build\", \"isDefault\": true },\n      \"problemMatcher\": {\n        \"source\": \"cint\",\n        \"severity\": \"error\",\n        \"fileLocation\": [\"relative\", \"${fileDirname}\"],\n        \"pattern\": [\n          { \"regexp\": \"^(error|fault)\\\\[(\\\\w+)\\\\]: (.*)$\", \"code\": 2, \"message\": 3 },\n          { \"regexp\": \"^\\\\s+--> (.*):(\\\\d+):(\\\\d+)$\", \"file\": 1, \"line\": 2, \"column\": 3 }\n        ]\n      }\n    }\n  ]\n}\n```\n\nThe `problemMatcher` part reads cint's messages. When a program has an error or stops with a fault, VS Code underlines the line and lists it in the **Problems** panel. Click the entry to jump to the line."
  },
  {
   "id": "cu-000-setup:or-use-a-text-editor-and-a-terminal",
   "edition": "CU-000.2",
   "title": "or use a text editor and a terminal",
   "clauses": "",
   "url": "/university/setup/#or-use-a-text-editor-and-a-terminal",
   "internal": 0,
   "content": "## or use a text editor and a terminal\n\nIf you would rather not use VS Code, any plain text editor and a terminal will do. Programs were written this way long before editors had buttons. You type the program into a file and hand the file to the compiler, as programmers once did on teletypes, typewriters wired to a computer.\n\n1. Open a plain text editor:\n   - **Windows:** Notepad.\n   - **macOS:** TextEdit. Choose **Format > Make Plain Text** and turn off **Edit > Substitutions > Smart Quotes**. Or use `nano` in Terminal.\n   - **Linux:** your desktop's Text Editor, or `nano` in a terminal.\n2. Type the program:\n\n   ```ci\n   \"Hello, world\\n\";\n   ```\n\n3. Save it as `hello.ci` in a folder of your own. In Notepad, set **Save as type** to **All files** so the name does not become `hello.ci.txt`. Set **Encoding** to **UTF-8**.\n4. Open a terminal, go to that folder with `cd` and run:\n\n   ```text\n   cint run hello.ci\n   ```\n\nTwo editor settings cause trouble. Curly quotes, which some editors put in place of straight ones as you type, are not quotes to cint:\n\n```text\nerror[C1013]: invalid name\n  --> hello.ci:1:1\n```\n\nA file saved as \"UTF-8 with BOM\" starts with three invisible bytes that cint refuses:\n\n```text\nerror[C1002]: invalid source bytes\n  --> hello.ci:1:1\n```\n\nEither message on the first line of a file you just typed means the editor changed what you typed. Fix the setting and save the file again."
  },
  {
   "id": "cu-000-setup:what-you-have-now",
   "edition": "CU-000.2",
   "title": "what you have now",
   "clauses": "",
   "url": "/university/setup/#what-you-have-now",
   "internal": 0,
   "content": "## what you have now\n\n- `cint run FILE.ci` builds a program and runs it.\n- `cint test FILE.ci` runs the tests in a file.\n- `cint build FILE.ci` writes a program you can run without cint, into a folder called `build` next to the file.\n- `cint emit-c --root DIR --out DIR FILE.ci` writes the C that cint makes from your program.\n\nEach lesson tells you which of these it uses."
  }
 ]
}
