@typesol/cli 0.50.0 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/README.md +12 -10
  3. package/SECURITY.md +5 -3
  4. package/dist/cli.js +36 -5
  5. package/dist/compiler/analyze.d.ts +8 -1
  6. package/dist/compiler/analyze.js +227 -19
  7. package/dist/compiler/diagnostics.d.ts +4 -0
  8. package/dist/compiler/diagnostics.js +5 -1
  9. package/dist/compiler/emit/base.d.ts +31 -1
  10. package/dist/compiler/emit/base.js +37 -1
  11. package/dist/compiler/emit/calls.js +27 -6
  12. package/dist/compiler/emit/cpi-core.d.ts +3 -0
  13. package/dist/compiler/emit/cpi-core.js +8 -2
  14. package/dist/compiler/emit/cpi.js +4 -2
  15. package/dist/compiler/emit/create.js +9 -9
  16. package/dist/compiler/emit/expressions.d.ts +8 -1
  17. package/dist/compiler/emit/expressions.js +65 -0
  18. package/dist/compiler/emit/function.d.ts +2 -0
  19. package/dist/compiler/emit/function.js +59 -7
  20. package/dist/compiler/emit/outline.d.ts +35 -0
  21. package/dist/compiler/emit/outline.js +547 -0
  22. package/dist/compiler/emit/program.js +11 -2
  23. package/dist/compiler/emit/shared.d.ts +57 -2
  24. package/dist/compiler/emit/shared.js +18 -3
  25. package/dist/compiler/emit/statements.d.ts +28 -1
  26. package/dist/compiler/emit/statements.js +279 -24
  27. package/dist/compiler/emit/storage.d.ts +16 -0
  28. package/dist/compiler/emit/storage.js +122 -3
  29. package/dist/compiler/hints.d.ts +1 -1
  30. package/dist/compiler/hints.js +9 -1
  31. package/dist/compiler/idl.js +1 -1
  32. package/dist/compiler/index.d.ts +15 -1
  33. package/dist/compiler/index.js +47 -10
  34. package/dist/compiler/model.d.ts +13 -1
  35. package/dist/compiler/stack.d.ts +71 -0
  36. package/dist/compiler/stack.js +309 -0
  37. package/dist/compiler/toolchain.d.ts +87 -5
  38. package/dist/compiler/toolchain.js +384 -19
  39. package/dist/workspace.d.ts +1 -0
  40. package/dist/workspace.js +1 -1
  41. package/docker/deps/0.51.0.lock.json +1206 -0
  42. package/docs/architecture.md +1 -1
  43. package/docs/audit.md +13 -11
  44. package/docs/case-study-escrow.md +1 -1
  45. package/docs/cli.md +2 -2
  46. package/docs/glossary.md +2 -1
  47. package/docs/language-basics.md +25 -1
  48. package/docs/language-pdas.md +6 -2
  49. package/docs/language-statements.md +101 -11
  50. package/docs/language-types.md +80 -5
  51. package/docs/runtime.md +1 -1
  52. package/docs/security-model.md +5 -3
  53. package/docs/stability.md +5 -1
  54. package/docs/troubleshooting.md +45 -1
  55. package/llms-full.txt +271 -27
  56. package/package.json +1 -1
  57. package/releases/0.50.0.json +874 -0
  58. package/runtime/typesol_rt.h +125 -51
@@ -109,7 +109,7 @@ representation in between. We reviewed this on 2026-10-30 and kept it that way f
109
109
  named in the source, see `alias.ts`), a second backend (SBF without clang), and optimizations clang cannot see
110
110
  because they depend on account semantics (dropping a repeated check, packing a `@layout borsh` account only where
111
111
  it changed).
112
- - **What it would cost now:** rewriting most of the compiler's 21,000 lines, and losing the property every release
112
+ - **What it would cost now:** rewriting most of the compiler's 23,000 lines, and losing the property every release
113
113
  relies on: programs that do not use a change compile to the same binaries. Audit scope and differential results
114
114
  would start over.
115
115
  - **What we have instead:** the layers above, each owning one concern; `Ref` / `Value` as the typed place and value
package/docs/audit.md CHANGED
@@ -7,21 +7,21 @@ with TypeSOL are out of scope; their authors audit them.
7
7
 
8
8
  ## Scope
9
9
 
10
- In order of priority. Line counts at 0.50.0 (November 2026).
10
+ In order of priority. Line counts at 0.51.0 (November 2026).
11
11
 
12
12
  | Priority | Component | Files | Lines | Why |
13
13
  | --- | --- | --- | ---: | --- |
14
- | 1 | C runtime | `runtime/typesol_rt.h` | 3,399 | In every program: input parsing, account checks, checked arithmetic, PDAs, system and token CPIs, account creation, resizing and closing, oracles, signature checks, the heap |
14
+ | 1 | C runtime | `runtime/typesol_rt.h` | 3,473 | In every program: input parsing, account checks, checked arithmetic, PDAs, system and token CPIs, account creation, resizing and closing, oracles, signature checks, the heap |
15
15
  | 1 | Compiler builtins | `runtime/typesol_builtins.c` | 529 | Compiled and linked with every program (0.45.0): the functions clang calls for 128-bit multiplication, division and shifts and signed 64-bit division (`__multi3`, `__udivti3`, `__divti3`, `__divdi3`, …), in place of platform-tools' compiler-builtins |
16
- | 1 | Instruction prologue and constraints | `src/compiler/emit/function.ts` | 890 | Which checks each account parameter gets, and their order |
17
- | 1 | Account data, Vecs and assignment | `src/compiler/emit/alias.ts`, `storage.ts`, `statements.ts`, `base.ts` | 4,093 | Reads and writes of account data, growable Vec layout and resizing, references and aliasing, closure and helper expansion |
18
- | 1 | Calls and CPIs | `src/compiler/emit/calls.ts`, `cpi-core.ts`, `cpi.ts`, `create.ts`, `token.ts` | 5,839 | Built-ins, remaining accounts, `invoke` / `invokeInstruction` and their account flags, signer seeds, token CPIs, account creation |
16
+ | 1 | Instruction prologue and constraints | `src/compiler/emit/function.ts` | 948 | Which checks each account parameter gets, and their order |
17
+ | 1 | Account data, Vecs and assignment | `src/compiler/emit/alias.ts`, `storage.ts`, `statements.ts`, `base.ts` | 4,494 | Reads and writes of account data, growable Vec layout and resizing, references and aliasing, closure and helper expansion |
18
+ | 1 | Calls and CPIs | `src/compiler/emit/calls.ts`, `cpi-core.ts`, `cpi.ts`, `create.ts`, `token.ts` | 5,884 | Built-ins, remaining accounts, `invoke` / `invokeInstruction` and their account flags, signer seeds, token CPIs, account creation |
19
19
  | 1 | Raw views and the red-black tree | `src/compiler/emit/views.ts`, `rbtree.ts` | 655 | Accounts read without a discriminator at run-time offsets (`loadRaw`, `loadRawAt`, `rawArrayAt`, `BigVec`), their bounds, and the red-black tree's node indexes (`rbTreeAt`) |
20
20
  | 1 | Metaplex CPIs | `src/compiler/emit/metaplex.ts` | 1,465 | Token Metadata, Core and Bubblegum instruction layouts and their account lists |
