Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

CAST — the Crush AST

CAST is the JSON abstract syntax tree that sits between source languages and CASM. The Crush parser produces it, the polyglot walkers produce it from other languages, and an AI agent can write it directly (see AI-Native CAST). The compiler (crush_frontend) turns it into CASM.

 Crush source ──parse──┐
 Python/JS/… ──walker──┼──▶ CAST (JSON) ──compile──▶ CASM IR ──▶ CVM1 ──▶ VM
 an agent's JSON ──────┘

This page is the schema reference. It is derived from crates/crush-cast/src/lib.rs in crush-ast (verified against dc0d0278, 2026-11-16); the examples are accepted by crush_cast::validate_json, compiled and run by this guide’s checker.

Document structure

{
  "cast_version": "0.1.0",
  "entry": "main",
  "lang": null,
  "functions": {
    "main": { "params": [], "body": [ /* statements */ ], "meta": {} }
  }
}
FieldTypeRequiredDescription
cast_versionstringyesformat version; see Serialization
entrystringyesname of the function to run first
langstring or nullyes (may be null)language that produced the tree ("crush", "python", …)
functionsobjectyesfunction name → function
ai_metaobjectnoprogram-level AI metadata — see AI-Native CAST
manifestobjectnothe @module navigation manifest (purpose, exports, invariants) used by crush-index
exhaustive_sites, wip, temporaries, decisionsnocompiler-populated tooling nodes (@wip, @temporary, @decision blocks)

A function is:

FieldTypeRequiredDescription
paramsarray of [name, type] pairsyes[["n", "Int"]]; use "Any" for untyped
bodyarray of statementsyes
metaobjectyesfree-form ({} is fine). Forgetting it is the most common validation error
is_asyncboolnotooling hint
annotationsobjectno@errors/@reads/@writes/@covers annotations

There is no top-level imports or structs table: imports and struct definitions are statements (Import, StructDef).

A complete program

{
  "cast_version": "0.1.0",
  "entry": "main",
  "lang": null,
  "functions": {
    "square": {
      "params": [["n", "Int"]],
      "body": [
        { "type": "Return",
          "value": { "type": "BinaryOp", "operator": "*",
                     "left":  { "type": "Var", "name": "n" },
                     "right": { "type": "Var", "name": "n" } } }
      ],
      "meta": {}
    },
    "main": {
      "params": [],
      "body": [
        { "type": "VarDecl", "name": "total", "value": { "type": "IntLiteral", "value": 0 }, "type_hint": "Int" },
        { "type": "For", "variable": "i",
          "iterable": { "type": "ArrayLiteral", "elements": [
              { "type": "IntLiteral", "value": 1 },
              { "type": "IntLiteral", "value": 2 },
              { "type": "IntLiteral", "value": 3 } ] },
          "body": [
            { "type": "Assign", "target": "total",
              "value": { "type": "BinaryOp", "operator": "+",
                         "left":  { "type": "Var", "name": "total" },
                         "right": { "type": "Call", "function": "square",
                                    "args": [ { "type": "Var", "name": "i" } ] } } }
          ] },
        { "type": "If",
          "condition": { "type": "BinaryOp", "operator": ">",
                         "left": { "type": "Var", "name": "total" },
                         "right": { "type": "IntLiteral", "value": 10 } },
          "then_body": [
            { "type": "ExprStmt", "expr": { "type": "CapabilityCall", "name": "io.print",
                "args": [ { "type": "StringLiteral", "value": "sum of squares: " },
                          { "type": "Var", "name": "total" } ], "meta": {} } }
          ],
          "else_body": null }
      ],
      "meta": {}
    }
  }
}
sum of squares: 14

Every node is an object with a "type" tag. meta is optional on almost every node (it defaults to {}), with one exception: CapabilityCall requires its meta. The Crush parser fills meta with line and col.

Statements

typeFieldsNotes
VarDeclname, value, type_hintdeclare a variable (type_hint defaults to "Any")
Assigntarget (a name), value
SetFieldtarget (expression), field, valuep.x = 3
Exportname, valuepublish a variable to the host / polyglot caller
ExprStmtexprexpression evaluated for effect; its value is dropped
Ifcondition, then_body, else_bodyelse_body is null or a statement list
Whilecondition, body
Forvariable, iterable, body
Returnvalue (nullable)
Break, Continue—
TryCatchbody, error_var, handler
Throwvalue
FunctionDefname, params, bodynested function definition
StructDefname, fields, kindfields is [[name, type], …]; kind is the @kind(…) annotation as written ({"args": [{"key", "value"}]}, values Name / Apply / List), or absent
ImplBlocktype_name, trait_name (optional), methodsimpl P { … } / impl T for P { … }; each method is {name, params, body}, self is an ordinary first parameter
TraitDefname, methodsa method without body is a required signature
LangBlocklang, code, variables, outputs, imports, depsa polyglot @lang { } block; variables are marshalled in, outputs (the -> names, mirrored in meta.polyglot_outputs) are marshalled out. After prepare_polyglot_blocks, code carries the generated marshalling prologue/epilogue
Importimportan ImportStatement — parsed, but not executed: see below
DomMutate, DomEventListenerDOM nodes; compile to NOP today
AIai_type, …AI statements — see AI-Native CAST

Import, in particular, is accepted by the schema in six flavours (CrushModule, PolyglotModule, MCPImport, Capability, External, SecureEnv), but at run time an import lowers to an unregistered module.load capability and fails — Crush imports are not implemented yet (CRUSH-110).

Expressions

