@typesol/cli 0.42.0 → 0.43.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 (44) hide show
  1. package/CHANGELOG.md +227 -0
  2. package/README.md +10 -7
  3. package/dist/compiler/analyze.js +443 -12
  4. package/dist/compiler/diagnostics.d.ts +1 -0
  5. package/dist/compiler/diagnostics.js +13 -0
  6. package/dist/compiler/emit/alias.d.ts +44 -0
  7. package/dist/compiler/emit/alias.js +135 -4
  8. package/dist/compiler/emit/base.d.ts +25 -0
  9. package/dist/compiler/emit/base.js +58 -7
  10. package/dist/compiler/emit/calls.d.ts +67 -0
  11. package/dist/compiler/emit/calls.js +521 -46
  12. package/dist/compiler/emit/cpi-core.d.ts +20 -3
  13. package/dist/compiler/emit/cpi-core.js +226 -5
  14. package/dist/compiler/emit/cpi.js +8 -2
  15. package/dist/compiler/emit/expressions.js +38 -7
  16. package/dist/compiler/emit/program.js +30 -1
  17. package/dist/compiler/emit/rbtree.d.ts +7 -0
  18. package/dist/compiler/emit/rbtree.js +142 -0
  19. package/dist/compiler/emit/shared.d.ts +8 -0
  20. package/dist/compiler/emit/shared.js +9 -1
  21. package/dist/compiler/emit/statements.d.ts +27 -1
  22. package/dist/compiler/emit/statements.js +288 -19
  23. package/dist/compiler/emit/storage.d.ts +23 -2
  24. package/dist/compiler/emit/storage.js +100 -56
  25. package/dist/compiler/emit/token.js +2 -2
  26. package/dist/compiler/emit/views.d.ts +60 -0
  27. package/dist/compiler/emit/views.js +523 -0
  28. package/dist/compiler/idl.js +2 -1
  29. package/dist/compiler/model.d.ts +65 -4
  30. package/dist/compiler/model.js +14 -0
  31. package/dist/compiler/toolchain.d.ts +15 -0
  32. package/dist/compiler/toolchain.js +146 -11
  33. package/docs/architecture.md +9 -2
  34. package/docs/case-study-phoenix.md +226 -0
  35. package/docs/language.md +139 -8
  36. package/docs/migrate-from-anchor.md +1 -0
  37. package/docs/runtime.md +1 -1
  38. package/docs/stability.md +21 -2
  39. package/docs/troubleshooting.md +5 -2
  40. package/lib/typesol.d.ts +221 -4
  41. package/llms-full.txt +169 -14
  42. package/llms.txt +1 -1
  43. package/package.json +2 -2
  44. package/runtime/typesol_rt.h +407 -0