21
- | 1 | Expressions | `src/compiler/emit/expressions.ts`, `shared.ts`, `borsh.ts` | 2,205 | Checked arithmetic and casts, Borsh encoding of arguments and `@layout borsh` accounts |
22
- | 2 | Front end | `src/compiler/analyze.ts`, `model.ts` | 3,553 | What the language accepts; constraints and account types as parsed from the source |
21
+ | 1 | Expressions | `src/compiler/emit/expressions.ts`, `shared.ts`, `borsh.ts` | 2,339 | Checked arithmetic and casts, Borsh encoding of arguments and `@layout borsh` accounts |
22
+ | 2 | Front end | `src/compiler/analyze.ts`, `model.ts` | 3,785 | What the language accepts; constraints and account types as parsed from the source |
23
23
  | 2 | Interface | `src/compiler/idl.ts`, `src/tools/clientgen.ts` | 2,460 | The IDL and the generated client must describe the program exactly (a mismatch can make clients sign the wrong thing) |
24
- | 3 | Build and tooling | `src/compiler/toolchain.ts`, `src/cli.ts`, `src/workspace.ts`, `src/tools/` | | Build flags, deploy and verification commands |
24
+ | 3 | Build and tooling | `src/compiler/toolchain.ts`, `src/compiler/stack.ts`, `src/cli.ts`, `src/workspace.ts`, `src/tools/` | | Build flags, the stack limits and the layout of a program that does not fit them, deploy and verification commands |
25
25
 
26
26
  The language surface is `lib/typesol.d.ts` (2,693 lines): every type and built-in a program can use, with its
27
27
  documented behavior. [docs/language.md](language.md) is the reference; [docs/architecture.md](architecture.md) maps
@@ -66,12 +66,14 @@ CHANGELOG.
66
66
 
67
67
  ### Not reviewed: 0.45.0 and later
68
68
 