typeFields
IntLiteral, FloatLiteral, StringLiteral, BoolLiteralvalue
NullLiteral—
Varname
BinaryOpoperator, left, right — operators as the language spells them: + - * / % == != < > <= >= && ||
UnaryOpoperator (-, !), operand
Callfunction (a name), args — a call to a user function
CapabilityCallname ("io.print"), args, meta (required)
ArrayLiteral, TupleLiteral, ListLiteral, VectorLiteral, SetLiteralelements
ObjectLiteralproperties: [[key, expression], …]
Indextarget, index
GetFieldtarget, field
NewStructname
Rangestart, end
Matchexpression, arms ({pattern, body} pairs)
Pipelinesegments — a |> b |> c
Spawn, Await, Yieldgreen tasks: Spawn is {function, args} (see Concurrency)
Lambdaparams ([name, type] pairs), body — what |x| x + k parses to; captures are worked out by the compiler, not stored in CAST (see Closures)
VectorMathoperator, args
DomQueryquery_type, selector
AIai_type, … — see AI-Native CAST

Note the naming: it is GetField (not FieldAccess), ArrayLiteral (there is no MapLiteral — use ObjectLiteral) and Var (not Identifier).

Patterns (for Match)

typeFields
Literalvalue (an expression)
Identifiername (binds the value)
Structname, fields: [[field, pattern], …]
Wildcard—
{ "type": "Match",
  "expression": { "type": "Var", "name": "n" },
  "arms": [
    { "pattern": { "type": "Literal", "value": { "type": "IntLiteral", "value": 6 } },
      "body": [ { "type": "ExprStmt", "expr": { "type": "StringLiteral", "value": "six" } } ] },
    { "pattern": { "type": "Wildcard" },
      "body": [ { "type": "ExprStmt", "expr": { "type": "StringLiteral", "value": "other" } } ] }
  ] }

Types

Type positions (type_hint, parameter and field types) hold a CastType. It is serialized the usual serde way: a bare string for the simple types, {"Variant": payload} for the others.

JSONMeaning
"Int", "Float", "F32", "BigInt", "Complex", "String", "Bool", "Null"scalars
"Any"dynamic (the default)
{"Array": "Int"}, {"List": …}, {"Vector": …}, {"Set": …}, {"Map": …}, {"Tensor": …}homogeneous collections of the inner type
{"Tuple": ["Int", "String"]}fixed-length sequence
{"Struct": "Point"}, {"TypeRef": "Point"}named types
{"Lambda": {"params": […], "returns": …}}function types

Types are hints: the compiler records them but the VM is dynamically typed.

{
  "cast_version": "0.1.0", "entry": "main", "lang": null,
  "functions": { "main": { "params": [], "meta": {}, "body": [
    { "type": "VarDecl", "name": "xs", "type_hint": { "Array": "Int" },
      "value": { "type": "ArrayLiteral", "elements": [ { "type": "IntLiteral", "value": 7 } ] } },
    { "type": "ExprStmt", "expr": { "type": "CapabilityCall", "name": "io.print", "meta": {},
      "args": [ { "type": "Index", "target": { "type": "Var", "name": "xs" },
                  "index": { "type": "IntLiteral", "value": 0 } } ] } }
  ] } }
}
7

Metadata

meta on a node is an open JSON object. The Crush parser writes line and col (1-based); walkers add their own keys. crush_frontend copies line/col onto the CASM instructions it emits, which is how a runtime error gets pointed at a source line. Nothing in meta changes what a program does, with one exception the compiler reads: LangBlock.meta.polyglot_output (the variable to marshal back).

Validation

crush_cast::validate_json(&str) checks a document against the schema and returns errors with a JSON path and a hint for the mistakes agents make most often. Only the first error is reported, because serde stops at the first one.

{ "cast_version": "0.1.0", "entry": "main", "functions": { "main": {
    "params": [], "meta": {},
    "body": [ { "type": "Print", "value": { "type": "StringLiteral", "value": "hi" } } ] } } }

The error for that document is functions.main.body[0].type: unknown variant Print, expected one of VarDecl, Assign, …, with the hint “Statement type ‘Print’ doesn’t exist. Use ExprStmt with CapabilityCall("print") instead”. Other built-in hints cover Identifier/Literal expressions, a missing Function.meta, prompt instead of query in an AI query, and an object where a DelegationStrategy string belongs.

Validation is structural. It does not check that a called function exists or that a capability name is real; the compiler and the VM do.

Serialization

crush_cast::Program can be written and read as JSON (the canonical form) or as CBOR:

ExtensionCodec
.cast.json, anything elseJSON (pretty-printed)
.castb, .cborCBOR (cbor4ii), no header or magic

Program::deserialize / load check cast_version and refuse a different major than CAST_VERSION ("0.1.0"): version mismatch at cast boundary: expected 0.1.0, found …. Every producer, the Crush front end included, writes "0.1.0" (from v0.3.9 through v0.9.0 the front end stamped "1.0.0" and the loader rejected its own output). A tree with major version 1 is refused:

{ "cast_version": "1.0.0", "entry": "main", "lang": null,
  "functions": { "main": { "params": [], "body": [], "meta": {} } } }

From CAST to CASM

crush_frontend::compile_cast(&program) (or compile_cast_owned) walks the tree and emits CASM IR. The control-flow statements lower to jumps:

  • If → condition, jmp_if_not over the then-branch, jmp over the else-branch.
  • While → test at the top, jmp_if_not to the exit, jmp back.
  • For over an array → an index loop (len/index), as shown in CASM Examples.
  • TryCatch → enter_try, the body, exit_try, jmp past the handler; the handler starts by storing the thrown value into error_var.
  • CapabilityCall → arguments in order, then cap_call name argc (a pop follows when the call is a statement and the capability returns a value).
  • Call → arguments last first, then call function argc.