@@ -85,6 +85,8 @@ export interface Ref {
85
85
  big?: string;
86
86
  /** `bigVec.slice(start, end)`: a view of some of its elements (`len` is then a value, not the stored length). */
87
87
  slice?: boolean;
88
+ /** A `rawArrayAt` view (with `big` and `slice`): `len` its run-time count, nothing stored. */
89
+ raw?: boolean;
88
90
  /** Growable Vecs stored after this one move when it grows or shrinks: where its elements end, and their paths. */
89
91
  tail?: {
90
92
  end: string;
@@ -115,6 +117,12 @@ export interface Local {
115
117
  /** For struct / data-enum references: the storage paths they alias (e.g. "book.asks[]"), and the declaration. */
116
118
  paths?: string[];
117
119
  decl?: ts.VariableDeclaration | ts.ParameterDeclaration;
120
+ /** A struct reference into an element of a list whose elements can move (a growable Vec, a heap Vec, a BigVec). */
121
+ movable?: boolean;
122
+ /** A native view (`loadRaw`, `loadRawMutAt`, `rawArrayMutAt`, `rbTreeMutAt` …): under NATIVE_ACCOUNT_WRITES two views may share bytes. */
123
+ view?: boolean;
124
+ /** For a native view: the account it reads (see `viewAccountKey`), so closeRaw / resizeAccount can end it. */
125
+ viewAcct?: string;
118
126
  /** A local closure (`const f = (…) => …` reading the enclosing function's variables), expanded where it is called. */
119
127
  closure?: Closure;
120
128
  /**
@@ -77,6 +77,12 @@ export function valueC(t) {
77
77
  return "TsEpochRewards";
78
78
  case "structRef":
79
79
  return `TSS_${t.struct} *`;
80
+ case "rawArray":
81
+ return `${fieldC(t.elem)} *`;
82
+ case "rbTree":
83
+ return "TsRbt";
84
+ case "rbEntry":
85
+ return "TsRbtEntry";
80
86
  case "enumRef":
81
87
  case "dataEnumArg":
82
88
  return `TSE_${t.name} *`;
@@ -209,6 +215,8 @@ export function helperSignature(h) {
209
215
  if (p.account.kind === "account" && p.account.mut && p.account.struct.vec)
210
216
  params.push(`uint64_t entry_${p.name}`);
211
217
  }
218
+ else if (p.inout?.kind === "vec")
219
+ params.push(`${fixedVecC(p.inout)} *p_${p.name}`); // the caller's list itself (Inout<FixedVec<T, N>>)
212
220
  else if (p.type.kind === "signerSeeds")
213
221
  params.push(`const SolSignerSeed *p_${p.name}`, `int p_${p.name}__n`);
214
222
  // The remaining accounts: the index of the first one among the instruction's accounts.
@@ -223,7 +231,7 @@ export function helperSignature(h) {
223
231
  }
224
232
  if (h.returns)
225
233
  params.push(h.returns.kind === "struct" ? `TSS_${h.returns.name} *ret` : h.returns.kind === "string" ? `TS_Str *ret` : `${scalarC(h.returns)} *ret`);
226
- return `static uint64_t fn_${h.name}(${params.join(", ")})`;
234
+ return `${h.noinline ? "__attribute__((noinline)) " : ""}static uint64_t fn_${h.name}(${params.join(", ")})`;
227
235
  }
228
236
  /** C type of a growable Vec stored after the first one of struct `s`: `{ uint32_t len; T items[]; }`. */
229
237
  export function laterVecC(s, field) {
@@ -1,6 +1,7 @@
1
1
  import ts from "typescript";
2
+ import { type TypeScope } from "../analyze.js";
2
3
  import { type FieldType } from "../model.js";
3
- import { type Value, type Closure, type FunctionChoice, type Ref } from "./shared.js";
4
+ import { type Value, type Local, type Closure, type FunctionChoice, type Ref } from "./shared.js";
4
5
  import { CpiEmitter } from "./cpi.js";
5
6
  /**
6
7
  * Statements: variables, assignment, control flow and return.
@@ -18,6 +19,13 @@ export declare abstract class StatementEmitter extends CpiEmitter {
18
19
  * As in JS, the length is read again before every step, so a body that pushes or pops sees the new length.
19
20
  */
20
21
  protected forOf(stmt: ts.ForOfStatement): void;
22
+ /**
23
+ * `for (const e of tree)` / `for (const e of tree.reversed())` over a RedBlackTree: lib-sokoban's in-order
24
+ * iterator (a stack of nodes, left registers down, then the right one), smallest key first or, reversed, largest
25
+ * first. `e` is the node (`e.key`, `e.value`, `e.index`), each read where it lies. The body may change values
26
+ * but not the tree's structure (insert / remove / initialize on it are compile errors, as Rust's borrow forbids).
27
+ */
28
+ protected treeForOf(stmt: ts.ForOfStatement, d: ts.VariableDeclaration): boolean;
21
29
  /** The functions a list literal names (`[f, g]`: closures, helpers or choices), or undefined when it holds anything else. */
22
30
  protected functionList(list: ts.ArrayLiteralExpression): (Closure | FunctionChoice)[] | undefined;
23
31
  /**
@@ -117,6 +125,11 @@ export declare abstract class StatementEmitter extends CpiEmitter {
117
125
  * was declared with, so a block around the call that declares the same name does not change what it reads, and
118
126
  * writes to captured `let`s are seen by the enclosing function. Returns the result (undefined for no value).
119
127
  */
128
+ /**
129
+ * An `Inout<T>` parameter of a function expanded where it is called: a pointer to the caller's place (a struct,
130
+ * FixedArray or FixedVec), which must be writable, bound as a reference local.
131
+ */
132
+ protected inoutBinding(p: ts.ParameterDeclaration, arg: ts.Expression, calleeScope: TypeScope, fnName: string): Local;
120
133
  protected expandClosure(c: Closure, args: readonly ts.Expression[], node: ts.Node, into?: Ref): Value | undefined;
121
134
  /**
122
135
  * `xs.forEach / some / every / find / findIndex / reduce / includes / indexOf` on a Vec, FixedArray, FixedVec or Vec
@@ -141,6 +154,19 @@ export declare abstract class StatementEmitter extends CpiEmitter {
141
154
  protected iterationClaims(body: ts.Statement): () => void;
142
155
  protected body(stmt: ts.Statement): void;
143
156
  protected variable(list: ts.VariableDeclarationList, topLevel?: boolean): void;
157
+ /**
158
+ * Whether a declaration is `/** @heap *\/`: a local list or struct kept on the heap (the bump allocator) rather
159
+ * than in the function's 4 KiB stack frame. Only in an instruction, which runs once per instruction: a helper may
160
+ * run any number of times and the heap is never freed.
161
+ */
162
+ protected heapLocal(d: ts.VariableDeclaration, aggregate: boolean): boolean;
163
+ /** A `@heap` local must fit in the heap (32 KiB, or HEAP_SIZE_KIB), which other allocations share. */
164
+ protected checkHeapRoom(bytes: number, at: ts.Node): void;
165
+ /**
166
+ * `const [address, bump] = findProgramAddressWithBump(seeds, program)`: Rust's `let (address, bump) =
167
+ * Pubkey::find_program_address(…)`, both from one search (the only array destructuring the language has).
168
+ */
169
+ protected addressAndBump(d: ts.VariableDeclaration, pattern: ts.ArrayBindingPattern, mutable: boolean): void;
144
170
  /**
145
171
  * `const { a, b: c } = s`: one declaration per name, `const a = s.a`, in source order. The source must be a name or
146
172
  * a field path (no calls), so reading it once per name reads the same thing JS reads once.
@@ -1,7 +1,7 @@
1
1
  import ts from "typescript";
2
2
  import { MAX_RETURN_DATA, calleeName, resolveScalarType, resolveValueType, structNameOf, typesolName } from "../analyze.js";
3
- import { INT_INFO, isScalar, optionKey, scalarSize, typeName } from "../model.js";
4
- import { U64, BOOL, cString, fixedVecC, helperSignature, optC, scalarC, scalarStorageC, storageDecl, valueC, } from "./shared.js";
3
+ import { INT_INFO, isScalar, optionKey, sameType, scalarSize, typeName } from "../model.js";
4
+ import { U64, BOOL, PUBKEY, cString, fixedVecC, helperSignature, optC, scalarC, scalarStorageC, storageDecl, valueC, } from "./shared.js";
5
5
  import { CpiEmitter } from "./cpi.js";
6
6
  import { cTokens, declaredNames, isGlobalName, parameterDecls, usedNames } from "./outline.js";
7
7
  /**
@@ -236,7 +236,8 @@ export class StatementEmitter extends CpiEmitter {
236
236
  if (ts.isVariableDeclarationList(init))
237
237
  this.variable(init);
238
238
  else
239
- this.expressionStatement(init, false);
239
+ for (const e of commaList(init))
240
+ this.expressionStatement(e, false);
240
241
  }
241
242
  this.loop(stmt.condition, stmt.statement, stmt.incrementor);
242
243
  });
@@ -258,6 +259,8 @@ export class StatementEmitter extends CpiEmitter {
258
259
  this.fail(stmt.expression, "iterate remaining accounts with for (let i = 0n; i < rest.length; i++) and rest.get(i)");
259
260
  if (ts.isArrayLiteralExpression(stmt.expression) && this.functionList(stmt.expression))
260
261
  return this.forOfFunctions(stmt, d.name);
262
+ if (this.treeForOf(stmt, d))
263
+ return;
261
264
  // Synthetic `list.length` / `list.get(i)` nodes placed at the loop, so errors and checks point at the source.
262
265
  const f = ts.factory;
263
266
  const index = `__of${this.temp++}`;
@@ -284,6 +287,87 @@ export class StatementEmitter extends CpiEmitter {
284
287
  this.loops.pop();
285
288
  });
286
289
  }
290
+ /**
291
+ * `for (const e of tree)` / `for (const e of tree.reversed())` over a RedBlackTree: lib-sokoban's in-order
292
+ * iterator (a stack of nodes, left registers down, then the right one), smallest key first or, reversed, largest
293
+ * first. `e` is the node (`e.key`, `e.value`, `e.index`), each read where it lies. The body may change values
294
+ * but not the tree's structure (insert / remove / initialize on it are compile errors, as Rust's borrow forbids).
295
+ */
296
+ treeForOf(stmt, d) {
297
+ let src = stmt.expression;
298
+ while (ts.isParenthesizedExpression(src))
299
+ src = src.expression;
300
+ let reversed = false;
301
+ if (ts.isCallExpression(src) &&
302
+ ts.isPropertyAccessExpression(src.expression) &&
303
+ src.expression.name.text === "reversed" &&
304
+ this.treeOf(src.expression.expression)) {
305
+ if (src.arguments.length)
306
+ this.fail(src, "reversed() takes no arguments");
307
+ reversed = true;
308
+ src = src.expression.expression;
309
+ }
310
+ const tree = this.treeOf(src);
311
+ if (!tree)
312
+ return false;
313
+ const t = tree.local.c;
314
+ const S = tree.inst.stride;
315
+ const [down, next] = reversed ? ["TS_RBT_RIGHT", "TS_RBT_LEFT"] : ["TS_RBT_LEFT", "TS_RBT_RIGHT"];
316
+ const stack = this.tmp("rbs");
317
+ const sp = this.tmp("rbsp");
318
+ const ptr = this.tmp("rbp");
319
+ const cur = this.tmp("rbc");
320
+ const e = this.tmp("rbe");
321
+ const label = this.tmp("ts_continue_");
322
+ const release = this.iterationClaims(stmt.statement);
323
+ this.line(`{`);
324
+ this.block(() => {
325
+ // The stack is walked with a pointer (no index arithmetic per step).
326
+ this.line(`uint32_t ${stack}[TS_RBT_STACK];`);
327
+ this.line(`uint32_t *${sp} = ${stack};`);
328
+ this.line(`uint32_t ${ptr} = TS_RBT_ROOT(${t}.base);`);
329
+ this.line(`while (1) {`);
330
+ this.block(() => {
331
+ // Each node's index is checked against the capacity once, when the walk steps onto it (the same panic, at the
332
+ // same point, as sokoban's indexing); popping it again reads its registers without a second check.
333
+ this.line(`while (${ptr} != 0) {`);
334
+ this.line(` if (${sp} == ${stack} + TS_RBT_STACK) ts_rbt_too_deep();`);
335
+ this.line(` *${sp}++ = ${ptr};`);
336
+ this.line(` ${ptr} = ((ts_u32_unaligned *)ts_rbt_node(&${t}, ${S}, ${ptr}))[${down}];`);
337
+ this.line(`}`);
338
+ this.line(`if (${sp} == ${stack}) break;`);
339
+ this.line(`uint32_t ${cur} = *--${sp};`);
340
+ this.line(`TsRbtEntry ${e} = {ts_rbt_node_checked(&${t}, ${S}, ${cur}), ${cur}};`);
341
+ // sokoban reads the next pointer when it yields the node, before the caller sees it.
342
+ this.line(`${ptr} = ((ts_u32_unaligned *)${e}.node)[${next}];`);
343
+ this.scopes.at(-1).set(d.name.text, {
344
+ c: e,
345
+ type: { kind: "rbEntry", inst: tree.inst.key, writable: tree.writable },
346
+ mutable: false,
347
+ paths: [`@${t}[]`],
348
+ decl: d,
349
+ });
350
+ const walking = !this.iteratingTrees.has(t);
351
+ this.iteratingTrees.set(t, { name: src.getText(), acct: tree.local.viewAcct ?? "?" });
352
+ this.loops.push(label);
353
+ try {
354
+ this.line(`{`);
355
+ this.block(() => this.body(stmt.statement));
356
+ this.line(`}`);
357
+ }
358
+ finally {
359
+ this.loops.pop();
360
+ if (walking)
361
+ this.iteratingTrees.delete(t);
362
+ }
363
+ this.line(`${label}:;`);
364
+ release();
365
+ });
366
+ this.line(`}`);
367
+ });
368
+ this.line(`}`);
369
+ return true;
370
+ }
287
371
  /** The functions a list literal names (`[f, g]`: closures, helpers or choices), or undefined when it holds anything else. */
288
372
  functionList(list) {
289
373
  if (!list.elements.length)
@@ -835,7 +919,7 @@ export class StatementEmitter extends CpiEmitter {
835
919
  this.checkLocalListSize(t, init, "the new list");
836
920
  this.model.localVecs.set(fixedVecC(t), t);
837
921
  const pad = " ".repeat(this.indent);
838
- this.lines[declAt] = `${pad}${fixedVecC(t)} ${c};\n${pad}ts_memzero(&${c}, sizeof(${c}));`;
922
+ this.lines[declAt] = `${pad}${fixedVecC(t)} ${c};\n${pad}ts_memzero_bulk(&${c}, sizeof(${c}));`;
839
923
  return t;
840
924
  }
841
925
  /** The element type of a Vec, FixedArray, FixedVec or Vec argument. */
@@ -887,8 +971,10 @@ export class StatementEmitter extends CpiEmitter {
887
971
  this.loops.pop();
888
972
  this.line(`${label}:;`);
889
973
  release();
974
+ // `i++, j--`: each update in order, all after the `continue` label.
890
975
  if (step)
891
- this.expressionStatement(step, false);
976
+ for (const e of commaList(step))
977
+ this.expressionStatement(e, false);
892
978
  });
893
979
  this.line(`}`);
894
980
  }
@@ -898,6 +984,53 @@ export class StatementEmitter extends CpiEmitter {
898
984
  * was declared with, so a block around the call that declares the same name does not change what it reads, and
899
985
  * writes to captured `let`s are seen by the enclosing function. Returns the result (undefined for no value).
900
986
  */
987
+ /**
988
+ * An `Inout<T>` parameter of a function expanded where it is called: a pointer to the caller's place (a struct,
989
+ * FixedArray or FixedVec), which must be writable, bound as a reference local.
990
+ */
991
+ inoutBinding(p, arg, calleeScope, fnName) {
992
+ const inner = p.type.typeArguments?.[0];
993
+ if (!inner || p.type.typeArguments.length !== 1)
994
+ this.fail(p.type, "Inout<T> takes one type: a struct, FixedArray<T, N> or FixedVec<T, N>");
995
+ const saved = this.scope;
996
+ this.scope = calleeScope;
997
+ let list;
998
+ let struct;
999
+ try {
1000
+ list = this.listAnnotation(inner);
1001
+ const sn = list ? undefined : structNameOf(inner, calleeScope);
1002
+ struct = sn && this.model.structs.has(sn) ? sn : undefined;
1003
+ }
1004
+ finally {
1005
+ this.scope = saved;
1006
+ }
1007
+ const name = p.name.text;
1008
+ const c2 = `l_${name}_${this.temp++}`;
1009
+ const extra = { paths: this.pathsOf(arg), decl: p, ...(this.throughMovableList(arg) ? { movable: true } : {}) };
1010
+ if (struct) {
1011
+ const place = this.structPlace(arg);
1012
+ if (!place || place.struct !== struct)
1013
+ this.fail(arg, `${fnName}() takes ${name} as Inout<${struct}>: pass a ${struct} place of yours (a local, a field, a list element)`);
1014
+ if (!place.writable)
1015
+ this.fail(arg, `${fnName}() changes ${name} (Inout), and this place is read-only`);
1016
+ this.line(`TSS_${struct} *${c2} = ${place.ptr};`);
1017
+ return { c: c2, type: { kind: "structRef", struct, writable: true }, mutable: false, ...extra };
1018
+ }
1019
+ if (!list)
1020
+ this.fail(inner, `Inout<${inner.getText()}>: Inout<T> takes a struct of fixed size, a FixedArray<T, N> or a FixedVec<T, N>`);
1021
+ const r = this.ref(arg);
1022
+ if (!r || !sameType(r.type, list))
1023
+ this.fail(arg, `${fnName}() takes ${name} as Inout<${typeName(list)}>: pass a ${typeName(list)} of yours`);
1024
+ if (!r.writable)
1025
+ this.fail(arg, `${fnName}() changes ${name} (Inout): ${this.readOnly(r)}`);
1026
+ if (list.kind === "vec") {
1027
+ this.model.localVecs.set(fixedVecC(list), list);
1028
+ this.line(`${fixedVecC(list)} *${c2} = &${r.lv};`);
1029
+ }
1030
+ else
1031
+ this.line(`${storageDecl(list, `(*${c2})`)} = &${r.lv};`);
1032
+ return { c: `(*${c2})`, type: list, mutable: false, ...extra };
1033
+ }
901
1034
  expandClosure(c, args, node, into) {
902
1035
  const fn = c.node;
903
1036
  if (this.inlining.has(fn))
@@ -919,6 +1052,11 @@ export class StatementEmitter extends CpiEmitter {
919
1052
  params.set(name, { c: "", type: BOOL, mutable: false, closure: this.closureOf(arg) });
920
1053
  return;
921
1054
  }
1055
+ // `Inout<T>` (a helper expanded here because it was given a closure): the caller's place, by reference.
1056
+ if (p.type && typesolName(p.type, calleeScope.imports) === "Inout") {
1057
+ params.set(name, this.inoutBinding(p, arg, calleeScope, c.name));
1058
+ return;
1059
+ }
922
1060
  const passed = ts.isIdentifier(arg) && this.lookup(arg.text) ? undefined : this.accountAt(arg);
923
1061
  if (p.type && passed && !resolveValueType(p.type, calleeScope)) {
924
1062
  aliases.set(name, passed);
@@ -934,6 +1072,7 @@ export class StatementEmitter extends CpiEmitter {
934
1072
  type: { kind: "structRef", struct: place.struct, writable: place.writable },
935
1073
  mutable: false,
936
1074
  paths: this.pathsOf(arg),
1075
+ ...(this.throughMovableList(arg) ? { movable: true } : {}),
937
1076
  decl: p,
938
1077
  });
939
1078
  return;
@@ -1331,6 +1470,10 @@ export class StatementEmitter extends CpiEmitter {
1331
1470
  this.destructure(list, d, d.name, d.initializer, topLevel);
1332
1471
  continue;
1333
1472
  }
1473
+ if (ts.isArrayBindingPattern(d.name)) {
1474
+ this.addressAndBump(d, d.name, mutable);
1475
+ continue;
1476
+ }
1334
1477
  if (!ts.isIdentifier(d.name) || !d.initializer)
1335
1478
  this.fail(d, "declare one plain name with an initializer");
1336
1479
  // A local function is a helper of its own (lifted when the program was analyzed): nothing to run here.
@@ -1357,6 +1500,13 @@ export class StatementEmitter extends CpiEmitter {
1357
1500
  this.fail(d.name, `"${name}" shadows the parameter "${name}"; use another name`);
1358
1501
  const c = `l_${name}_${this.temp++}`;
1359
1502
  const init = d.initializer;
1503
+ // `/** @heap */` names a list or struct type (checked again where such locals are made).
1504
+ if ([d, d.parent?.parent].some((n) => n && ts.getJSDocTags(n).some((t) => t.tagName.text === "heap")) &&
1505
+ !(d.type && (["FixedVec", "FixedArray"].includes(typesolName(d.type, this.scope.imports) ?? "") || structNameOf(d.type, this.scope))))
1506
+ this.heapLocal(d, false);
1507
+ // Run-time offset views (loadRawAt, rawArrayAt, rbTreeAt) and references into a tree's nodes (views.ts).
1508
+ if (this.bindView(d, init, name, c, mutable))
1509
+ continue;
1360
1510
  // A function as a value: another name for one (`const h = g`), or the one a function returns (`adder(5n)`).
1361
1511
  const made = ts.isCallExpression(init) ? this.madeFunction(init) : undefined;
1362
1512
  const alias = ts.isIdentifier(init) ? this.functionNamed(init) : undefined;
@@ -1374,6 +1524,8 @@ export class StatementEmitter extends CpiEmitter {
1374
1524
  continue;
1375
1525
  }
1376
1526
  const fn = ts.isCallExpression(init) ? this.exportName(init.expression) : undefined;
1527
+ if (d.type && typesolName(d.type, this.scope.imports) === "Inout")
1528
+ this.fail(d.type, "Inout<T> is for helper parameters; a local needs none (const r = acct.rec refers to that place and changes it, const copy: Rec = acct.rec is a copy)");
1377
1529
  // The instruction's data as sent, discriminator included (a @fallback's input): a list of u8.
1378
1530
  if (fn === "instructionData") {
1379
1531
  if (init.arguments.length)
@@ -1438,7 +1590,16 @@ export class StatementEmitter extends CpiEmitter {
1438
1590
  if (h)
1439
1591
  loaded = { handle: h, struct: t.type.struct, mut: fn === "loadAccountMut" };
1440
1592
  }
1441
- this.scopes.at(-1).set(name, { c, type: t.type, mutable: false, paths: [`@${c}`], decl: d, loaded, ...(t.bigCap ? { bigCap: t.bigCap } : {}) });
1593
+ this.scopes.at(-1).set(name, {
1594
+ c,
1595
+ type: t.type,
1596
+ mutable: false,
1597
+ paths: [`@${c}`],
1598
+ decl: d,
1599
+ loaded,
1600
+ ...(fn === "loadRaw" || fn === "loadRawMut" ? { view: true, viewAcct: this.viewAccountKey(init.arguments[0]) } : {}),
1601
+ ...(t.bigCap ? { bigCap: t.bigCap } : {}),
1602
+ });
1442
1603
  continue;
1443
1604
  }
1444
1605
  // A local decoded from an account's Borsh bytes: `const pool = loadBorsh<StakePool>(acct)` (a copy, as Rust's).
@@ -1486,35 +1647,59 @@ export class StatementEmitter extends CpiEmitter {
1486
1647
  this.line(l.trim());
1487
1648
  this.line(`TSS_${S.name} *${c} = &${c}__v;`);
1488
1649
  }
1489
- this.scopes.at(-1).set(name, { c, type: { kind: "structRef", struct: S.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d });
1650
+ // A copy of the return data: never account data (owned).
1651
+ this.scopes
1652
+ .at(-1)
1653
+ .set(name, { c, type: { kind: "structRef", struct: S.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d, owned: true });
1490
1654
  continue;
1491
1655
  }
1492
1656
  // A local list declared with its type: `const metas: FixedVec<Meta, 4> = fixedVec([{ pubkey, isSigner, … }])`,
1493
1657
  // `const buf: FixedVec<u8, 600> = fixedVec([])`, or a copy of another list (a Vec argument, instruction data).
1494
1658
  const listType = d.type ? this.listAnnotation(d.type) : undefined;
1659
+ // Struct values: `const p: Point = { x, y }` (or a copy of another Point) is a local of its own.
1660
+ const structType = d.type && structNameOf(d.type, this.scope) ? this.model.structs.get(structNameOf(d.type, this.scope)) : undefined;
1661
+ // `/** @heap */`: the local lives on the heap instead of the 4 KiB stack frame.
1662
+ const heap = this.heapLocal(d, !!listType || !!structType);
1495
1663
  if (listType) {
1496
- this.checkLocalListSize(listType, d.type);
1497
- if (listType.kind === "vec") {
1664
+ if (heap)
1665
+ this.checkHeapRoom(this.fieldBytes(listType), d.type);
1666
+ else
1667
+ this.checkLocalListSize(listType, d.type, undefined, true);
1668
+ let lv = c;
1669
+ if (listType.kind === "vec")
1498
1670
  this.model.localVecs.set(fixedVecC(listType), listType);
1499
- this.line(`${fixedVecC(listType)} ${c};`);
1500
- this.line(`ts_memzero(&${c}, sizeof(${c}));`);
1671
+ if (heap) {
1672
+ // One allocation per declaration and instruction (a loop reuses it): the heap is never freed.
1673
+ this.hoistLazy(c, (n) => (listType.kind === "vec" ? `${fixedVecC(listType)} *${n}` : storageDecl(listType, `(*${n})`)));
1674
+ this.line(`if (${c} == NULL) TS_TRY(ts_alloc(sizeof(*${c}), (uint8_t **)&${c}));`);
1675
+ lv = `(*${c})`;
1501
1676
  }
1502
1677
  else
1503
- this.line(`${storageDecl(listType, c)};`);
1504
- this.writeAggregate({ lv: c, type: listType, writable: true }, init, true);
1505
- this.scopes.at(-1).set(name, { c, type: listType, mutable });
1678
+ this.line(listType.kind === "vec" ? `${fixedVecC(listType)} ${c};` : `${storageDecl(listType, c)};`);
1679
+ // A literal zeroes its own free slots; anything else (a copy of another list) may fill only the first ones.
1680
+ if (listType.kind === "vec" && !this.isListLiteral(init))
1681
+ this.line(`ts_memzero_bulk(&${lv}, sizeof(${lv}));`);
1682
+ this.writeAggregate({ lv, type: listType, writable: true }, init, true);
1683
+ this.scopes.at(-1).set(name, { c: lv, type: listType, mutable });
1506
1684
  continue;
1507
1685
  }
1508
- // Struct values: `const p: Point = { x, y }` (or a copy of another Point) is a local of its own.
1509
- const structType = d.type && structNameOf(d.type, this.scope) ? this.model.structs.get(structNameOf(d.type, this.scope)) : undefined;
1510
1686
  if (structType) {
1511
1687
  if (mutable)
1512
1688
  this.fail(d, "bind struct values with const (their fields can still be updated)");
1513
1689
  if (structType.size === undefined || structType.vec)
1514
1690
  this.fail(d.type, `${structType.name} has variable-size fields and cannot be a local`);
1515
- this.line(`TSS_${structType.name} ${c}__v;`);
1516
- this.writeAggregate({ lv: `${c}__v`, type: { kind: "struct", name: structType.name }, writable: true }, init, true);
1517
- this.line(`TSS_${structType.name} *${c} = &${c}__v;`);
1691
+ if (heap) {
1692
+ this.checkHeapRoom(structType.size, d.type);
1693
+ this.hoistLazy(`${c}__h`, (n) => `TSS_${structType.name} *${n}`);
1694
+ this.line(`if (${c}__h == NULL) TS_TRY(ts_alloc(sizeof(TSS_${structType.name}), (uint8_t **)&${c}__h));`);
1695
+ this.writeAggregate({ lv: `(*${c}__h)`, type: { kind: "struct", name: structType.name }, writable: true }, init, true);
1696
+ this.line(`TSS_${structType.name} *${c} = ${c}__h;`);
1697
+ }
1698
+ else {
1699
+ this.line(`TSS_${structType.name} ${c}__v;`);
1700
+ this.writeAggregate({ lv: `${c}__v`, type: { kind: "struct", name: structType.name }, writable: true }, init, true);
1701
+ this.line(`TSS_${structType.name} *${c} = &${c}__v;`);
1702
+ }
1518
1703
  this.scopes
1519
1704
  .at(-1)
1520
1705
  .set(name, { c, type: { kind: "structRef", struct: structType.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d, owned: true });
@@ -1561,6 +1746,7 @@ export class StatementEmitter extends CpiEmitter {
1561
1746
  type: { kind: "structRef", struct: target.struct, writable: target.writable },
1562
1747
  mutable: false,
1563
1748
  paths: owned ? [`@${c}`] : this.pathsOf(init),
1749
+ ...(!owned && this.throughMovableList(init) ? { movable: true } : {}),
1564
1750
  decl: d,
1565
1751
  ...(owned ? { owned } : {}),
1566
1752
  });
@@ -1585,6 +1771,18 @@ export class StatementEmitter extends CpiEmitter {
1585
1771
  this.scopes.at(-1).set(name, { c: v.c, type, mutable: false });
1586
1772
  continue;
1587
1773
  }
1774
+ // A tree node reached any other way than `const e = tree.min()` (`c ? t.min() : t.max()`, `t.get(k)!`): it
1775
+ // aliases the tree like the direct form, so it keeps the paths it may name; one whose tree is unknown is refused.
1776
+ if (type.kind === "rbEntry" || (type.kind === "structRef" && type.nullable)) {
1777
+ if (mutable)
1778
+ this.fail(d, "bind a tree node with const: it refers to a node of the tree");
1779
+ const paths = this.pathsOf(init);
1780
+ if (!paths)
1781
+ this.fail(init, "this refers to a node of a tree, and which tree is not clear here: bind the tree's own call to a const (const e = tree.min(), const o = tree.get(key))");
1782
+ this.line(`${valueC(type)} ${c} = ${v.c};`);
1783
+ this.scopes.at(-1).set(name, { c, type, mutable: false, paths, decl: d });
1784
+ continue;
1785
+ }
1588
1786
  if ((type.kind === "account" || type.kind === "structRef") && mutable)
1589
1787
  this.fail(d, "bind accounts with const");
1590
1788
  if (type.kind === "pubkey")
@@ -1596,6 +1794,69 @@ export class StatementEmitter extends CpiEmitter {
1596
1794
  this.scopes.at(-1).set(name, { c, type, mutable, ...(owned ? { paths: [`@${c}`], owned } : {}) });
1597
1795
  }
1598
1796
  }
1797
+ /**
1798
+ * Whether a declaration is `/** @heap *\/`: a local list or struct kept on the heap (the bump allocator) rather
1799
+ * than in the function's 4 KiB stack frame. Only in an instruction, which runs once per instruction: a helper may
1800
+ * run any number of times and the heap is never freed.
1801
+ */
1802
+ heapLocal(d, aggregate) {
1803
+ const tag = [d, d.parent?.parent].flatMap((n) => (n ? ts.getJSDocTags(n) : [])).find((t) => t.tagName.text === "heap");
1804
+ if (!tag)
1805
+ return false;
1806
+ if (!aggregate)
1807
+ this.fail(d, "@heap is for a local list or struct declared with its type (const buf: FixedVec<u8, 1024> = …)");
1808
+ if (this.helper)
1809
+ this.fail(d, "@heap locals belong to instructions: a helper may run many times per instruction and the heap is never freed; declare it in the instruction and pass it (Inout<T>)");
1810
+ return true;
1811
+ }
1812
+ /** A `@heap` local must fit in the heap (32 KiB, or HEAP_SIZE_KIB), which other allocations share. */
1813
+ checkHeapRoom(bytes, at) {
1814
+ const kib = this.model.constants.get("HEAP_SIZE_KIB")?.value;
1815
+ const room = (typeof kib === "bigint" ? Number(kib) : 32) * 1024 - 8;
1816
+ if (bytes > room)
1817
+ this.fail(at, `this local takes ${bytes} bytes and the heap holds ${room} (raise HEAP_SIZE_KIB, at most 256)`);
1818
+ }
1819
+ /**
1820
+ * `const [address, bump] = findProgramAddressWithBump(seeds, program)`: Rust's `let (address, bump) =
1821
+ * Pubkey::find_program_address(…)`, both from one search (the only array destructuring the language has).
1822
+ */
1823
+ addressAndBump(d, pattern, mutable) {
1824
+ const init = d.initializer;
1825
+ const call = init && ts.isCallExpression(init) && this.exportName(init.expression) === "findProgramAddressWithBump" ? init : undefined;
1826
+ if (!call)
1827
+ this.fail(d.name, "array destructuring is only for const [address, bump] = findProgramAddressWithBump(seeds, program)");
1828
+ if (mutable)
1829
+ this.fail(d, "bind them with const: const [address, bump] = findProgramAddressWithBump(seeds, program)");
1830
+ if (d.type)
1831
+ this.fail(d.type, "leave the type out: the address is a Pubkey and the bump a u8");
1832
+ if (pattern.elements.length > 2)
1833
+ this.fail(pattern, "findProgramAddressWithBump gives two values: const [address, bump] = …");
1834
+ const names = pattern.elements.map((el) => {
1835
+ if (ts.isOmittedExpression(el))
1836
+ return undefined;
1837
+ if (el.dotDotDotToken || el.initializer || !ts.isIdentifier(el.name))
1838
+ this.fail(el, "name the address and the bump: const [address, bump] = findProgramAddressWithBump(seeds, program)");
1839
+ const name = el.name.text;
1840
+ if (this.scopes.at(-1).has(name))
1841
+ this.fail(el.name, `"${name}" is already declared`);
1842
+ if (this.accounts.has(name) || this.args.has(name) || this.isGroup(name))
1843
+ this.fail(el.name, `"${name}" shadows the parameter "${name}"; use another name`);
1844
+ return name;
1845
+ });
1846
+ if (call.arguments.length !== 2)
1847
+ this.fail(call, "findProgramAddressWithBump(seeds, program) takes the seeds and the program's address");
1848
+ const seeds = this.seeds(call.arguments[0], 0);
1849
+ const program = this.expect(this.expr(call.arguments[1], PUBKEY), PUBKEY, call.arguments[1]);
1850
+ const [address, bump] = names;
1851
+ const key = address ? `l_${address}_${this.temp++}` : this.tmp("pda");
1852
+ const b = bump ? `l_${bump}_${this.temp++}` : this.tmp("bump");
1853
+ this.line(`SolPubkey ${key}; uint8_t ${b};`);
1854
+ this.line(`if (ts_find_pda(${seeds.name}, ${seeds.count}, ${program.c}, &${key}, &${b}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no program address for these seeds");`);
1855
+ if (address)
1856
+ this.scopes.at(-1).set(address, { c: key, type: PUBKEY, mutable: false });
1857
+ if (bump)
1858
+ this.scopes.at(-1).set(bump, { c: b, type: { kind: "int", name: "u8" }, mutable: false });
1859
+ }
1599
1860
  /**
1600
1861
  * `const { a, b: c } = s`: one declaration per name, `const a = s.a`, in source order. The source must be a name or
1601
1862
  * a field path (no calls), so reading it once per name reads the same thing JS reads once.
@@ -1773,3 +2034,11 @@ export class StatementEmitter extends CpiEmitter {
1773
2034
  this.line(place.write(value.c) + ";");
1774
2035
  }
1775
2036
  }
2037
+ /** The expressions of a comma list (`i++, j--` in a for loop's update or initializer), left to right. */
2038
+ function commaList(e) {
2039
+ while (ts.isParenthesizedExpression(e))
2040
+ e = e.expression;
2041
+ if (ts.isBinaryExpression(e) && e.operatorToken.kind === ts.SyntaxKind.CommaToken)
2042
+ return [...commaList(e.left), ...commaList(e.right)];
2043
+ return [e];
2044
+ }
@@ -29,11 +29,13 @@ export declare abstract class StorageEmitter extends AliasEmitter {
29
29
  protected looksLikeStructPlace(node: ts.Expression): boolean;
30
30
  /**
31
31
  * A local list lives in the function's stack frame (4 KiB on SBPF v0, shared with every other local and the helpers
32
- * clang inlines): one list may take at most 2 KiB, so the failure is a clear compile error, not clang's frame error.
32
+ * clang inlines): one list's elements may take at most 2 KiB, so the failure is a clear compile error, not clang's
33
+ * frame error. A FixedVec's u32 length is not counted: `FixedVec<u32, 512>` (2,052 bytes) is 2 KiB of elements, and
34
+ * a frame that then overflows is reported by the frame check, which names the biggest locals.
33
35
  */
34
36
  protected checkLocalListSize(t: FieldType & {
35
37
  kind: "vec" | "array";
36
- }, at: ts.Node, what?: string): void;
38
+ }, at: ts.Node, what?: string, declared?: boolean): void;
37
39
  /**
38
40
  * `FixedVec<T, N>` / `FixedArray<T, N>` written as a local's type: T an integer, boolean, Pubkey, enum,
39
41
  * `FixedString<N>` or fixed-size struct, N a literal. Undefined for other types; a list type with anything else fails.
@@ -79,11 +81,28 @@ export declare abstract class StorageEmitter extends AliasEmitter {
79
81
  */
80
82
  /** A whole struct account copied as a value (`return vault`, `info = vault`): fixed-size structs only. */
81
83
  private wholeAccount;
84
+ /**
85
+ * A data enum literal (`{ kind: "Variant", … }`), checked: its variant, and `writeFields(base)`, which evaluates the
86
+ * fields in source order (as JS does) into `${base}.<field>`, a `TSV_<Enum>__<Variant>` place (or, given a function,
87
+ * into the place it names for each field).
88
+ */
89
+ protected dataEnumLiteral(name: string, valueNode: ts.ObjectLiteralExpression): {
90
+ e: import("../model.js").DataEnumDef;
91
+ vi: number;
92
+ variant: {
93
+ name: string;
94
+ fields: import("../model.js").StructField[];
95
+ size: number;
96
+ };
97
+ writeFields: (base: string | ((field: string) => string)) => void;
98
+ };
82
99
  /**
83
100
  * Write an aggregate value into `target`. `fresh`: the target is a value just declared (or a temporary), which no
84
101
  * expression can read yet, so a literal is built in it directly rather than in a temporary first.
85
102
  */
86
103
  protected writeAggregate(target: Ref, valueNode: ts.Expression, fresh?: boolean): void;
104
+ /** `fixedVec([…])` or `[…]`: a list literal, which writeAggregate builds in a fresh target with its free slots zeroed. */
105
+ protected isListLiteral(node: ts.Expression): boolean;
87
106
  /** The Vec view of a FixedVec stored at `lv` (`{ len, items[cap] }`). */
88
107
  protected fixedVec(lv: string, elem: FieldType, cap: number): NonNullable<Ref["vec"]>;
89
108
  /** A heap Vec (a Vec<T> in a `@layout borsh` struct) at `lv`: `{ len, cap, items }`, grown by ts_hvec_reserve. */
@@ -103,6 +122,8 @@ export declare abstract class StorageEmitter extends AliasEmitter {
103
122
  protected peekArray(node: ts.Expression): boolean;
104
123
  /** The kind of storage an expression names (struct, array, dataEnum…), without emitting code or failing. */
105
124
  protected peekKind(node: ts.Expression): FieldType["kind"] | undefined;
125
+ /** The type of the storage an expression names, without emitting code or failing. */
126
+ protected peekType(node: ts.Expression): FieldType | undefined;
106
127
  protected place(node: ts.Expression): {
107
128
  type: ValueType;
108
129
  read: string;