69
- 0.45.0 to 0.50.0 have had no security review. They add, among others,
69
+ 0.45.0 to 0.51.0 have had no security review. They add, among others,
70
70
  `runtime/typesol_builtins.c` (the compiler builtins as TypeSOL's own C, 0.45.0), `transferCheckedWithHook`,
71
71
  `EVENT_AUTHORITY_CHECK` and the reads of processed sibling instructions (0.48.0), `zeroData`, `log64`,
72
72
  `PANIC_STYLE = "solana-1.18"`, `executable` on remaining accounts and lamport writes on remaining accounts under
73
- `NATIVE_ACCOUNT_WRITES` (0.49.0), and `copyData`, `getReturnData()`, `PANIC_STYLE = "pinocchio"` and whole values
74
- copied and zeroed by the memory syscalls (0.50.0). An external review should include them
73
+ `NATIVE_ACCOUNT_WRITES` (0.49.0), `copyData`, `getReturnData()`, `PANIC_STYLE = "pinocchio"` and whole values
74
+ copied and zeroed by the memory syscalls (0.50.0), and the base58 text of keys from a table, derivations without
75
+ the run-time seed-limit check, object-type structs, `extends`, struct spreads, labels, logical assignment and the
76
+ stack layout the build chooses for a program that does not fit (0.51.0). An external review should include them
75
77
  with the areas the reviews below left out.
76
78
 
77
79
  ### 0.44.0 (2026-11-11)
@@ -191,7 +191,7 @@ token account. A client that matches on this code needs to accept either.
191
191
  ## Cost
192
192
 
193
193
  Mean compute units per instruction in LiteSVM (21 make_offer, 10 take_offer and 10 refund_offer calls), and the
194
- program size, from typesol-lang/benchmarks (`results.json`, `official`: measured with TypeSOL 0.48.0 and Anchor 1.0.2
194
+ program size, from typesol-lang/benchmarks (`results.json`, `official`: measured with TypeSOL 0.48.0 and anchor-lang 1.2.1
195
195
  on 2026-11-14). Lower is better.
196
196
 
197
197
  | | TypeSOL | Anchor | Native Rust | Pinocchio |
package/docs/cli.md CHANGED
@@ -9,8 +9,8 @@ error. Exit codes: **0** success, **1** failure (compile errors, failed deploy,
9
9
  | `typesol init [<dir>] [--name <program>] [--template counter\|vault\|escrow] [--no-agent-files]` | Create a project ([below](#typesol-init)). |
10
10
  | `typesol new <program> [--template counter\|vault\|escrow]` | In a project: add a program, `programs/<program>.ts` and `tests/<program>.test.ts` from the template, and its entry in `typesol.json`. Refuses to overwrite files or reuse a name, and to write through a symbolic link inside the project (a linked `programs/` or `tests/`, or a link where a new file goes). |
11
11
  | `typesol doctor [--url <rpc>] [--config <cli config>]` | Check what building, testing and deploying need: Node.js, the platform-tools (and a `toolchain` row: the tested ones, or untested with both versions), the Solana CLI, Docker (optional: only `--docker` builds need it; it says when they run emulated), its keypair, the RPC (`--url`, a cluster moniker, or the CLI config) and the keypair's balance there, and the project. Each problem is printed with the command that fixes it. The last line says what is ready (building and testing, or also deploying) and what the warnings concern. Exit code 1 when building is impossible (Node.js or the platform-tools missing); deploy pieces are warnings. |
12
- | `typesol build [<program>…] [--sbpf v0\|v1\|v2] [--profile] [--toolchain-strict] [--docker [--typesol-version <v>] [--release-record <file>]] [--quiet]` | In a project: build every program (or those named) into `<out>/<name>/`: `<name>.so`, `<name>.json` (Anchor IDL), `<name>.client.ts` (TypeScript client, see [client.md](client.md)), `<name>.c`, `<name>.build.json` (the TypeSOL, TypeScript, clang and platform-tools versions, the host, the SBPF version, each source's sha256 and the binary's). Each source's sha256 is that of the bytes the compiler read, and the build fails without a manifest when a source or the runtime changes while it runs (an editor saving a file mid-build), so a manifest never pairs a binary with sources that did not make it. With platform-tools other than the tested ones it warns once; `--toolchain-strict` (or `TYPESOL_TOOLCHAIN=strict`) refuses them. The first build creates `<out>/deploy/<name>-keypair.json` and records the address in `typesol.json`; later builds refuse a different keypair. First builds may run at once (several programs, or several processes): the keypair is created exclusively (a process that loses the race uses the winner's key) and `typesol.json` is updated one process at a time and replaced whole, so each address is kept. Without the keypair (a fresh clone, CI) it builds at the recorded address and says so; only `deploy` needs the keypair. `--docker` builds in the pinned container instead ([below](#build---docker-and-verify---docker)). |
13
- | `typesol build <file.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile] [--toolchain-strict] [--docker …] [--quiet]` | Outside a project (or a file that is not one of its programs): build that file. Its keypair is `--program-id`, which must exist, or `<out>/<name>-keypair.json`, created on the first build. A project program's `.ts` builds as that program. |
12
+ | `typesol build [<program>…] [--sbpf v0\|v1\|v2] [--profile] [--stack-auto on\|off] [--toolchain-strict] [--docker [--typesol-version <v>] [--release-record <file>]] [--quiet]` | In a project: build every program (or those named) into `<out>/<name>/`: `<name>.so`, `<name>.json` (Anchor IDL), `<name>.client.ts` (TypeScript client, see [client.md](client.md)), `<name>.c`, `<name>.build.json` (the TypeSOL, TypeScript, clang and platform-tools versions, the host, the SBPF version, each source's sha256 and the binary's). Each source's sha256 is that of the bytes the compiler read, and the build fails without a manifest when a source or the runtime changes while it runs (an editor saving a file mid-build), so a manifest never pairs a binary with sources that did not make it. A program that does not fit the stack is laid out another way when it can ([Memory](language-basics.md#memory-stack-and-heap)): each step is printed as a `note:` and recorded in `<name>.build.json` under `stack` (`actions`, in order: `scope`, `noinline` or `heap`, with what each was for, and `frames`, the frames of the functions that did not fit before and after); a program that fits has no `stack` field. `--stack-auto off` makes such a build fail instead, as `const STACK_AUTO = false` in the program does (with `--docker`, write the constant). With platform-tools other than the tested ones it warns once; `--toolchain-strict` (or `TYPESOL_TOOLCHAIN=strict`) refuses them. The first build creates `<out>/deploy/<name>-keypair.json` and records the address in `typesol.json`; later builds refuse a different keypair. First builds may run at once (several programs, or several processes): the keypair is created exclusively (a process that loses the race uses the winner's key) and `typesol.json` is updated one process at a time and replaced whole, so each address is kept. Without the keypair (a fresh clone, CI) it builds at the recorded address and says so; only `deploy` needs the keypair. `--docker` builds in the pinned container instead ([below](#build---docker-and-verify---docker)). |
13
+ | `typesol build <file.ts> [--out <dir>] [--program-id <keypair.json>] [--sbpf …] [--profile] [--stack-auto on\|off] [--toolchain-strict] [--docker …] [--quiet]` | Outside a project (or a file that is not one of its programs): build that file. Its keypair is `--program-id`, which must exist, or `<out>/<name>-keypair.json`, created on the first build. A project program's `.ts` builds as that program. |
14
14
  | `typesol check [<program>… \| <file.ts>] [--json] [--stdin \| --files]` | Type-check and validate without building. In a project, no argument checks every program (or those named) and exits 1 if any has errors. `--json` prints `{ ok, diagnostics: [{ file, line, column, message }] }`, always (a missing file or unreadable `--files` input is a diagnostic too, exit 1 or 2); `--stdin` checks the text given on stdin as that file (its imports come from disk); `--files` reads `{ "files": { "<absolute path>": "<text>", … } }` from stdin and checks with those texts instead of the disk (an editor's unsaved buffers). |
15
15
  | `typesol clone [<address>…] [--url <rpc>] [--config <cli config>] [--out <dir>]` | Copy cluster accounts and programs for the tests (Anchor's `[test.validator.clone]`): each account to `<address>.json` (lamports, owner, data), each program to `<address>.so` (its ELF, from the ProgramData account for upgradeable programs), in `tests/accounts` (`"accounts"` in `typesol.json`) or `--out`. Without addresses it clones the project's `"clone"` list. `testProgram` loads that directory into its LiteSVM; commit it so the tests run offline. |
16
16
  | `typesol emit-c <file.ts> [--out <file.c>] [--profile]` | Print or write the generated C. |
package/docs/glossary.md CHANGED
@@ -57,7 +57,8 @@ bytes. See [seeds](language-pdas.md#seeds).
57
57
  ## Bump
58
58
 
59
59
  The one byte added to a PDA's seeds so that the derived address has no private key. The canonical bump is the
60
- highest that works; it is found by trying 255, 254, … and is usually stored in the account. See [PDAs](language-pdas.md).
60
+ highest that works; it is found by trying 255, 254, … down to 1, as Solana's `find_program_address` does (bump 0 is
61
+ never tried), and is usually stored in the account. See [PDAs](language-pdas.md).
61
62
 
62
63
  ## Signer
63
64
 
@@ -356,10 +356,34 @@ From the source alone, a build writes:
356
356
  ## Memory: stack and heap
357
357
 
358
358
  A program runs with a 4 KiB stack frame per function and a heap of 32 KiB. Locals live on the stack: a list local
359
- holds at most 2 KiB, and a frame that overflows is a compile error that names its biggest locals. Strings built at run
359
+ holds at most 2 KiB, and a frame that overflows is a compile error that names its biggest locals. Under SBPF v1 and v2
360
+ (`--sbpf v1` / `v2`) each function's frame is sized to fit, so the 4 KiB limit is lifted, but one frame holds at most
361
+ 32,767 bytes and all the frames of a call path share 256 KiB; the build refuses a program past either
362
+ ([troubleshooting](troubleshooting.md#-needs-n-bytes-of-stack-sbpf-v1-allows-one-function-at-most-32767)). Strings built at run
360
363
  time and a few other values live on the heap ([heap values](language-types.md#heap-values)), which is never freed
361
364
  during an instruction.
362
365
 
366
+ A program that does not fit the stack as written is laid out another way by the build before it gives up. It does
367
+ nothing to a program that fits, which builds to the same bytes as before. In order, measuring with clang after each
368
+ step, until the program fits:
369
+
370
+ 1. each statement of the function that does not fit, and of the helpers inlined into it, gets a C block of its own, so
371
+ clang can give the temporaries of different statements one slot (a struct literal's, a helper result's); nothing
372
+ else changes;
373
+ 2. helpers inlined into it are kept out of line, as if each were [`@noinline`](language-statements.md#inline-and-noinline),
374
+ largest frame first (about 10 compute units per call), except a helper that takes a function or is marked
375
+ `/** @inline */`; nothing else changes;
376
+ 3. in an instruction, its largest list and struct locals and the struct results of helpers it holds are kept on the
377
+ heap, as if each were [`@heap`](language-types.md#heap-values) (about 17 compute units each, and their bytes of
378
+ heap), as long as the instruction's heap locals together fit in the heap; never a local marked `/** @stack */`.
379
+
380
+ Each step is printed as a note (`note: instruction f did not fit the stack (4864 bytes; SBPF v0 allows 4096); now 64
381
+ bytes`, `note: helper settle() kept out of line, for instruction trade …`) and recorded in `<name>.build.json` as
382
+ `stack.actions` ([cli.md](cli.md)). The steps depend only on the sources and clang's measurements, so a
383
+ rebuild (`typesol verify`, `--docker`) takes the same ones and gives the same bytes. When none of them is enough, the
384
+ build fails with the error it would have given, and a line saying what it tried. `const STACK_AUTO = false` in the
385
+ program (or `typesol build --stack-auto off` for one build) turns this off: the program then fails to build instead.
386
+
363
387
  `const HEAP_SIZE_KIB = 64n` (32 to 256) lets the program use a bigger heap; the client must then add a ComputeBudget
364
388
  `requestHeapFrame` instruction with that size to the transaction.
365
389
 
@@ -56,7 +56,10 @@ A seed list is an array literal written where the seeds go. Each seed contribute
56
56
  A seed is at most 32 bytes (`a seed can be at most 32 bytes`, when its length is known at compile time). A `string`
57
57
  argument longer than that is only known at run time: `create`, `createIfNeeded`, `requirePda` and `Seeds<…>` then fail
58
58
  with 2006, as for any other address that is not the PDA; check `byteLength(s) <= 32n` first to fail with an error of
59
- your own. Solana takes at
59
+ your own. A list whose every seed has a length known at compile time (keys, integers, enums, string literals and
60
+ constants) cannot exceed the limits, so its derivation skips the run-time check of the seed lengths; a list with a
61
+ `string` value keeps it, and so do the account-creating calls (`create`, `createIfNeeded`, `createPda` and the token
62
+ creates) of any program that passes one of them such a list. Solana takes at
60
63
  most 16 seeds per address, the bump included. A list the derivation adds the bump to (`create`, `requirePda`,
61
64
  `findProgramAddress`) holds at most 15 entries (`at most 15 seeds: the bump the derivation adds makes 16, Solana's
62
65
  limit`); a list that ends with its bump (signer seeds, `createProgramAddress`) holds 16: 15 seeds and the bump (`at
@@ -135,7 +138,8 @@ export function locate(book: Mut<Book>, owner: Pubkey, start: u64): void {
135
138
  - `findProgramAddress(seeds, program)` is the canonical PDA of any program (Rust's
136
139
  `Pubkey::find_program_address(..).0`, e.g. a Bubblegum asset id), and `findProgramAddressBump(seeds, program)` its
137
140
  bump. `const [address, bump] = findProgramAddressWithBump(seeds, program)` gives both from one search (Rust's
138
- `let (address, bump) = …`). Each search costs about 450 CU per bump tried.
141
+ `let (address, bump) = …`). Each search costs about 450 CU per bump tried, and tries 255 down to 1 as Solana's
142
+ does: bump 0 is never tried.
139
143
  - `createProgramAddress(seeds, program)` is `Pubkey::create_program_address`: the address for seeds that include the
140
144
  bump, or `null` when they give none.
141
145
  - `programId()` is this program's address.
@@ -10,8 +10,9 @@ In short, a function body may contain:
10
10
  | --- | --- |
11
11
  | `const`, `let` | one name each, with an initializer ([declarations](#declarations)) |
12
12
  | assignment, `+=` … `>>=`, `++`, `--` | checked arithmetic ([types](language-types.md#integers)) |
13
+ | `\|\|=`, `&&=`, `??=` | [logical assignment](#logical-assignment): booleans, Options |
13
14
  | `if` / `else`, `? :`, `&&`, `\|\|`, `!` | conditions are `boolean` |
14
- | `for`, `for … of`, `while`, `do … while`, `break`, `continue` | [loops](#loops) |
15
+ | `for`, `for … of`, `while`, `do … while`, `break`, `continue` | [loops](#loops), labeled too (`outer: for …`) |
15
16
  | `switch` | on integers, enums and a data enum's `kind` |
16
17
  | `return` | |
17
18
  | calls | helpers, closures, built-ins, account methods |
@@ -65,7 +66,39 @@ You can assign to a local, a field of a writable account (`Mut<T>`), a field of
65
66
  read-only; copy the value into a local first`), and so are helper parameters (see [Inout](#inout-parameters)).
66
67
 
67
68
  Compound assignments (`+=`, `-=`, `*=`, `/=`, `%=`, `**=`, `&=`, `|=`, `^=`, `<<=`, `>>=`) and `++` / `--` are
68
- checked like the operators they stand for.
69
+ checked like the operators they stand for. All of them are statements: used as a value (`const y = x++`, `f(x += 1n)`)
70
+ they are refused (`x++ is a statement in TypeSOL, not a value: …`).
71
+
72
+ ### Logical assignment
73
+
74
+ ```ts
75
+ import { type Mut, type Option, type u64 } from "typesol";
76
+
77
+ export interface Prefs {
78
+ seen: boolean;
79
+ open: boolean;
80
+ limit: Option<u64>;
81
+ }
82
+
83
+ function fallback(): u64 {
84
+ return 100n;
85
+ }
86
+
87
+ export function touch(prefs: Mut<Prefs>, now: boolean): void {
88
+ prefs.seen ||= now; // written only when seen is false
89
+ prefs.open &&= now; // written only when open is true
90
+ prefs.limit ??= fallback(); // fallback() runs only when limit is empty
91
+ }
92
+ ```
93
+
94
+ - `x ||= v`, `x &&= v` and `x ??= v` work wherever `x = v` does (a local, a field of a writable account or of a local
95
+ struct, a list element's field), as JavaScript runs them: the place is found once, its value read, and only when it
96
+ decides so (false for `||=`, true for `&&=`, empty for `??=`) is `v` evaluated and written. Otherwise `v` does not
97
+ run and nothing is written.
98
+ - `||=` and `&&=` take booleans. On an integer, JavaScript would test for `0n`, which TypeSOL does not do implicitly:
99
+ `||= works on booleans; on u64 JavaScript would test for 0n: write if (…) x = …`.
100
+ - `??=` takes an `Option` (of an integer, boolean, `Pubkey`, struct or array; `acct.home ??= { x, y }` writes the
101
+ whole struct). On anything else it is refused (`??= needs an Option on the left (u64 is never null): …`).
69
102
 
70
103
  ### Copies and references
71
104
 
@@ -100,6 +133,10 @@ export function edit(shape: Mut<Shape>): void {
100
133
  refused (`bind struct references with const`).
101
134
  - **An annotation makes a copy.** `const p: Point = acct.home` (or `= { x, y }`) is a local struct of its own. Lists
102
135
  likewise: `const ys: FixedVec<u64, 4> = acct.xs` is a copy.
136
+ - **A spread copies.** `{ ...p, x: 1n }` copies p's fields at its place in the literal, as `field: p.field` entries
137
+ would ([structs](language-types.md#spreads-in-struct-literals)). A field holding a struct, list or data enum must
138
+ be given after the spread (`pos: { ...p.pos }`): JavaScript would share that nested object between the two values,
139
+ which TypeSOL, copying, could not.
103
140
  - **A reference cannot outlive what it names.** Replacing the referenced place (`book.bids.set(i, …)`, `pop()`,
104
141
  `clear()`, `acct.p = …`) while the reference is still used afterwards is a compile error, because JavaScript would
105
142
  keep the old object: `"q" still refers to a.home; replacing it here would change what "q" reads (in JS it keeps the
@@ -148,7 +185,12 @@ A condition (in `if`, `while`, `for`, `? :`, `&&`, `||`, `!`) must be a `boolean
148
185
  truthiness: `if (amount)` is refused (`expected boolean, got u64`).
149
186
 
150
187
  `==` and `!=` compile like `===` and `!==`: both operands have the same type (`operands have different types` otherwise),
151
- so there is no coercion for the loose forms to do.
188
+ so there is no coercion for the loose forms to do. All four compare integers, booleans, enums, `Pubkey`s, strings and
189
+ Options of those by value. On two structs, data enums, lists, Options of a struct or accounts they are refused: those
190
+ are held by reference, so the comparison would test where they are rather than what they hold, and the compiler copies
191
+ them where JavaScript would pass the same object (a struct argument of a helper, a local declared with its type), so
192
+ the answer would differ from JavaScript's. Compare the fields (`a.x === b.x && a.y === b.y`), a data enum's `.kind`,
193
+ a list's `.length` and elements, or two accounts' `.key`. Comparing an Option with `null` is unchanged.
152
194
 
153
195
  ## Loops
154
196
 
@@ -187,8 +229,36 @@ export function tally(book: Mut<Book>, extra: Vec<u64>, n: u64): void {
187
229
  - `for (const f of [dbl, inc])` runs a list of named functions in turn ([functions](#arrow-functions-and-closures)).
188
230
  - `while`, `do … while`, `break` and `continue`. Inside a `switch`, `break` leaves the switch and `continue` the
189
231
  enclosing loop, as in JavaScript.
190
- - Labels (`outer: for …`) and `for … in` are refused.
232
+ - A label names a loop or a block: `break outer` leaves the labeled statement, `continue outer` goes on with the
233
+ labeled loop's next pass (a `for` runs its update first), from any depth, as in JavaScript. A label on another
234
+ statement (`done: if (…)`) is refused, and so is a second label on one statement. A `loadAccountMut` view held by a
235
+ loop the jump leaves is dropped, as at the end of that loop's pass; a plain `break` drops its loop's views too, so
236
+ the accounts can be loaded again after the loop, and so does a `return` from a helper or a closure for every loop it
237
+ leaves.
238
+ - `for … in` is refused.
191
239
  - There is no iteration limit: loops are bounded by the transaction's compute budget.
240
+
241
+ ```ts
242
+ import { type u64 } from "typesol";
243
+
244
+ export function firstPair(n: u64, target: u64): u64 {
245
+ let found = 0n;
246
+ search: for (let i = 0n; i < n; i++) {
247
+ for (let j = i + 1n; j < n; j++) {
248
+ if (j % 3n === 0n) continue search; // next i
249
+ if (i + j === target) {
250
+ found = i * 1000n + j;
251
+ break search; // leaves both loops
252
+ }
253
+ }
254
+ }
255
+ done: {
256
+ if (found !== 0n) break done;
257
+ found = 1n;
258
+ }
259
+ return found;
260
+ }
261
+ ```
192
262
  - Remaining accounts are iterated by index: `for (let i = 0n; i < rest.length; i++) rest.get(i)`.
193
263
 
194
264
  ## switch
@@ -345,9 +415,14 @@ while passing large values by pointer:
345
415
 
346
416
  ### Inline and @noinline
347
417
 
348
- clang inlines most helpers into their callers, so their locals share the caller's 4 KiB stack frame.
418
+ clang inlines most helpers into their callers, so their locals share the caller's 4 KiB stack frame (on SBPF v1 and v2,
419
+ a frame of at most 32,767 bytes, with 256 KiB for all the frames of a call path).
349
420
  `/** @noinline */` on a helper keeps it a function of its own with its own frame (a few CU per call), for work with
350
- large locals of its own (Phoenix's order ids, built after its event recorder's last CPI):
421
+ large locals of its own (Phoenix's order ids, built after its event recorder's last CPI). A program that does not fit
422
+ the stack without it is laid out by the build itself, which keeps helpers out of line as needed
423
+ ([Memory](language-basics.md#memory-stack-and-heap)), so `@noinline` is for compute units (a rarely taken path kept out
424
+ of its caller) and for explicit control. `/** @inline */` on a helper keeps the build from doing that to it (clang may
425
+ still keep it out of line on its own); a helper is not both.
351
426
 
352
427
  ```ts
353
428
  import { type Mut, type u64, fixedArray } from "typesol";
@@ -562,15 +637,17 @@ may gain a hint line.
562
637
  | reassigning a parameter | `n = 3n;` | "n" is const or an argument and cannot be reassigned |
563
638
  | writing an argument | `p.x = 3n;` (`p: Point` argument) | instruction arguments are read-only; copy the value into a local first |
564
639
  | `for … in` | `for (const k in b) {}` | for … in is not supported: use for (init; cond; step), for (const x of list), while or do … while |
565
- | labels | `outer: for (…) { break outer; }` | LabeledStatement is not supported in TypeSOL |
640
+ | a label on another statement | `done: if (n > 1n) { break done; }` | a label goes on a loop or a block: done: for (…) { … } (break / continue done) or done: { … } (break done) |
641
+ | `\|\|=` / `&&=` on a non-boolean | `b.value \|\|= n;` | \|\|= works on booleans; on u64 JavaScript would test for 0n: write if (…) b.value = … |
642
+ | `??=` on a non-Option | `b.value ??= n;` | ??= needs an Option on the left (u64 is never null): write b.value = … |
566
643
  | truthiness | `if (n) log("x");` | expected boolean, got u64 |
567
644
  | indexing with `[ ]` | `b.value = b.xs[0];` | indexing with [ ] is not supported: use .get(i) and .set(i, value), with i a bigint (0n) |
568
645
  | array literals as values | `const a = [1n, 2n];` | arrays are only allowed inline as seeds/CPI lists; declare local arrays with fixedArray<T, N>(fill) |
569
- | untyped object literals, spread | `const o = { a: 1n };` | an object literal needs a struct type here: give it one (const p: Point = { … }), … |
570
- | `new` | `const m = new Map<u64, u64>();` | this syntax (NewExpression) is not supported in TypeSOL expressions |
646
+ | untyped object literals | `const o = { a: 1n };` | an object literal needs a struct type here: give it one (const p: Point = { … }), … |
647
+ | `new` | `const m = new Map<u64, u64>();` | new is not supported: a program has no Map or Set; keep entries in a FixedVec<T, N> of structs (or a FixedArray), or one account per key (a PDA) |
571
648
  | `typeof` | `const t = typeof n;` | typeof is not supported at run time: the types are known when the program compiles |
572
649
  | `delete` | `const k = delete b.value;` | The operand of a 'delete' operator must be optional. (TypeScript; on an operand TypeScript accepts: delete is not supported: account fields always exist; set the value instead) |
573
- | `void` | `const v = void n;` | this syntax (VoidExpression) is not supported in TypeSOL expressions |
650
+ | `void` | `const v = void n;` | void is not supported: call the function as a statement (its result is then unused) |
574
651
  | `instanceof` | `if (b instanceof Object) {}` | operator instanceof is not supported |
575
652
  | `in` | `if ("value" in b) {}` | operator in is not supported |
576
653
  | the comma operator | `y = (b.value = 1n, 2n);` | operator , is not supported |
@@ -583,8 +660,18 @@ may gain a hint line.
583
660
  | optional fields | `export interface O { v?: u64 }` | optional fields are not supported; use v: Option<T> (null for none) |
584
661
  | methods in interfaces | `export interface G { v(): u64 }` | structs may only contain plain fields |
585
662
  | enum initializers | `export enum E { A = 1, B = 2 }` | value enum members are numbered 0, 1, 2… in order; leave out initializers |
586
- | nested `function` declarations | `function inner(x: u64): u64 { return x; }` (in a body) | FunctionDeclaration is not supported in TypeSOL |
663
+ | nested `function` declarations | `function inner(x: u64): u64 { return x; }` (in a body) | function declarations inside a function are not supported: write const inner = (…): T => { … } (a closure), or declare inner at the top level |
664
+ | a function called where it is written | `b.value = ((v: u64): u64 => v)(n);` | a function called where it is written is not supported: bind it first (const f = (…) => …) and call f(…) |
665
+ | `++` / `--` / `+=` as a value | `const y = m++;` | m++ is a statement in TypeSOL, not a value: read m into a const first, then write m++; on its own line |
666
+ | union types | `export function f(x: u64 \| boolean): void {}` | union types (u64 \| boolean) are not supported: a value has one type; use a data enum (…) for a value of several shapes |
667
+ | literal types | `type Side = "bid" \| "ask";` | a union of literal types ("bid" \| "ask") is not supported: use an enum (export enum Side { … }) for named choices, or the integer type itself |
668
+ | intersection types | `export type B = Box & { n: u64 };` | intersection types (Box & { n: u64 }) are not supported: declare an interface that extends the named structs and adds the other fields (…) |
669
+ | `Readonly`, `Pick`, `keyof`, `typeof` and other type operators | `function h(p: Readonly<Point>): u64 { … }` | Readonly<T> is not supported: write T itself (helper parameters are read-only already) |
670
+ | a spread that would share a nested object | `const c: Line = { ...l, n };` (`l.a: Point`) | ...l would copy a, a Point: JavaScript shares that object between the two values, TypeSOL copies it; give a after the spread (a: { ...l.a } copies it in JavaScript too) |
671
+ | a struct passed as its parent | `c.base = c.child;` (`Child extends Base`) | expected a Base: an object literal, another Base; a Child is not used as its parent Base (TypeSOL copies structs where JavaScript shares the object): … |
587
672
  | recursion | `function a(x: u64): u64 { return x === 0n ? 0n : a(x - 1n); }` | recursion is not supported: a -> a |
673
+ | `declare function` | `declare function ext(x: u64): u64;` | declare function has no body to compile: a program calls only the helpers it defines and TypeSOL's built-ins (another program is called with a CPI) |
674
+ | overload signatures | `function h(x: u64): u64;` (before `function h(x: u64): u64 { … }`) | overload signatures are not supported: write one function, with an Option<T> parameter for an argument that may be left out |
588
675
  | helpers without a return type | `function h(x: u64) { return x; }` | helper functions need an explicit return type (void, an integer, boolean, Pubkey or a struct) |
589
676
  | namespaces | `namespace N { export const x = 1n; }` | namespaces are not supported: use separate files and import from them |
590
677
  | npm and Node.js imports | `import { x } from "lodash";` | only imports from "typesol" and relative TypeSOL files ("./math") are allowed, got "lodash" |
@@ -601,6 +688,9 @@ may gain a hint line.
601
688
  | unary minus on unsigned | `b.value = -n;` | unary minus needs a signed integer (i8 … i128) |
602
689
  | operators on `f64` | `b.value = r.x + r.x;` (`r.x: f64`) | + on an f64 is not supported: an f64 is held as its IEEE 754 bits and there is no float arithmetic (this would compute on the bits); compute in integers and make the result with f64FromBits(bits), or take an f64's bits with f64Bits(x) |
603
690
  | `===` on `f64` | `if (r.x === r.y) {}` (`f64` fields) | === on an f64 is not supported: an f64 is held as its IEEE 754 bits, and equal bits are not equal numbers (NaN would equal itself, 0 would not equal -0); to compare the bits, write f64Bits(a) === f64Bits(b) |
691
+ | `===` on structs | `if (p === q) {}` (`p`, `q`: `Point` arguments) | === on two structs is not supported: it would compare where they are held, not their contents, and a struct passed to a helper or declared with its type is a copy; compare the fields you need (a.x === b.x && …) |
692
+ | `===` on data enums | `if (e === g) {}` (`e`, `g`: data enum arguments) | === on two data enums is not supported: it would compare where they are held, not their contents; compare .kind, then the fields of the narrowed variants |
693
+ | `===` on lists | `if (u === w) {}` (`u`, `w`: `Vec<u64>` arguments) | === on two lists is not supported: it would compare where they are held, not their contents; compare .length and the elements (.get(i)) |
604
694
  | an `f64` as an integer | `b.value = r.x;` (`r.x: f64`) | an f64 is not an integer, so it is not converted to u64: it is held as its IEEE 754 bits, and the integer would be those bits; to use the bits, write f64Bits(x) |
605
695
  | an `f64` as text | ``log(`${r.x}`);`` (`r.x: f64`) | an f64 cannot be written as text: there is no float formatting, and the digits would be its IEEE 754 bits read as an integer; to show the bits, write f64Bits(x) |
606
696
  | `?.` on a non-optional value | `const v = b?.value;` | ?. works on optional accounts and Option<struct> values (other values are never null) |
@@ -201,7 +201,8 @@ export function report(owner: Pubkey, amount: u64, limit: Option<u64>): void {
201
201
  or `Hash` prints as base58 and an `Option` of an integer, boolean, `Pubkey` or `Hash` as its value or `null`, as
202
202
  JavaScript prints it (after `x !== null`, the value). A template is joined in one allocation; text known when the
203
203
  program compiles (literals, string and `Pubkey` constants) is folded in; `s += …` grows the newest heap string in
204
- place. Tagged templates (`` String.raw`…` ``) are refused.
204
+ place. The left side of `s += …` is read before the right side runs, as in JavaScript: a right side that assigns `s`
205
+ (a closure it calls) does not change what is appended to. Tagged templates (`` String.raw`…` ``) are refused.
205
206
 
206
207
  ## Enums
207
208
 
@@ -264,6 +265,7 @@ export function apply(vault: Mut<Vault>, action: Action): void {
264
265
 
265
266
  - A data enum is a union of object types, each with a `kind` string literal: Rust's enum with fields, Borsh-encoded as
266
267
  Anchor encodes one. `a.kind === "Deposit"` or `switch (a.kind)`, and TypeScript narrowing picks the variant.
268
+ Two data enums are not compared with `===` (refused): compare their `kind`, then the fields of the narrowed variants.
267
269
  - Reading a variant's field is checked again at run time: when the value is not that variant, 5112.
268
270
  - In account data: 1 tag byte then room for the largest variant. In arguments and events: the tag, then that
269
271
  variant's fields.
@@ -299,7 +301,10 @@ export function step(player: Mut<Player>, dx: u64): void {
299
301
  ```
300
302
 
301
303
  - An `interface` with fixed-size fields is a struct; exported ones are in the IDL. Fields are stored in declaration
302
- order, back to back, with no padding.
304
+ order, back to back, with no padding. An object type alias is the same struct: `export type Point = { x: u64; y: u64 }`
305
+ works wherever `export interface Point { … }` does (account data, arguments, results, events, helper parameters,
306
+ fields of other structs). An object type with `kind: "Name"` is a [data enum](#data-enums) of one variant instead.
307
+ Account groups are interfaces only.
303
308
  - A struct literal names every field (`{ x, y: 2n }`); a missing or unknown field is an error. An object literal needs
304
309
  a known struct type: a typed local (`const p: Point = { … }`), a field, a helper parameter, `emit<T>(…)`.
305
310
  - `a.home = b.home` copies the whole struct, as Rust and Anchor do; how `const` binds one is in [copies and
@@ -312,7 +317,71 @@ export function step(player: Mut<Player>, dx: u64): void {
312
317
  The same holds wherever TypeSOL copies a whole value itself (Borsh fields, instruction arguments, a helper's copy of
313
318
  a struct argument, events), and a value it zeroes whole (`x.o = null` on an `Option<struct>`, a data-enum literal)
314
319
  takes the memset syscall from 192 bytes in account data and 600 in a local.
320
+ - `===`, `!==`, `==` and `!=` on two structs are refused (`=== on two structs is not supported`): a struct is held by
321
+ reference and copied where JavaScript would share it, so the comparison could not give JavaScript's answer. Compare
322
+ the fields you need: `a.x === b.x && a.y === b.y`. The same holds for data enums, lists and Options of a struct
323
+ ([conditions](language-statements.md#conditions)).
315
324
  - A struct cannot contain itself.
325
+ - Generic structs (`interface Pair<T>`, `type Pair<T> = { … }`) and intersection types (`type B = A & { … }`) are
326
+ refused; write the struct out, or extend it ([below](#structs-that-extend-others)).
327
+
328
+ ### Structs that extend others
329
+
330
+ ```ts
331
+ import { type Mut, type Pubkey, type u32, type u64, type u8 } from "typesol";
332
+
333
+ export interface Base {
334
+ id: u32;
335
+ owner: Pubkey;
336
+ }
337
+
338
+ export type Tagged = { tag: u8 };
339
+
340
+ // Fields, in this order: id, owner (Base's), tag (Tagged's), then qty.
341
+ export interface Item extends Base, Tagged {
342
+ qty: u64;
343
+ }
344
+
345
+ export interface Shelf {
346
+ base: Base;
347
+ item: Item;
348
+ }
349
+
350
+ export function stock(shelf: Mut<Shelf>, qty: u64): void {
351
+ shelf.item = { ...shelf.base, tag: 1n, qty }; // a parent's fields, then the child's own
352
+ shelf.base = { ...shelf.item }; // a child's copy of the parent's fields
353
+ }
354
+ ```
355
+
356
+ - `interface B extends A, C { … }` (with `A` and `C` structs of the program, interfaces or object types) has A's fields,
357
+ then C's, then its own, in that order: that is its layout in account data, arguments and events, and its order in
358
+ the IDL. In the fixed layout growable `Vec`s still go last ([fixed layout](#structs)); a `BigVec` must stay the last
359
+ field, so a struct cannot extend one that ends in a `BigVec` and add fields.
360
+ - A field in two parents is one field when it has the same type in both (`C.a and A.a have different types; B cannot
361
+ extend both` otherwise). A struct cannot declare an inherited field again, extend a generic type, a data enum or an
362
+ account group, or extend the same struct twice. Doc tags (`@layout`, `@discriminator`) are each struct's own.
363
+ - A `B` is not passed or assigned where an `A` is expected (`a Child is not used as its parent Base (TypeSOL copies
364
+ structs where JavaScript shares the object): …`): JavaScript would pass the object itself, extra fields and all,
365
+ which TypeSOL, copying structs, could not reproduce. Write the parent's copy as a spread, `{ ...child }`, or field by
366
+ field.
367
+
368
+ ### Spreads in struct literals
369
+
370
+ - `{ ...p, x: 1n }` and `{ x: 1n, ...p }` build a struct from p's fields and the entries given: entries run left to
371
+ right, each once, and a later one overwrites an earlier one, as in JavaScript. `...p` reads p's fields at its place,
372
+ so an entry after it that changes p (a helper writing the account) does not change what was copied, and an entry
373
+ before it does.
374
+ - p is a struct place (a local, a field, a list element, a helper's struct parameter) or a struct account; of the
375
+ literal's type, of a struct the literal's type extends (its fields are copied, the rest are given), or of one that
376
+ extends it (the literal's fields are copied from it).
377
+ - A spread copies as assignment does ([copies and references](language-statements.md#copies-and-references)). For
378
+ scalars, strings and Options of scalars that is JavaScript's result. A field holding a struct, list or data enum
379
+ would be shared by JavaScript between p and the new value, so it must be given after the spread:
380
+ `{ ...p, pos: { ...p.pos } }` is a copy in JavaScript too, while `{ ...p }` alone is refused (`...p would copy pos,
381
+ a Point: JavaScript shares that object between the two values, TypeSOL copies it; give pos after the spread …`).
382
+ - `acct.p = { ...acct.p, x: 1n }` reads the old fields: the new value is built before it is stored.
383
+ - Spreads are for struct literals of a known struct type. In `emit<T>(…)`, a data enum literal, a list literal or a
384
+ built-in's object argument they are refused.
316
385
 
317
386
  ### File-local structs
318
387
 
@@ -340,6 +409,7 @@ export function bid(auction: Mut<Auction>, amount: u64, cap: Option<u64>): void
340
409
  ```
341
410
 
342
411
  - `Option<T>` (or `T | null`) is a value or `null`. Compare with `=== null` / `!== null`; TypeScript narrows it.
412
+ Two Options of a struct are not compared with `===` (refused): check each against `null`, then compare fields.
343
413
  - Using an empty option where a value is needed fails with 5108; `x!` is the value, or 5108.
344
414
  - `a ?? b` takes `b` only when `a` is empty, and evaluates `b` only then; the result is an Option when `b` can be null.
345
415
  - `===` between options, or with a value, follows JavaScript: `null === null`, and an empty option never equals a
@@ -454,8 +524,8 @@ own PDA must sign, which only its `executeTransaction` does, for a transaction e
454
524
  - Setting one up costs about the same at any size: `fixedVec([])` of 1280 bytes is about 10 CU (the free slots are
455
525
  zeroed by the memset syscall, the elements written in place, also as a struct literal's field).
456
526
  - **Size limit.** One list holds at most 2 KiB of elements (the FixedVec's u32 length aside: `FixedVec<u32, 512>`
457
- fits). The 4 KiB stack frame is shared with the rest of the function, and a frame that overflows is reported with
458
- its biggest locals; a bigger list is a compile error naming its size. [`@heap`](#heap-values) moves one to the heap.
527
+ fits). The 4 KiB stack frame (on SBPF v1 and v2, at most 32,767 bytes) is shared with the rest of the function, and
528
+ a frame that overflows is reported with its biggest locals; a bigger list is a compile error naming its size. [`@heap`](#heap-values) moves one to the heap.
459
529
  - A `FixedVec<u8, N>` is also a byte buffer: `pushLE`, `pushKey`, `pushBorsh`, `setLE`, `truncate`
460
530
  ([byte builders](language-native.md#byte-strings-built-by-hand)).
461
531
 
@@ -591,6 +661,8 @@ Locals live on the stack. These live on the heap (32 KiB by default;
591
661
  - strings built at run time (5110 when the heap is full);
592
662
  - a `@layout borsh` struct's `Vec` fields while the instruction runs;
593
663
  - the CPI scratch lists of a program that declares `MAX_ACCOUNTS`;
664
+ - a list or struct local of an instruction that the build moved there because the program did not fit the stack
665
+ ([Memory](language-basics.md#memory-stack-and-heap)), as it moves a helper's struct result the instruction holds;
594
666
  - a list or struct local marked `/** @heap */`:
595
667
 
596
668
  ```ts
@@ -606,6 +678,9 @@ export function collect(n: u8): void {
606
678
 
607
679
  `/** @heap */` on an instruction's list or struct local keeps it on the heap instead of the stack: one allocation per
608
680
  declaration, reused when a loop declares it again, up to the heap's size, for about 18 CU. Not in helpers, which may
609
- run many times while the heap is never freed.
681
+ run many times while the heap is never freed. A local the build moves to the heap to fit the stack is handled the same
682
+ way (one allocation per declaration, reused by a loop; for a helper's struct result, one per call site), and only while
683
+ the instruction's `@heap` and moved locals together fit in the heap; the note gives its bytes. `/** @stack */` on a
684
+ list or struct local (or on `const r = helper(…)` returning a struct) keeps it off the heap; a local is not both.
610
685
 
611
686
  **Next:** [Statements and functions](language-statements.md): which TypeScript is TypeSOL.
package/docs/runtime.md CHANGED
@@ -71,7 +71,7 @@ In file order:
71
71
  | Account checks | owner, discriminator, signer, writable, executable, address, size, uniqueness (`ts_check_*`), growable Vec lengths; `ts_owned`, the native views' owner check with its one-account cache (`TS_OWNER_CACHE`, forgotten at every CPI and owner write by `TS_OWNER_FORGET`) |
72
72
  | Little-endian IO | `ts_read_le` and friends for argument decoding and Borsh |
73
73
  | Sysvars | clock, rent (`ts_rent`, `ts_minimum_balance_of`, `ts_minimum_balance`), program data |
74
- | PDA | `ts_pda_hash`, `ts_create_pda_address`, `ts_find_pda` (canonical bump), `ts_require_pda` |
74
+ | PDA | `ts_pda_hash`, `ts_create_pda_address`, `ts_find_pda` (canonical bump: 255 down to 1, as the syscall), `ts_require_pda`; their `_fit` forms, without the run-time check of the seed limits, for seed lists the compiler proved within them (`TS_PDA_SEEDS_FIT` for the account-creating helpers when every list of the program is) |
75
75
  | System program CPIs | create, assign, allocate, transfer, `ts_create_pda`, `ts_resize` / `ts_realloc`, close |
76
76
  | Token-2022 extensions | TLV walking for the extensions the language reads |
77
77
  | Metaplex Core and Bubblegum | account readers (`coreAssetOwner`, …) |
@@ -180,10 +180,12 @@ exposed to them.
180
180
  The compiler and runtime have had internal security reviews, the latest of 0.44.0 (above); its findings are fixed in
181
181
  0.44.1. It was an internal review, not an independent audit; it covered the token, Token-2022, Metaplex and Stake
182
182
  wrappers, the oracles and SBPF v1/v2 builds of the examples that the review of 0.43.0 left out, but not the Metaplex
183
- wrappers for unusual argument shapes beyond reading them, the large ports on SBPF v1/v2, or Windows. 0.45.0 to 0.50.0
183
+ wrappers for unusual argument shapes beyond reading them, the large ports on SBPF v1/v2, or Windows. 0.45.0 to 0.51.0
184
184
  have had no security review. They add, among others, `runtime/typesol_builtins.c` (the
185
185
  compiler builtins as TypeSOL's own C, 0.45.0), `transferCheckedWithHook`, `EVENT_AUTHORITY_CHECK` and the reads of
186
186
  processed sibling instructions (0.48.0), `zeroData`, `log64`,
187
187
  `PANIC_STYLE = "solana-1.18"`, `executable` on remaining accounts and lamport writes on remaining accounts under
188
- `NATIVE_ACCOUNT_WRITES` (0.49.0), and `copyData`, `getReturnData()`, `PANIC_STYLE = "pinocchio"` and whole values
189
- copied and zeroed by the memory syscalls (0.50.0). There has been no external audit: see [audit.md](audit.md).
188
+ `NATIVE_ACCOUNT_WRITES` (0.49.0), `copyData`, `getReturnData()`, `PANIC_STYLE = "pinocchio"` and whole values
189
+ copied and zeroed by the memory syscalls (0.50.0), and the base58 text of keys from a table, derivations without
190
+ the run-time seed-limit check, object-type structs, `extends`, struct spreads, labels, logical assignment and the
191
+ stack layout the build chooses for a program that does not fit (0.51.0). There has been no external audit: see [audit.md](audit.md).
package/docs/stability.md CHANGED
@@ -138,7 +138,11 @@ Useful today, but may still change before 1.0 (each change listed in the CHANGEL
138
138
  - Constant expressions (0.43.0): top-level integer constants folded from literals and earlier constants, a typed
139
139
  one computed in its type.
140
140
  - Comma-separated `for` updates and initializers (0.43.0).
141
- - Stack room (0.43.0): `/** @noinline */` helpers and `/** @heap */` locals.
141
+ - Stack room (0.43.0): `/** @noinline */` helpers and `/** @heap */` locals. A program that does not fit the stack is
142
+ laid out by the build (statements in blocks of their own, helpers kept out of line, an instruction's locals on the
143
+ heap), with `STACK_AUTO`, `--stack-auto`, `/** @inline */` and `/** @stack */` to turn it off (unreleased). Which
144
+ steps it takes, and so the bytes of a program that did not fit as written, may change between releases; a program
145
+ that fits is never laid out.
142
146
  - Local `FixedVec` / `FixedArray` lists of structs, `FixedVec.pushAll`, the instruction data as a list (`slice`,
143
147
  `InstructionBytes` helper parameters), `invokeInstruction` in helpers (0.42.0); local FixedVecs given for read-only
144
148
  `FixedVec<T, N>` / `Vec<T>` helper parameters (0.43.0).
@@ -122,7 +122,8 @@ a ComputeBudget `requestHeapFrame` instruction to the transaction.
122
122
  ### "instruction X (with the helpers inlined into it) needs N bytes of stack; SBPF v0 gives each function 4096"
123
123
 
124
124
  Under SBPF v0 (the default) every function gets a fixed 4 KiB stack frame, and going past it corrupts memory, so the
125
- build refuses it. SBPF v1 and v2 (`--sbpf v1` / `v2`) grow frames dynamically, so this limit does not apply there. Large
125
+ build refuses it. SBPF v1 and v2 (`--sbpf v1` / `v2`) size each function's frame, so the 4 KiB limit is lifted there,
126
+ but they have limits of their own (the next two entries). Large
126
127
  structs and arrays copied into typed locals (`const q: Big = acct.big`) are the usual cause: bind them without a type
127
128
  (`const q = acct.big`, a reference into the account data). The message lists the biggest locals (clang's frame layout: a
128
129
  local's name and the source line near it; the locals of an inlined helper show as unnamed, with the helpers' locals that
@@ -130,6 +131,49 @@ may be them). Helpers are often inlined into their instruction, so their locals
130
131
  @noinline */` to give it a 4 KiB frame of its own (a few compute units per call), or declare a large local list or
131
132
  struct of an instruction `/** @heap */` to keep it on the heap (about 18 CU for the allocation).
132
133
 
134
+ The build tries those itself before it gives this error ([Memory](language-basics.md#memory-stack-and-heap)): when they
135
+ were not enough, the message ends with "To fit, the build also tried …", and lists the locals the heap could not hold.
136
+ What is left is usually a helper's own locals (the build keeps a helper's locals on the stack: it may run many times,
137
+ and the heap is never freed) or one local larger than the heap. With `const STACK_AUTO = false` (or `--stack-auto off`)
138
+ the build does not try, and gives the error as it is.
139
+
140
+ ### "note: instruction X did not fit the stack …"
141
+
142
+ Not an error: the program did not fit the stack as written, and the build laid it out another way (the notes after it
143
+ say how, and `<name>.build.json` records it under `stack`). Its binary differs from what the source would give if it
144
+ fitted, so a port comparing compute units with its original should look at the notes: a helper kept out of line costs
145
+ about 10 compute units per call, a local on the heap about 17 and its bytes of heap. Declaring the same yourself
146
+ (`/** @noinline */`, `/** @heap */`) or binding large values as references instead of copies gives the same or better,
147
+ and `/** @inline */` or `/** @stack */` keeps the build from choosing a helper or a local.
148
+
149
+ ### "… needs N bytes of stack; SBPF v1 allows one function at most 32767"
150
+
151
+ On SBPF v1 and v2 a load or store reaches its stack slot with a signed 16-bit offset, so a frame over 32,767 bytes
152
+ cannot be addressed: clang's SBF backend builds it anyway, with the large offsets wrapped, and the program reads and
153
+ writes the wrong memory. The build refuses such a frame. The remedies are the ones above: references instead of copies,
154
+ `/** @heap */` on a large local of an instruction, or a `/** @noinline */` helper for work with large locals of its
155
+ own.
156
+
157
+ ### "the deepest call path needs N bytes of stack; SBPF v1 gives all the frames of a call path together 262144"
158
+
159
+ On SBPF v1 and v2 every frame of a call path (the entrypoint, the instruction, each helper it calls in turn) comes out
160
+ of one 256 KiB stack, and past it the program fails with an access violation. After linking, the build measures the
161
+ deepest path from the program's own code (its calls and the frame each function reserves, so a helper clang inlined
162
+ counts in its caller) and refuses a program whose deepest path is over 262,144 bytes. The message lists the path with
163
+ each function's frame. Shorten it: keep large values in account data or on the heap, or call the helpers with large
164
+ frames one after another rather than from each other. (An indirect call, which TypeSOL does not generate, cannot be
165
+ followed: a program with one is refused with a request to report it.)
166
+
167
+ ### "… a call passes arguments on the stack past the end of the 4096-byte frame of SBPF v0"
168
+
169
+ A helper call with more than 5 arguments in C (its parameters, plus one for the program's context and one for a
170
+ returned value) passes the rest on the stack, after the caller's locals. When the caller's frame is at the limit,
171
+ those arguments overwrite its own values. clang's SBF backend reports this ("A function call in method … overwrites
172
+ values in the frame") but still builds, and such a program computed wrong results; the build now refuses it, naming the
173
+ function and the helpers it calls with arguments on the stack. Give the helper fewer parameters (a struct parameter is
174
+ passed as one pointer) or make room in the caller as above. The backend's other message, "Stack offset of N exceeded
175
+ max offset of M", is refused the same way.
176
+
133
177
  ### "… is missing, but typesol.json records …"
134
178
 
135
179
  The program keypair under `target/deploy/` was deleted or replaced. Restore it from your backup. Without it you cannot