{
 "meta": {
  "title": "Instruction Set Reference — The Crush Language Guide",
  "description": "Generated from casm/instructions.md of The Crush Language Guide (https://docs.crushlang.org/casm/instructions.html). Edit the guide, not this file: it is regenerated on every build.",
  "frontends": [
   "crush"
  ],
  "author": "The Crush Language Guide",
  "tags": {
   "source": "casm/instructions.md",
   "guide_url": "https://docs.crushlang.org/casm/instructions.html",
   "generator": "scripts/build-notebooks.py"
  }
 },
 "cells": [
  {
   "id": "casm-instructions-md-1",
   "kind": {
    "type": "markdown"
   },
   "source": "# Instruction Set Reference\n\nEvery instruction has two spellings: the **JSON name** used in the CASM IR\n(`\"op\": \"push_int\"`) and the **CVM1 mnemonic** used in the text assembly and the\nbinary (`PUSH`). The tables below give both, the operand, and the stack effect.\nBehaviour was checked against crush-ast `v0.13.0` (`dc0d0278`, 2026-12-03); the examples at the\nend of each section are run by this guide's checker.\n\n## Reading stack effects\n\n`a b → c` means: pop `b` (the **top**), pop `a`, push `c`. The rightmost value is\nalways the top of the stack. `…` is \"whatever was below\".\n\nOperands in the text assembly follow the mnemonic: `PUSH 42`, `LOAD 3`,\n`CAP_CALL \"io.print\" 1`. In the IR they are named fields next to `op`.\n\n> **Two instruction sets.** The IR (`casm::OpCode`) is wider than the VM: it has\n> names the VM bytecode does not (`break`, `continue`, `await` with a handle,\n> `call_host`, `import_var`) and the VM bytecode has mnemonics the IR lowering never\n> emits (`ROT`, `PICK`, `CAST`, the `MATH_*` family). [The last\n> section](#what-lowers-to-cvm1) lists exactly which IR ops reach the VM.\n\n## Stack\n\n| JSON `op` | CVM1 | Operand | Stack effect | Notes |\n|---|---|---|---|---|\n| `push_int` | `PUSH` | `value` (i64) | `→ int` | |\n| `push_float` | `PUSH_F64` | `value` (f64) | `→ float` | |\n| `push_str` | `PUSH_STR` | `value` (string) | `→ str` | text form: quoted string |\n| `push_bool` | `PUSH_BOOL` | `value` (bool; `1`/`0` in text) | `→ bool` | |\n| `push_null` | `PUSH_NULL` | — | `→ null` | |\n| `pop` | `POP` | — | `a →` | |\n| `dup` | `DUP` | — | `a → a a` | |\n| `swap` | `SWAP` | — | `a b → b a` | |\n| `rot` | `ROT` | — | `a b c → b a c` | as observed on `dc0d0278`; **not** Forth's `ROT` |\n| `pick` | `PICK n` | `n` | `… → … v` | copy the item `n` below the top (`PICK 2` copies the third) |\n| `roll` | `ROLL n` | `n` | `… → … v` | *move* the item `n` below the top to the top |\n| — | `NOP` | — | — | text/binary only |\n\n```casm\n.func main\n    PUSH 1\n    PUSH 2\n    PUSH 3\n    ROLL 2          ; stack is now 2 3 1\n    CAP_CALL \"io.print\" 1\n    CAP_CALL \"io.print\" 1\n    CAP_CALL \"io.print\" 1\n    HALT\n```\n\n```text\n1\n3\n2\n```\n\n## Variables\n\n| JSON `op` | CVM1 | Operand | Stack effect | Notes |\n|---|---|---|---|---|\n| `load` | `LOAD slot` | `name` | `→ v` | push the variable |\n| `store` | `STORE slot` | `name` | `v →` | pop into the variable |\n| `export_var` | — | `name` | — | IR only; lowers to `NOP` (the value stays on the stack) |\n| `import_var` | — | `name` | — | IR only; **not lowered** |\n\nIn the IR a variable is a name; in CVM1 it is a numeric **slot** (0–65535) local to\nthe current call frame. Frames do not share slots: a callee cannot see its caller's\nvariables.\n\n## Arithmetic and comparison\n\nAll binary operators pop `b` then `a` and push `a OP b`.\n\n| JSON `op` | CVM1 | Effect | Notes |\n|---|---|---|---|\n| `add` `sub` `mul` | `ADD` `SUB` `MUL` | `a b → a∘b` | `ADD` also concatenates strings |\n| `div` | `DIV` | `a b → a/b` | integer division on two ints (`7/2 = 3`), float otherwise |\n| `mod` | `MOD` | `a b → a%b` | |\n| `neg` | `NEG` | `a → -a` | |\n| `eq` `ne` | `EQ` `NE` | `a b → bool` | |\n| `lt` `gt` `le` `ge` | `LT` `GT` `LE` `GE` | `a b → bool` | |\n| `and` `or` | `AND` `OR` | `a b → bool` | **eager** — both operands are already evaluated. The `&&` / `\\|\\|` operators of Crush compile to jumps, not to these |\n| `not` | `NOT` | `a → bool` | logical not |\n| `bit_and` `bit_or` `bit_xor` | `BITAND` `BITOR` `BITXOR` | `a b → a∘b` | |\n| `bit_not` | `BITNOT` | `a → ~a` | |\n| `shl` `shr` | `SHL` `SHR` | `a b → a<<b` / `a>>b` | |\n\n```casm\n.func main\n    PUSH 10\n    PUSH 3\n    SUB                 ; 10 - 3\n    CAP_CALL \"io.print\" 1\n    PUSH 7\n    PUSH 2\n    DIV                 ; integer division\n    CAP_CALL \"io.print\" 1\n    PUSH 12\n    PUSH 10\n    BITAND\n    CAP_CALL \"io.print\" 1\n    PUSH 1\n    PUSH 4\n    SHL\n    CAP_CALL \"io.print\" 1\n    HALT\n```\n\n```text\n7\n3\n8\n16\n```\n\n## Control flow\n\n| JSON `op` | CVM1 | Operand | Stack effect | Notes |\n|---|---|---|---|---|\n| `jmp` | `JMP label` | `target` | — | unconditional |\n| `jmp_if_not` | `JZ label` | `target` | `cond →` | jump if `cond` is **falsy** |\n| `jmp_if` | `JNZ label` | `target` | `cond →` | jump if `cond` is truthy |\n| `call` | `CALL name` | `function`, `argc` | `args… → [result]` | see below |\n| `ret` | `RET` | — | `[v] →` | return to the caller |\n| `halt` | `HALT` | — | — | stop the whole program |\n| `enter_try` | `ENTER_TRY label` | `target` | — | push an exception handler |\n| `exit_try` | `EXIT_TRY` | — | — | pop it again (normal exit of the `try` body) |\n| `throw` | `THROW` | — | `v →` | unwind to the nearest handler, which receives `v` on its stack |\n| `break` `continue` | — | — | — | in the IR enum only; the compiler lowers loops to `jmp`s and never emits these |\n\nJump operands are **instruction indices** in the IR and **byte offsets** in the\nbinary; the text assembler takes label names. A value is *falsy* if it is `false`,\n`null`, `0`, `0.0`, the empty string or an empty array; everything else (including\nthe string `\"0\"`) is truthy.\n\n**Calling convention.** The caller pushes the arguments **last first**, then\n`CALL`s. The callee's body begins with one `STORE` per parameter, in declaration\norder, which pops the first argument first. `RET` returns to the caller; a function\nthat produces a value leaves it on the stack for `RET`. Crush functions always end\nwith `PUSH_NULL` / `RET` if they have no explicit `return`.\n\n```casm\n.func main\n    PUSH 5              ; counter\n    STORE 0\nloop:\n    LOAD 0\n    JZ done             ; stop when the counter reaches 0\n    LOAD 0\n    CAP_CALL \"io.print\" 1\n    LOAD 0\n    PUSH 1\n    SUB\n    STORE 0\n    JMP loop\ndone:\n    PUSH 4\n    CALL double\n    CAP_CALL \"io.print\" 1\n    HALT\n.func double\n    STORE 0\n    LOAD 0\n    PUSH 2\n    MUL\n    RET\n```\n\n```text\n5\n4\n3\n2\n1\n8\n```\n\n**Exceptions.** `ENTER_TRY handler` records where to resume; `THROW` pops a value,\nunwinds, and jumps to `handler` with that value on top of the stack.\n\n```casm\n.func main\n    ENTER_TRY handler\n    PUSH_STR \"boom\"\n    THROW\n    EXIT_TRY            ; not reached\n    JMP end\nhandler:\n    CAP_CALL \"io.print\" 1   ; prints the thrown value\nend:\n    HALT\n```\n\n```text\nboom\n```\n\n## Collections and objects\n\n| JSON `op` | CVM1 | Operand | Stack effect | Notes |\n|---|---|---|---|---|\n| `new_array` | `NEW_ARRAY n` | `size` | `v₁…vₙ → array` | pops `n` values. **IR quirk:** lowering ignores `size` and emits `NEW_ARRAY 0` — build arrays with `new_array` + `array_push`, as the compiler does |\n| `array_push` / `arr_push` | `ARR_PUSH` | — | `array v → array` | |\n| `array_pop` / `arr_pop` | `ARR_POP` | — | `array → array v` | |\n| `index` / `arr_get` | `ARR_GET` | — | `array i → v` | also indexes objects/strings |\n| `arr_set` | `ARR_SET` | — | `array i v → array` | |\n| `len` / `arr_len` | `ARR_LEN` | — | `array → n` | works on strings too |\n| `make_range` | `MAKE_RANGE` | — | `start end → range` | `1..4` yields 1, 2, 3 |\n| `new_tuple` `new_list` `new_vector` `new_set` | `NEW_TUPLE n` etc. | `size` | `v₁…vₙ → coll` | plus `TUPLE_PUSH` `LIST_PUSH` `VECTOR_PUSH` `SET_PUSH` |\n| `new_obj` | `NEW_OBJ` | — | `→ obj` | empty object |\n| `new_struct` | `NEW_OBJ` | `name` | `→ obj` | the struct name is dropped on lowering |\n| `set_field` | `SET_FIELD \"f\"` | `name` or `field` | `obj v → obj` | |\n| `get_field` | `GET_FIELD \"f\"` | `name` or `field` | `obj → v` | |\n\n```casm\n.func main\n    PUSH 10\n    PUSH 20\n    PUSH 30\n    NEW_ARRAY 3\n    DUP\n    ARR_LEN\n    CAP_CALL \"io.print\" 1       ; 3\n    PUSH 1\n    ARR_GET\n    CAP_CALL \"io.print\" 1       ; 20\n    NEW_OBJ\n    PUSH 5\n    SET_FIELD \"x\"\n    GET_FIELD \"x\"\n    CAP_CALL \"io.print\" 1       ; 5\n    HALT\n```\n\n```text\n3\n20\n5\n```\n\n## Strings, math, types\n\nString operations pop their operands in the order shown and push the result.\n\n| JSON `op` | CVM1 | Stack effect |\n|---|---|---|\n| `str_contains` | `STR_CONTAINS` | `s pattern → bool` |\n| `str_split` | `STR_SPLIT` | `s delim → array` |\n| `str_replace` | `STR_REPLACE` | `s old new → s` |\n| `str_join` | `STR_JOIN` | `array delim → s` |\n| `str_starts_with` `str_ends_with` | `STR_STARTS_WITH` `STR_ENDS_WITH` | `s prefix → bool` |\n| `str_to_upper` `str_to_lower` `str_trim` | `STR_TO_UPPER` `STR_TO_LOWER` `STR_TRIM` | `s → s` |\n| `math_pow` | `MATH_POW` | `base exp → float` |\n| `math_sqrt` `math_abs` `math_round` `math_floor` `math_ceil` | `MATH_SQRT` … | `x → float` |\n| `type_of` | `TYPEOF` | `v → str` — `\"int\"`, `\"float\"`, `\"str\"`, `\"bool\"`, `\"null\"`, `\"array\"`, `\"map\"` (an object), `\"tuple\"`, … |\n| `cast` | `CAST \"t\"` | `v → v'` — `\"int\"`, `\"float\"`, `\"string\"` |\n| — | `VEC_ADD` `VEC_DOT` `MAT_MUL` | vector/matrix helpers, CVM1 only |\n\n```casm\n.func main\n    PUSH_STR \"aXb\"\n    PUSH_STR \"X\"\n    PUSH_STR \"-\"\n    STR_REPLACE\n    CAP_CALL \"io.print\" 1       ; a-b\n    PUSH 2\n    PUSH 10\n    MATH_POW\n    CAP_CALL \"io.print\" 1       ; 1024.0\n    PUSH_STR \"12\"\n    CAST \"int\"\n    PUSH 1\n    ADD\n    CAP_CALL \"io.print\" 1       ; 13\n    HALT\n```\n\n```text\na-b\n1024.0\n13\n```\n\n(The Crush-level equivalents of these live in the standard-library capabilities —\n`str.*`, `math.*`, `conv.*` — and compile to `CAP_CALL`s, not to these opcodes. See\nthe [standard library](https://docs.crushlang.org/crush/stdlib.html).)\n\n## Capabilities\n\n| JSON `op` | CVM1 | Operand | Stack effect |\n|---|---|---|---|\n| `cap_call` | `CAP_CALL \"name\" argc` | `name`, `argc` | `a₁…aₙ → [result]` |\n| `call_host` | — | `capsule`, `ic_id`, `method`, `argc` | IR only, **not lowered** |\n| `call_interface` | — | `handle`, `method`, `argc` | IR only, **not lowered** |\n\n`CAP_CALL` pops `argc` arguments (the first argument was pushed first) and invokes\nthe named host capability. Whether it then pushes a result depends on the\ncapability: `io.print` returns nothing, `str.len` returns a number. The compiler\nknows this and drops the `pop` it would otherwise emit after a statement-position\ncall. If the capability is not registered by the host the VM stops with `unknown\ncapability: NAME`; if it is registered but missing from the manifest, with\n`capability not declared in manifest: NAME`. See the\n[capability chapter](https://docs.crushlang.org/crush/capabilities.html).\n\n## Records and Kinds (COSM)\n\nStructs compile to **Records** of a **Kind** (crush-ast CRUSH-zorro-43). The\nprogram carries a kind table, written in text assembly as one `.cosm` line of\nJSON (`crushc --emit casm` prints a readable summary above it as `;` comments),\nand functions that need their arity for bound methods are written `.func name N`.\nFor this source:\n",
   "state": {
    "status": "done"
   },
   "meta": {},
   "outputs": []
  },
  {
   "id": "casm-instructions-1",
   "kind": {
    "type": "crush"
   },
   "source": "struct P { x: Int }\nimpl P { fn get(self) { return self.x } }\nlet p = P { x: 7 }\nprint(p.get())\nprint(p.x)\n",
   "state": {
    "status": "pending"
   },
   "meta": {
    "tags": [
     "guide",
     "runnable"
    ],
    "extra": {
     "guide": {
      "src": "casm/instructions.md:320",
      "browser": "run",
      "expect_output": "7\n7\n"
     }
    }
   },
   "outputs": []
  },
  {
   "id": "casm-instructions-md-3",
   "kind": {
    "type": "markdown"
   },
   "source": "`crushc --emit casm` writes:\n\n```casm\n; kind table (COSM): 1 Kind, 0 interfaces\n;   kind P (crush): fields [x], members [get]\n.cosm {\"kinds\":[{\"name\":\"P\",\"home_lang\":\"crush\",\"span\":{\"line\":1,\"col\":1},\"storage\":{\"sealed\":{\"fields\":[{\"name\":\"x\",\"type\":\"Int\"}]}},\"semantics\":\"reference\",\"resolution\":\"none\",\"receiver\":\"explicit_ref\",\"construct\":\"literal\",\"members\":[{\"name\":\"get\",\"span\":{\"line\":2,\"col\":10},\"kind\":\"method\",\"fn\":\"P::get\"}],\"equality\":\"structural\"}],\"interfaces\":[]}\n.func main 0\n    NEW_RECORD \"P\"\n    PUSH 7\n    SET_FIELD \"x\"\n    STORE 0\n    LOAD 0\n    CALL_MEMBER \"get\" 0\n    CAP_CALL \"io.print\" 1\n    LOAD 0\n    GET_FIELD \"x\"\n    CAP_CALL \"io.print\" 1\n    PUSH_NULL\n    RET\n.func P::get 1\n    STORE 0\n    LOAD 0\n    GET_FIELD \"x\"\n    RET\n```\n\n```text\n7\n7\n```\n\nThe member opcodes are `GET_MEMBER`, `SET_MEMBER`, `HAS_MEMBER`, `DEL_MEMBER`,\n`CALL_MEMBER name argc`, `CONSTRUCT kind argc`, `GET_SLOT`, `SET_SLOT`, `IS_KIND`\n(what a struct pattern tests), `COPY` (value semantics) and `NEW_RECORD`.\n`GET_FIELD`/`SET_FIELD` on a Record are member accesses. Only the CVM1 VMs run\nthem; FastVM, the JIT and the AOT backends refuse a program that needs them (see\n[Engines, AOT and Walkers](https://docs.crushlang.org/crush/engines.html)).\n\n## Polyglot, concurrency, AI and DOM\n\n| JSON `op` | CVM1 | Notes |\n|---|---|---|\n| `exec_lang` | `EXEC_LANG \"json\"` | run a `@python { }` / `@javascript { }` / `@bash { }` block; the operand is a JSON string with `lang`, `code`, `var_count` and the marshalling lists. Needs the matching `polyglot.<lang>` capability — see [Polyglot](https://docs.crushlang.org/crush/polyglot.html) |\n| `spawn` `yield` `await` | `SPAWN n` `YIELD` `AWAIT` | real green tasks on the CVM1 VMs, see [Concurrency](https://docs.crushlang.org/crush/concurrency.html) |\n| `ai_query` … (10 names) | `AI_QUERY` … (10 opcodes) | gated through `ai_native.<kind>` capabilities; `ai_capability_discovery`, `ai_adaptation_request`, `ai_semantic_switch` are refused. See [AI-Native CAST](https://docs.crushlang.org/cast/ai-native.html#what-actually-runs) |\n| `dom_query` `dom_mutate` `dom_event_listener` | `DOM_QUERY` … | **stubs**: lowered to `NOP`; the `dom_native.*` gates exist only for hand-written CVM1 |\n\n## What lowers to CVM1\n\n`crush_lang_sdk::compile::casm_to_vm` is the bridge from the JSON IR to a runnable\nprogram. It handles exactly these IR operations:\n\n| | |\n|---|---|\n| **Lowered** | every IR operation except the rows below: the stack, arithmetic, comparison, logic, bit (`bit_*`, `shl`, `shr`), `math_*`, `type_of`, `cast`, string, array/collection, object and COSM member ops, calls, jumps, `try`/`throw`, `exec_lang`, `spawn`/`yield`/`await`, and ten `ai_*` ops |\n| **Lowered with a loss** | `new_array` (size ignored: always empty), `new_struct` (→ `NEW_OBJ`, name dropped), `export_var` and the `dom_*` ops (→ `NOP`) |\n| **Rejected** | `break`, `continue` (no loop target in the instruction), `import_var`, `call_host`, `call_interface`, and the declined `ai_capability_discovery`, `ai_adaptation_request`, `ai_semantic_switch`: they fail with `Unsupported CVM1 opcode: NAME at FUNCTION:INDEX` |\n\n(crush-ast keeps this classification exhaustive in its\n`crush-lang-sdk/tests/casm_lowering_completeness.rs`; the spot checks below were\nrun against `dc0d0278`.) A bit shift lowers and runs:\n\n```json\n{\n  \"version\": \"1.0\",\n  \"functions\": { \"main\": { \"body\": [\n    {\"op\": \"push_int\", \"value\": 1},\n    {\"op\": \"push_int\", \"value\": 3},\n    {\"op\": \"shl\"},\n    {\"op\": \"cap_call\", \"name\": \"io.print\", \"argc\": 1},\n    {\"op\": \"halt\"}\n  ] } },\n  \"manifest\": { \"permissions\": [\"io.print\"] }\n}\n```\n\n```text\n8\n```\n\nwhile `break` is refused:\n\n```json\n{\n  \"version\": \"1.0\",\n  \"functions\": { \"main\": { \"body\": [\n    {\"op\": \"push_int\", \"value\": 1},\n    {\"op\": \"break\"},\n    {\"op\": \"halt\"}\n  ] } },\n  \"manifest\": { \"permissions\": [\"io.print\"] }\n}\n```\n",
   "state": {
    "status": "done"
   },
   "meta": {},
   "outputs": []
  }
 ]
}
