@typesol/cli 0.49.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 (79) hide show
  1. package/CHANGELOG.md +541 -0
  2. package/NOTICE +9 -0
  3. package/README.md +34 -15
  4. package/SECURITY.md +6 -3
  5. package/dist/cli.js +36 -5
  6. package/dist/compiler/analyze.d.ts +10 -1
  7. package/dist/compiler/analyze.js +234 -20
  8. package/dist/compiler/diagnostics.d.ts +4 -0
  9. package/dist/compiler/diagnostics.js +5 -1
  10. package/dist/compiler/emit/base.d.ts +35 -4
  11. package/dist/compiler/emit/base.js +46 -4
  12. package/dist/compiler/emit/borsh.js +8 -8
  13. package/dist/compiler/emit/calls.d.ts +6 -0
  14. package/dist/compiler/emit/calls.js +98 -18
  15. package/dist/compiler/emit/cpi-core.d.ts +3 -0
  16. package/dist/compiler/emit/cpi-core.js +11 -5
  17. package/dist/compiler/emit/cpi.js +6 -4
  18. package/dist/compiler/emit/create.js +9 -9
  19. package/dist/compiler/emit/expressions.d.ts +9 -1
  20. package/dist/compiler/emit/expressions.js +77 -0
  21. package/dist/compiler/emit/function.d.ts +2 -0
  22. package/dist/compiler/emit/function.js +71 -15
  23. package/dist/compiler/emit/outline.d.ts +35 -0
  24. package/dist/compiler/emit/outline.js +547 -0
  25. package/dist/compiler/emit/program.js +19 -4
  26. package/dist/compiler/emit/rbtree.js +1 -1
  27. package/dist/compiler/emit/shared.d.ts +69 -4
  28. package/dist/compiler/emit/shared.js +44 -9
  29. package/dist/compiler/emit/statements.d.ts +36 -2
  30. package/dist/compiler/emit/statements.js +332 -29
  31. package/dist/compiler/emit/storage.d.ts +16 -0
  32. package/dist/compiler/emit/storage.js +134 -13
  33. package/dist/compiler/emit/views.js +1 -1
  34. package/dist/compiler/hints.d.ts +1 -1
  35. package/dist/compiler/hints.js +9 -1
  36. package/dist/compiler/idl.js +1 -1
  37. package/dist/compiler/index.d.ts +30 -2
  38. package/dist/compiler/index.js +94 -16
  39. package/dist/compiler/model.d.ts +13 -1
  40. package/dist/compiler/stack.d.ts +71 -0
  41. package/dist/compiler/stack.js +309 -0
  42. package/dist/compiler/toolchain.d.ts +87 -5
  43. package/dist/compiler/toolchain.js +384 -19
  44. package/dist/keys.d.ts +12 -1
  45. package/dist/keys.js +57 -7
  46. package/dist/workspace.d.ts +9 -0
  47. package/dist/workspace.js +91 -16
  48. package/docker/deps/0.50.0.lock.json +1206 -0
  49. package/docker/deps/0.51.0.lock.json +1206 -0
  50. package/docs/architecture.md +1 -1
  51. package/docs/audit.md +16 -13
  52. package/docs/case-study-escrow.md +1 -1
  53. package/docs/case-study-jito-mev.md +14 -14
  54. package/docs/case-study-marginfi.md +127 -127
  55. package/docs/case-study-multisig.md +16 -4
  56. package/docs/case-study-raydium-clmm.md +44 -28
  57. package/docs/case-study-raydium-cp-swap.md +18 -18
  58. package/docs/cli.md +5 -4
  59. package/docs/glossary.md +2 -1
  60. package/docs/language-accounts.md +16 -10
  61. package/docs/language-basics.md +29 -2
  62. package/docs/language-builtins.md +4 -2
  63. package/docs/language-cpi.md +34 -0
  64. package/docs/language-native.md +50 -4
  65. package/docs/language-pdas.md +6 -2
  66. package/docs/language-statements.md +103 -12
  67. package/docs/language-types.md +93 -8
  68. package/docs/runtime.md +20 -3
  69. package/docs/security-model.md +6 -3
  70. package/docs/stability.md +10 -5
  71. package/docs/testing.md +6 -2
  72. package/docs/troubleshooting.md +45 -1
  73. package/lib/typesol.d.ts +25 -3
  74. package/llms-full.txt +403 -54
  75. package/package.json +1 -1
  76. package/releases/0.49.0.json +857 -0
  77. package/releases/0.50.0.json +874 -0
  78. package/runtime/typesol_builtins.c +47 -2
  79. package/runtime/typesol_rt.h +254 -54
@@ -1,12 +1,23 @@
1
1
  import ts from "typescript";
2
- import { MAX_RETURN_DATA, calleeName, resolveScalarType, resolveValueType, structNameOf, typesolName } from "../analyze.js";
2
+ import { MAX_RETURN_DATA, calleeName, resolveScalarType, resolveValueType, structNameOf, typesolName, unsupportedTypeForm, } from "../analyze.js";
3
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";
4
+ import { STRING, U64, BOOL, PUBKEY, cString, fitSuffix, fixedVecC, helperSignature, optC, scalarC, scalarStorageC, storageDecl, valueC, } from "./shared.js";
5
+ import { Bail } from "../diagnostics.js";
5
6
  import { CpiEmitter } from "./cpi.js";
6
- import { cTokens, declaredNames, isGlobalName, parameterDecls, usedNames } from "./outline.js";
7
+ import { SCOPE_MARK, cTokens, declaredNames, isGlobalName, parameterDecls, usedNames } from "./outline.js";
7
8
  /**
8
9
  * Statements: variables, assignment, control flow and return.
9
10
  */
11
+ /** The statements that get a C block of their own under StackPlan.scope: every kind that declares no name of the program. */
12
+ const scopedStatement = (s) => ts.isExpressionStatement(s) ||
13
+ ts.isIfStatement(s) ||
14
+ ts.isSwitchStatement(s) ||
15
+ ts.isForStatement(s) ||
16
+ ts.isForOfStatement(s) ||
17
+ ts.isWhileStatement(s) ||
18
+ ts.isDoStatement(s) ||
19
+ ts.isReturnStatement(s) ||
20
+ ts.isLabeledStatement(s);
10
21
  /** The built-ins that return whether a proof or signature holds, and fail nothing by themselves. */
11
22
  const VERIFIERS = new Set(["merkleVerify", "verifyEd25519", "verifySecp256k1"]);
12
23
  /** A proof or signature check whose result decides nothing: `how` says why (discarded, never read, an empty if). */
@@ -20,13 +31,54 @@ export class StatementEmitter extends CpiEmitter {
20
31
  this.line(`sol_log(${cString(`ts:${this.where}`)});`);
21
32
  this.line(`sol_log_compute_units();`);
22
33
  }
34
+ // A statement using a name whose declaration failed is skipped: that error explains it.
35
+ if (this.brokenDecls.size && this.usesBrokenName(stmt)) {
36
+ this.where = outer;
37
+ return;
38
+ }
23
39
  try {
24
- this.statementInner(stmt, topLevel);
40
+ // To fit the stack (StackPlan.scope), each statement that declares no name of the program gets a C block of its
41
+ // own, so clang can give the temporaries of different statements one slot. Blocks whose names are used after
42
+ // them are taken out again when the function is done (settleScopes).
43
+ if (this.scopeTemps && scopedStatement(stmt)) {
44
+ const n = ++this.scopeBlocks;
45
+ // The mark goes before the brace: read as C tokens (outlinedLoop), a comment is a lone 0, and a declaration
46
+ // right after a brace must still start a statement.
47
+ this.line(`/*${SCOPE_MARK}${n}{*/ {`);
48
+ try {
49
+ this.block(() => this.statementInner(stmt, topLevel));
50
+ }
51
+ finally {
52
+ this.line(`/*${SCOPE_MARK}${n}}*/ }`);
53
+ }
54
+ }
55
+ else
56
+ this.statementInner(stmt, topLevel);
57
+ }
58
+ catch (e) {
59
+ if (e instanceof Bail && ts.isVariableStatement(stmt))
60
+ for (const d of stmt.declarationList.declarations)
61
+ this.brokenDecls.add(d);
62
+ throw e;
25
63
  }
26
64
  finally {
27
65
  this.where = outer;
28
66
  }
29
67
  }
68
+ /** Declarations that failed (a refused const, a nested function declaration): later uses are not reported again. */
69
+ brokenDecls = new Set();
70
+ usesBrokenName(stmt) {
71
+ const visit = (n) => {
72
+ if (ts.isIdentifier(n)) {
73
+ const sym = this.checker.getSymbolAtLocation(n);
74
+ const decl = sym?.valueDeclaration ?? sym?.declarations?.[0];
75
+ if (decl && this.brokenDecls.has(decl))
76
+ return true;
77
+ }
78
+ return !!ts.forEachChild(n, visit);
79
+ };
80
+ return visit(stmt);
81
+ }
30
82
  statementInner(stmt, topLevel) {
31
83
  if (ts.isVariableStatement(stmt))
32
84
  return this.variable(stmt.declarationList, topLevel);
@@ -64,14 +116,25 @@ export class StatementEmitter extends CpiEmitter {
64
116
  return this.forOf(stmt);
65
117
  if (ts.isWhileStatement(stmt))
66
118
  return this.loop(stmt.expression, stmt.statement, undefined);
119
+ if (ts.isLabeledStatement(stmt))
120
+ return this.labeled(stmt);
121
+ if ((ts.isBreakStatement(stmt) || ts.isContinueStatement(stmt)) && stmt.label)
122
+ return this.labeledJump(stmt);
67
123
  if (ts.isBreakStatement(stmt) || ts.isContinueStatement(stmt)) {
68
- if (stmt.label)
69
- this.fail(stmt, "labeled break/continue is not supported");
70
124
  if (!this.loops.length)
71
125
  this.fail(stmt, `${ts.isBreakStatement(stmt) ? "break" : "continue"} outside a loop`);
72
126
  // Inside a switch, `break` leaves the switch (as in JS) and `continue` targets the enclosing loop.
73
127
  if (ts.isContinueStatement(stmt) && !this.loops.at(-1))
74
128
  this.fail(stmt, "continue outside a loop");
129
+ // `break` out of a loop (not out of a switch in it) ends its pass early: the loadAccountMut views it held are
130
+ // dropped first, as the pass's end drops them, so the accounts can be loaded again after the loop.
131
+ if (ts.isBreakStatement(stmt))
132
+ for (let n = stmt.parent; n && !ts.isFunctionLike(n) && !ts.isSwitchStatement(n); n = n.parent)
133
+ if (ts.isIterationStatement(n, false)) {
134
+ for (const slot of this.loopClaims.get(n.statement) ?? [])
135
+ this.line(`ts_release_mut(params, &${slot});`);
136
+ break;
137
+ }
75
138
  this.line(ts.isBreakStatement(stmt) ? `break;` : `goto ${this.loops.at(-1)};`);
76
139
  return;
77
140
  }
@@ -83,7 +146,91 @@ export class StatementEmitter extends CpiEmitter {
83
146
  this.fail(stmt, 'throw is not supported: fail the instruction with require(false, ErrorCode.X) or require(cond, "message")');
84
147
  if (ts.isTryStatement(stmt))
85
148
  this.fail(stmt, "try/catch is not supported: a failed check or CPI aborts the whole instruction, so check first with require(…)");
86
- this.fail(stmt, `${ts.SyntaxKind[stmt.kind]} is not supported in TypeSOL`);
149
+ if (ts.isEmptyStatement(stmt))
150
+ return; // a lone `;`: nothing to do, as in JS
151
+ if (ts.isFunctionDeclaration(stmt)) {
152
+ this.brokenDecls.add(stmt);
153
+ const name = stmt.name?.text ?? "f";
154
+ this.fail(stmt.name ?? stmt, `function declarations inside a function are not supported: write const ${name} = (…): T => { … } (a closure), or declare ${name} at the top level`);
155
+ }
156
+ if (stmt.kind === ts.SyntaxKind.DebuggerStatement)
157
+ this.fail(stmt, "debugger is not supported: a program runs on chain, with no debugger; log values with log(…)");
158
+ if (ts.isClassDeclaration(stmt))
159
+ this.fail(stmt, "classes are not supported: describe account data with an interface and logic with functions");
160
+ if (ts.isWithStatement(stmt))
161
+ this.fail(stmt, "with is not supported: name the value it reads from");
162
+ this.fail(stmt, statementMessage(stmt.kind));
163
+ }
164
+ /**
165
+ * `outer: for (…) { … }` (any loop) or `done: { … }`: the statement, then a C label after it for `break outer`, emitted
166
+ * when a jump uses it. `continue outer` goes to the loop's own `continue` label, so the step of a `for` runs, as in
167
+ * JS.
168
+ */
169
+ labeled(stmt) {
170
+ const inner = stmt.statement;
171
+ const loop = ts.isForStatement(inner) || ts.isForOfStatement(inner) || ts.isWhileStatement(inner) || ts.isDoStatement(inner) ? inner : undefined;
172
+ if (ts.isLabeledStatement(inner))
173
+ this.fail(inner.label, "one label per statement: break and continue name the nearest one");
174
+ if (ts.isForInStatement(inner))
175
+ return this.statement(inner);
176
+ if (!loop && !ts.isBlock(inner))
177
+ this.fail(stmt.label, `a label goes on a loop or a block: ${stmt.label.text}: for (…) { … } (break / continue ${stmt.label.text}) or ${stmt.label.text}: { … } (break ${stmt.label.text})`);
178
+ if (this.labels.some((l) => l.name === stmt.label.text))
179
+ this.fail(stmt.label, `"${stmt.label.text}" already labels an enclosing statement`);
180
+ const entry = { name: stmt.label.text, node: stmt, depth: this.loops.length, brk: this.tmp("ts_break_"), loop, used: false };
181
+ this.labels.push(entry);
182
+ try {
183
+ this.statement(inner);
184
+ }
185
+ finally {
186
+ this.labels.pop();
187
+ }
188
+ if (entry.used)
189
+ this.line(`${entry.brk}:;`);
190
+ }
191
+ /**
192
+ * `break outer` / `continue outer`: a jump to the label after the statement, or to the labeled loop's `continue`
193
+ * label. The views of loadAccountMut held by the loops it leaves are dropped first, as each loop drops them at the end
194
+ * of an iteration.
195
+ */
196
+ labeledJump(stmt) {
197
+ const name = stmt.label.text;
198
+ const entry = [...this.labels].reverse().find((l) => l.name === name);
199
+ const word = ts.isBreakStatement(stmt) ? "break" : "continue";
200
+ if (!entry)
201
+ this.fail(stmt, `${word} ${name}: no enclosing statement is labeled ${name}`);
202
+ if (ts.isContinueStatement(stmt) && !entry.loop)
203
+ this.fail(stmt, `continue ${name}: ${name} labels a block, not a loop; continue goes to a loop`);
204
+ const target = this.loops[entry.depth];
205
+ if (ts.isContinueStatement(stmt) && !target)
206
+ this.fail(stmt, `continue ${name} cannot leave the function it is in`);
207
+ // The loops left: those around the jump up to the labeled one (included for break, whose iteration ends too).
208
+ for (let n = stmt.parent; n && n !== entry.node; n = n.parent) {
209
+ if (ts.isFunctionLike(n))
210
+ break;
211
+ if (ts.isIterationStatement(n, false) && (n !== entry.loop || ts.isBreakStatement(stmt)))
212
+ for (const slot of this.loopClaims.get(n.statement) ?? [])
213
+ this.line(`ts_release_mut(params, &${slot});`);
214
+ }
215
+ if (ts.isBreakStatement(stmt)) {
216
+ entry.used = true;
217
+ this.line(`goto ${entry.brk};`);
218
+ }
219
+ else
220
+ this.line(`goto ${target};`);
221
+ }
222
+ /**
223
+ * Before a `return` from a helper or a closure: the loadAccountMut views of the loops it leaves are dropped, as each
224
+ * loop drops them at the end of an iteration, so the caller may load the same accounts again (JavaScript has no such
225
+ * claims to leak). An instruction's own return needs none: nothing of the instruction runs after it.
226
+ */
227
+ releaseOnReturn(stmt) {
228
+ if (!this.helper && !this.inlineFrames.length)
229
+ return;
230
+ for (let n = stmt.parent; n && !ts.isFunctionLike(n); n = n.parent)
231
+ if (ts.isIterationStatement(n, false))
232
+ for (const slot of this.loopClaims.get(n.statement) ?? [])
233
+ this.line(`ts_release_mut(params, &${slot});`);
87
234
  }
88
235
  returnStatement(stmt) {
89
236
  const frame = this.inlineFrames.at(-1);
@@ -93,6 +240,7 @@ export class StatementEmitter extends CpiEmitter {
93
240
  if (!returns) {
94
241
  if (stmt.expression)
95
242
  this.fail(stmt, this.helper ? "this helper returns void" : "this instruction returns void; use `return;`");
243
+ this.releaseOnReturn(stmt);
96
244
  for (const l of this.epilogue())
97
245
  this.line(l);
98
246
  this.line(`return SUCCESS;`);
@@ -104,6 +252,7 @@ export class StatementEmitter extends CpiEmitter {
104
252
  if (this.helper) {
105
253
  // Write the struct through the caller's out pointer (a literal, a place or another helper's result).
106
254
  this.writeAggregate({ lv: "(*ret)", type: returns, writable: true }, stmt.expression);
255
+ this.releaseOnReturn(stmt);
107
256
  this.line(`return SUCCESS;`);
108
257
  return;
109
258
  }
@@ -134,9 +283,12 @@ export class StatementEmitter extends CpiEmitter {
134
283
  if (this.helper && returns.kind === "string") {
135
284
  // The caller gets its own copy: the text may be account data the caller then changes.
136
285
  this.line(`TS_TRY(ts_str_copy(${v.c}, ret));`);
286
+ this.releaseOnReturn(stmt);
137
287
  }
138
- else if (this.helper)
288
+ else if (this.helper) {
139
289
  this.line(returns.kind === "pubkey" ? `*ret = *(${v.c});` : `*ret = ${v.c};`);
290
+ this.releaseOnReturn(stmt);
291
+ }
140
292
  else if (returns.kind === "string") {
141
293
  // Return data is the Borsh String: u32 length, then the bytes (at most 1024 in all).
142
294
  const s = this.tmp("rets");
@@ -269,6 +421,8 @@ export class StatementEmitter extends CpiEmitter {
269
421
  this.fail(stmt.initializer, "write for (const x of list): one const name, no type annotation");
270
422
  if (this.isRemaining(stmt.expression))
271
423
  this.fail(stmt.expression, "iterate remaining accounts with for (let i = 0n; i < rest.length; i++) and rest.get(i)");
424
+ if (this.checker.getTypeAtLocation(stmt.expression).flags & ts.TypeFlags.StringLike)
425
+ this.fail(stmt.expression, "for … of over a string is not supported: a program handles text as UTF-8 bytes (byteLength(s) gives their count)");
272
426
  if (ts.isArrayLiteralExpression(stmt.expression) && this.functionList(stmt.expression))
273
427
  return this.forOfFunctions(stmt, d.name);
274
428
  if (this.treeForOf(stmt, d))
@@ -664,7 +818,7 @@ export class StatementEmitter extends CpiEmitter {
664
818
  const closure = { node: st.fn, name: "map's callback", scopes: [...this.scopes], env: this.envNow(), imports: this.scope.imports };
665
819
  const sc = this.tmp("lm_s");
666
820
  this.line(`TSS_${S.name} ${sc}__v;`);
667
- this.line(`ts_memzero(&${sc}__v, sizeof(${sc}__v));`);
821
+ this.line(`TS_ZERO_LOCAL(&${sc}__v, sizeof(${sc}__v));`);
668
822
  this.expandClosure(closure, [element, idx].slice(0, st.fn.parameters.length), st.fn, {
669
823
  lv: `${sc}__v`,
670
824
  type: { kind: "struct", name: S.name },
@@ -729,6 +883,11 @@ export class StatementEmitter extends CpiEmitter {
729
883
  const returns = (n) => ts.isReturnStatement(n) || (!ts.isFunctionLike(n) && !ts.isClassLike(n) && (ts.forEachChild(n, returns) ?? false));
730
884
  if (body && returns(body))
731
885
  return false;
886
+ // `break outer` / `continue outer` to a statement around the loop jumps within this function.
887
+ const jumpsOut = (n) => ((ts.isBreakStatement(n) || ts.isContinueStatement(n)) && !!n.label && this.labels.some((l) => l.name === n.label.text)) ||
888
+ (!ts.isFunctionLike(n) && (ts.forEachChild(n, jumpsOut) ?? false));
889
+ if (body && jumpsOut(body))
890
+ return false;
732
891
  // The variables visible here, by C name (innermost first, as lookup finds them).
733
892
  const visible = new Map();
734
893
  for (const scope of [...[...this.scopes].reverse(), this.args])
@@ -805,7 +964,7 @@ export class StatementEmitter extends CpiEmitter {
805
964
  outlinedParams(c, visible) {
806
965
  const toks = cTokens(c);
807
966
  const own = declaredNames(toks);
808
- const signature = this.helper ? parameterDecls(helperSignature(this.helper)) : new Map();
967
+ const signature = this.helper ? parameterDecls(helperSignature(this.helper, this.stack.noinline)) : new Map();
809
968
  const out = { params: [], args: [], copyIn: [], copyOut: [] };
810
969
  for (const n of [...usedNames(toks)].sort()) {
811
970
  if (own.has(n) || n === "params" || isGlobalName(n))
@@ -1135,6 +1294,7 @@ export class StatementEmitter extends CpiEmitter {
1135
1294
  scope: this.scope,
1136
1295
  scopes: this.scopes,
1137
1296
  loops: this.loops.splice(0),
1297
+ labels: this.labels.splice(0),
1138
1298
  args: swap(this.args, c.env.args),
1139
1299
  accounts: swap(this.accounts, bodyAccounts),
1140
1300
  };
@@ -1175,6 +1335,7 @@ export class StatementEmitter extends CpiEmitter {
1175
1335
  this.scopes = saved.scopes;
1176
1336
  this.scope = saved.scope;
1177
1337
  this.loops.push(...saved.loops);
1338
+ this.labels.push(...saved.labels);
1178
1339
  }
1179
1340
  if (!frame.type) {
1180
1341
  if (this.lines[frame.declAt].includes(`/* ${frame.result} */`))
@@ -1340,19 +1501,21 @@ export class StatementEmitter extends CpiEmitter {
1340
1501
  this.line(this.writeStorage(target, this.ownedString(this.expect(this.expr(stmt.expression, vt), vt, stmt.expression)).c) + ";");
1341
1502
  else
1342
1503
  this.writeAggregate(target, stmt.expression);
1504
+ this.releaseOnReturn(stmt);
1343
1505
  this.line(`goto ${frame.label};`);
1344
1506
  return;
1345
1507
  }
1346
1508
  if (!stmt.expression) {
1347
1509
  if (frame.type)
1348
1510
  this.fail(stmt, "this function returns a value");
1511
+ this.releaseOnReturn(stmt);
1349
1512
  this.line(`goto ${frame.label};`);
1350
1513
  return;
1351
1514
  }
1352
- this.closureResult(this.expr(stmt.expression, frame.type), stmt.expression, frame);
1515
+ this.closureResult(this.expr(stmt.expression, frame.type), stmt.expression, frame, stmt);
1353
1516
  }
1354
1517
  /** Store a closure's result (fixing its type on the first one) and jump past the rest of its body. */
1355
- closureResult(value, at, frame) {
1518
+ closureResult(value, at, frame, ret) {
1356
1519
  let v = value;
1357
1520
  const stmt = { expression: at };
1358
1521
  if (v.isNull && !frame.type)
@@ -1370,9 +1533,11 @@ export class StatementEmitter extends CpiEmitter {
1370
1533
  if (frame.type.kind === "pubkey")
1371
1534
  this.line(`${frame.result} = *(${v.c});`);
1372
1535
  else if (frame.type.kind === "option" && v.isNull)
1373
- this.line(`ts_memzero(&${frame.result}, sizeof(${frame.result}));`);
1536
+ this.line(`TS_ZERO_LOCAL(&${frame.result}, sizeof(${frame.result}));`);
1374
1537
  else
1375
1538
  this.line(`${frame.result} = ${this.ownedString(v).c};`);
1539
+ if (ret)
1540
+ this.releaseOnReturn(ret);
1376
1541
  this.line(`goto ${frame.label};`);
1377
1542
  }
1378
1543
  /** `do { … } while (cond)`: the body once, then the test; `continue` goes to the test. */
@@ -1462,6 +1627,8 @@ export class StatementEmitter extends CpiEmitter {
1462
1627
  this.claimSlots.set(call, slot);
1463
1628
  return slot;
1464
1629
  });
1630
+ if (slots.length)
1631
+ this.loopClaims.set(body, slots);
1465
1632
  return () => {
1466
1633
  for (const slot of slots)
1467
1634
  this.line(`ts_release_mut(params, &${slot});`);
@@ -1485,7 +1652,11 @@ export class StatementEmitter extends CpiEmitter {
1485
1652
  continue;
1486
1653
  }
1487
1654
  if (ts.isArrayBindingPattern(d.name)) {
1488
- this.addressAndBump(d, d.name, mutable);
1655
+ const init = d.initializer;
1656
+ if (init && ts.isCallExpression(init) && this.exportName(init.expression) === "getReturnData")
1657
+ this.programAndReturnData(d, d.name, init, mutable);
1658
+ else
1659
+ this.addressAndBump(d, d.name, mutable);
1489
1660
  continue;
1490
1661
  }
1491
1662
  if (!ts.isIdentifier(d.name) || !d.initializer)
@@ -1515,9 +1686,20 @@ export class StatementEmitter extends CpiEmitter {
1515
1686
  const c = `l_${name}_${this.temp++}`;
1516
1687
  const init = d.initializer;
1517
1688
  // `/** @heap */` names a list or struct type (checked again where such locals are made).
1518
- if ([d, d.parent?.parent].some((n) => n && ts.getJSDocTags(n).some((t) => t.tagName.text === "heap")) &&
1519
- !(d.type && (["FixedVec", "FixedArray"].includes(typesolName(d.type, this.scope.imports) ?? "") || structNameOf(d.type, this.scope))))
1689
+ const aggregateType = !!d.type && (["FixedVec", "FixedArray"].includes(typesolName(d.type, this.scope.imports) ?? "") || !!structNameOf(d.type, this.scope));
1690
+ if ([d, d.parent?.parent].some((n) => n && ts.getJSDocTags(n).some((t) => t.tagName.text === "heap")) && !aggregateType)
1520
1691
  this.heapLocal(d, false);
1692
+ // `/** @stack */`: a list or struct the build never moves to the heap (one declared with its type, or a helper's result).
1693
+ if (this.stackTagged(d)) {
1694
+ if ([d, d.parent?.parent].some((n) => n && ts.getJSDocTags(n).some((t) => t.tagName.text === "heap")))
1695
+ this.fail(d, "a local is either @heap or @stack, not both");
1696
+ let bare = init;
1697
+ while (bare && ts.isParenthesizedExpression(bare))
1698
+ bare = bare.expression;
1699
+ const result = !d.type && !!bare && ts.isCallExpression(bare) && this.helperOf(bare)?.returns?.kind === "struct";
1700
+ if (!aggregateType && !result)
1701
+ this.fail(d, "@stack is for a local list or struct (declared with its type, or a helper's struct result): the build never moves it to the heap");
1702
+ }
1521
1703
  // Run-time offset views (loadRawAt, rawArrayAt, rbTreeAt) and references into a tree's nodes (views.ts).
1522
1704
  if (this.bindView(d, init, name, c, mutable))
1523
1705
  continue;
@@ -1673,8 +1855,11 @@ export class StatementEmitter extends CpiEmitter {
1673
1855
  // Struct values: `const p: Point = { x, y }` (or a copy of another Point) is a local of its own.
1674
1856
  const structType = d.type && structNameOf(d.type, this.scope) ? this.model.structs.get(structNameOf(d.type, this.scope)) : undefined;
1675
1857
  // `/** @heap */`: the local lives on the heap instead of the 4 KiB stack frame.
1676
- const heap = this.heapLocal(d, !!listType || !!structType);
1858
+ const tagged = this.heapLocal(d, !!listType || !!structType);
1859
+ const stackTag = this.stackTagged(d);
1677
1860
  if (listType) {
1861
+ // To fit the stack, the build may keep it on the heap as if it were /** @heap */ (src/compiler/stack.ts).
1862
+ const heap = this.autoHeap(d, { name: `\`${name}\``, c, bytes: this.fieldBytes(listType), stack: stackTag, heap: tagged }) || tagged;
1678
1863
  if (heap)
1679
1864
  this.checkHeapRoom(this.fieldBytes(listType), d.type);
1680
1865
  else
@@ -1699,9 +1884,10 @@ export class StatementEmitter extends CpiEmitter {
1699
1884
  }
1700
1885
  if (structType) {
1701
1886
  if (mutable)
1702
- this.fail(d, "bind struct values with const (their fields can still be updated)");
1887
+ this.fail(d, `let on a struct is not supported: bind it with const (its fields can still be updated, ${d.name.getText()}.field = …); to replace it whole, assign each field`);
1703
1888
  if (structType.size === undefined || structType.vec)
1704
1889
  this.fail(d.type, `${structType.name} has variable-size fields and cannot be a local`);
1890
+ const heap = this.autoHeap(d, { name: `\`${name}\``, c: `${c}__v`, bytes: structType.size, stack: stackTag, heap: tagged }) || tagged;
1705
1891
  if (heap) {
1706
1892
  this.checkHeapRoom(structType.size, d.type);
1707
1893
  this.hoistLazy(`${c}__h`, (n) => `TSS_${structType.name} *${n}`);
@@ -1726,7 +1912,8 @@ export class StatementEmitter extends CpiEmitter {
1726
1912
  let ptr;
1727
1913
  let writable = true;
1728
1914
  let paths = [`@${c}`];
1729
- if (enumType && ts.isObjectLiteralExpression(init)) {
1915
+ // A literal, or `cond ? { kind: "A", … } : { kind: "B" }`: built in place (only the chosen branch runs).
1916
+ if (enumType && (ts.isObjectLiteralExpression(init) || ts.isConditionalExpression(init))) {
1730
1917
  name2 = enumType.name;
1731
1918
  this.line(`TSE_${name2} ${c}__v;`);
1732
1919
  this.writeAggregate({ lv: `${c}__v`, type: { kind: "dataEnum", name: name2 }, writable: true }, init);
@@ -1735,7 +1922,7 @@ export class StatementEmitter extends CpiEmitter {
1735
1922
  else {
1736
1923
  const r = this.ref(init);
1737
1924
  if (!r || r.type.kind !== "dataEnum" || (enumType && r.type.name !== enumType.name))
1738
- this.fail(init, `expected a ${enumType?.name ?? "data enum"}`);
1925
+ this.fail(init, `expected a ${enumType?.name ?? "data enum"}: a literal ({ kind: "…", … }), a choice between them (c ? { … } : { … }) or another one`);
1739
1926
  name2 = r.type.name;
1740
1927
  ptr = `(&${r.lv})`;
1741
1928
  writable = r.writable;
@@ -1772,7 +1959,7 @@ export class StatementEmitter extends CpiEmitter {
1772
1959
  else if (d.type) {
1773
1960
  declared = resolveValueType(d.type, this.scope);
1774
1961
  if (!declared || declared.kind === "vecArg")
1775
- this.fail(d.type, "local type must be an integer, boolean, Pubkey, enum, option or string");
1962
+ this.fail(d.type, unsupportedTypeForm(d.type, this.scope.imports) ?? "local type must be an integer, boolean, Pubkey, enum, option or string");
1776
1963
  }
1777
1964
  // `const bump = acct.create(...)` / `const fresh = acct.createIfNeeded(...)` count as top-level statements.
1778
1965
  const isCreate = topLevel && ts.isCallExpression(init) && ts.isPropertyAccessExpression(init.expression) && /^create(IfNeeded)?$/.test(init.expression.name.text);
@@ -1830,15 +2017,59 @@ export class StatementEmitter extends CpiEmitter {
1830
2017
  if (bytes > room)
1831
2018
  this.fail(at, `this local takes ${bytes} bytes and the heap holds ${room} (raise HEAP_SIZE_KIB, at most 256)`);
1832
2019
  }
2020
+ /**
2021
+ * `const [program, data] = getReturnData()`: Rust's `get_return_data()`, the return data as the runtime holds it
2022
+ * (sol_get_return_data): the program that set it and its bytes, read into 1 KiB of this function's stack frame (the
2023
+ * runtime's maximum, so nothing is cut). Rust's `None` is `data.length === 0n` (the runtime keeps no empty return
2024
+ * data), with `program` then all zeros.
2025
+ */
2026
+ programAndReturnData(d, pattern, call, mutable) {
2027
+ const usage = "const [program, data] = getReturnData()";
2028
+ if (mutable)
2029
+ this.fail(d, `bind them with const: ${usage}`);
2030
+ if (d.type)
2031
+ this.fail(d.type, "leave the type out: the program is a Pubkey and the data a read-only list of u8 (InstructionBytes)");
2032
+ if (call.arguments.length)
2033
+ this.fail(call, "getReturnData() takes no arguments");
2034
+ if (pattern.elements.length > 2)
2035
+ this.fail(pattern, `getReturnData gives two values: ${usage}`);
2036
+ const names = pattern.elements.map((el) => {
2037
+ if (ts.isOmittedExpression(el))
2038
+ return undefined;
2039
+ if (el.dotDotDotToken || el.initializer || !ts.isIdentifier(el.name))
2040
+ this.fail(el, `name the program and the data: ${usage}`);
2041
+ const name = el.name.text;
2042
+ if (this.scopes.at(-1).has(name))
2043
+ this.fail(el.name, `"${name}" is already declared`);
2044
+ if (this.accounts.has(name) || this.args.has(name) || this.isGroup(name))
2045
+ this.fail(el.name, `"${name}" shadows the parameter "${name}"; use another name`);
2046
+ return name;
2047
+ });
2048
+ const [program, data] = names;
2049
+ const key = program ? `l_${program}_${this.temp++}` : this.tmp("rdfrom");
2050
+ const buf = this.tmp("rdbuf");
2051
+ const len = this.tmp("rdlen");
2052
+ this.line(`SolPubkey ${key} = {0}; uint8_t ${buf}[1024];`);
2053
+ this.line(`uint64_t ${len} = sol_get_return_data(${buf}, sizeof(${buf}), &${key});`);
2054
+ if (program)
2055
+ this.scopes.at(-1).set(program, { c: key, type: PUBKEY, mutable: false });
2056
+ if (data) {
2057
+ const c = `l_${data}_${this.temp++}`;
2058
+ this.line(`TS_VecArg ${c} = {${buf}, (uint32_t)(${len} < sizeof(${buf}) ? ${len} : sizeof(${buf}))};`);
2059
+ this.scopes.at(-1).set(data, { c, type: { kind: "vecArg", elem: { kind: "int", name: "u8" } }, mutable: false });
2060
+ }
2061
+ else
2062
+ this.line(`(void)${len};`);
2063
+ }
1833
2064
  /**
1834
2065
  * `const [address, bump] = findProgramAddressWithBump(seeds, program)`: Rust's `let (address, bump) =
1835
- * Pubkey::find_program_address(…)`, both from one search (the only array destructuring the language has).
2066
+ * Pubkey::find_program_address(…)`, both from one search (with getReturnData, the only array destructuring).
1836
2067
  */
1837
2068
  addressAndBump(d, pattern, mutable) {
1838
2069
  const init = d.initializer;
1839
2070
  const call = init && ts.isCallExpression(init) && this.exportName(init.expression) === "findProgramAddressWithBump" ? init : undefined;
1840
2071
  if (!call)
1841
- this.fail(d.name, "array destructuring is only for const [address, bump] = findProgramAddressWithBump(seeds, program)");
2072
+ this.fail(d.name, "array destructuring is only for const [address, bump] = findProgramAddressWithBump(seeds, program) and const [program, data] = getReturnData()");
1842
2073
  if (mutable)
1843
2074
  this.fail(d, "bind them with const: const [address, bump] = findProgramAddressWithBump(seeds, program)");
1844
2075
  if (d.type)
@@ -1865,7 +2096,7 @@ export class StatementEmitter extends CpiEmitter {
1865
2096
  const key = address ? `l_${address}_${this.temp++}` : this.tmp("pda");
1866
2097
  const b = bump ? `l_${bump}_${this.temp++}` : this.tmp("bump");
1867
2098
  this.line(`SolPubkey ${key}; uint8_t ${b};`);
1868
- 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");`);
2099
+ this.line(`if (ts_find_pda${fitSuffix(seeds)}(${seeds.name}, ${seeds.count}, ${program.c}, &${key}, &${b}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no program address for these seeds");`);
1869
2100
  if (address)
1870
2101
  this.scopes.at(-1).set(address, { c: key, type: PUBKEY, mutable: false });
1871
2102
  if (bump)
@@ -2110,6 +2341,8 @@ export class StatementEmitter extends CpiEmitter {
2110
2341
  const base = compound[op];
2111
2342
  if (base !== undefined)
2112
2343
  return this.assign(e.left, e.right, base);
2344
+ if (op === ts.SyntaxKind.BarBarEqualsToken || op === ts.SyntaxKind.AmpersandAmpersandEqualsToken || op === ts.SyntaxKind.QuestionQuestionEqualsToken)
2345
+ return this.logicalAssign(e, op);
2113
2346
  if (op === ts.SyntaxKind.AsteriskAsteriskEqualsToken) {
2114
2347
  // x **= n is x = x ** n; the target is read twice, so it must not run anything (no calls in it).
2115
2348
  let hasCall = false;
@@ -2147,8 +2380,55 @@ export class StatementEmitter extends CpiEmitter {
2147
2380
  this.call(e, topLevel);
2148
2381
  return;
2149
2382
  }
2383
+ if (ts.isVoidExpression(e))
2384
+ this.fail(e, "void is not supported: call the function as a statement (its result is then unused)");
2150
2385
  this.fail(e, "this expression has no effect; only assignments and calls can be statements");
2151
2386
  }
2387
+ /**
2388
+ * `x ||= b`, `x &&= b` (booleans) and `x ??= b` (Options), as JS runs them: the place is found once, its value read,
2389
+ * and only when that decides it (false, true, empty) is `b` evaluated and written; otherwise nothing runs or is
2390
+ * written.
2391
+ */
2392
+ logicalAssign(e, op) {
2393
+ const word = ts.tokenToString(op);
2394
+ const target = e.left;
2395
+ if (this.writesThroughVec(target) && this.mayResizeVecs(e.right))
2396
+ this.fail(target, "the right side may change this Vec (a helper, closure or push/pop/clear); store its result in a local first");
2397
+ if (op === ts.SyntaxKind.QuestionQuestionEqualsToken) {
2398
+ // An Option of a struct or an array is a place of its own: written whole, as `=` writes it.
2399
+ const r = this.probe(() => this.ref(target));
2400
+ if (r?.type.kind === "option" && (r.type.inner.kind === "struct" || r.type.inner.kind === "array")) {
2401
+ const ref = this.ref(target);
2402
+ if (!ref.writable)
2403
+ this.fail(target, this.readOnly(ref));
2404
+ this.assertNotAliased(this.pathsOf(target), target);
2405
+ this.line(`if (!${ref.lv}.some) {`);
2406
+ this.block(() => this.writeAggregate(ref, e.right));
2407
+ this.line(`}`);
2408
+ return;
2409
+ }
2410
+ }
2411
+ const place = this.place(target);
2412
+ let test;
2413
+ if (op === ts.SyntaxKind.QuestionQuestionEqualsToken) {
2414
+ if (place.type.kind !== "option")
2415
+ this.fail(e, `??= needs an Option on the left (${typeName(place.type)} is never null): write ${target.getText()} = …`);
2416
+ const cur = this.tmp("opt");
2417
+ this.line(`${optC(place.type.inner)} ${cur} = ${place.read};`);
2418
+ test = `!${cur}.some`;
2419
+ }
2420
+ else {
2421
+ if (place.type.kind !== "bool")
2422
+ this.fail(e, `${word} works on booleans; on ${typeName(place.type)} JavaScript would test ${place.type.kind === "int" ? "for 0n" : "truthiness"}: write if (…) ${target.getText()} = …`);
2423
+ test = op === ts.SyntaxKind.BarBarEqualsToken ? `!(${place.read})` : `(${place.read})`;
2424
+ }
2425
+ this.line(`if (${test}) {`);
2426
+ this.block(() => {
2427
+ const value = this.expect(this.expr(e.right, place.type), place.type, e.right);
2428
+ this.line(place.write(value.c) + ";");
2429
+ });
2430
+ this.line(`}`);
2431
+ }
2152
2432
  assign(target, valueNode, op, topLevel = false) {
2153
2433
  // The place is resolved before the right side runs (JS order). A right side that can resize a Vec of the account
2154
2434
  // would move the element out from under it: the write would land in the bytes that follow.
@@ -2173,24 +2453,35 @@ export class StatementEmitter extends CpiEmitter {
2173
2453
  const local = cur === current.c && place.write("X") === `${cur} = X`;
2174
2454
  const bare = (e) => (ts.isParenthesizedExpression(e) ? bare(e.expression) : e);
2175
2455
  const rhsNode = bare(valueNode);
2456
+ // JS reads the left side before the right side runs. A right side that assigns the local (a closure called in
2457
+ // it) leaves the local's old text in a snapshot taken before it ran (settle), which is then appended to and
2458
+ // stored; otherwise the local itself is appended to, as before.
2459
+ const mark = this.lines.length;
2460
+ const old = () => this.settle({ c: cur, type: STRING }, mark).c;
2176
2461
  if (local && ts.isTemplateExpression(rhsNode)) {
2177
2462
  const pieces = this.templatePieces(rhsNode);
2463
+ const to = old();
2178
2464
  if (pieces.text !== undefined)
2179
- this.line(`TS_TRY(ts_str_append(&${cur}, ts_str((const uint8_t *)${cString(pieces.text)}, ${Buffer.byteLength(pieces.text, "utf8")})));`);
2465
+ this.line(`TS_TRY(ts_str_append(&${to}, ts_str((const uint8_t *)${cString(pieces.text)}, ${Buffer.byteLength(pieces.text, "utf8")})));`);
2180
2466
  else if (pieces.only !== undefined)
2181
- this.line(`TS_TRY(ts_str_append(&${cur}, ${pieces.only}));`);
2467
+ this.line(`TS_TRY(ts_str_append(&${to}, ${pieces.only}));`);
2182
2468
  else
2183
- this.line(`TS_TRY(ts_str_append_parts(&${cur}, ${pieces.arr}, ${pieces.n}));`);
2469
+ this.line(`TS_TRY(ts_str_append_parts(&${to}, ${pieces.arr}, ${pieces.n}));`);
2470
+ if (to !== cur)
2471
+ this.line(place.write(to) + ";");
2184
2472
  return;
2185
2473
  }
2186
2474
  const rhs = this.toText(valueNode);
2475
+ const from = old();
2187
2476
  if (local) {
2188
- this.line(`TS_TRY(ts_str_append(&${cur}, ${rhs}));`);
2477
+ this.line(`TS_TRY(ts_str_append(&${from}, ${rhs}));`);
2478
+ if (from !== cur)
2479
+ this.line(place.write(from) + ";");
2189
2480
  return;
2190
2481
  }
2191
2482
  const t = this.tmp("cat");
2192
2483
  this.line(`TS_Str ${t};`);
2193
- this.line(`TS_TRY(ts_str_concat(${cur}, ${rhs}, &${t}));`);
2484
+ this.line(`TS_TRY(ts_str_concat(${from}, ${rhs}, &${t}));`);
2194
2485
  this.line(place.write(t) + ";");
2195
2486
  return;
2196
2487
  }
@@ -2263,3 +2554,15 @@ function commaList(e) {
2263
2554
  return [...commaList(e.left), ...commaList(e.right)];
2264
2555
  return [e];
2265
2556
  }
2557
+ /** Why a statement is refused (`ts.SyntaxKind[kind]` names some kinds by an alias, such as LastStatement). */
2558
+ function statementMessage(kind) {
2559
+ const top = {
2560
+ [ts.SyntaxKind.InterfaceDeclaration]: "interfaces",
2561
+ [ts.SyntaxKind.TypeAliasDeclaration]: "type aliases",
2562
+ [ts.SyntaxKind.EnumDeclaration]: "enums",
2563
+ };
2564
+ const what = top[kind];
2565
+ if (what)
2566
+ return `${what} are declared at the top level of a file, not inside a function`;
2567
+ return `${ts.SyntaxKind[kind]} is not supported in TypeSOL`;
2568
+ }
@@ -76,6 +76,12 @@ export declare abstract class StorageEmitter extends AliasEmitter {
76
76
  protected readStorage(r: Ref, node: ts.Node): Value;
77
77
  /** C statement (without `;`) writing a lowered value into storage. */
78
78
  protected writeStorage(r: Ref, c: string): string;
79
+ /**
80
+ * Why a struct value cannot stand for another struct type it extends (`interface Child extends Base`, a Child passed
81
+ * as a Base): JavaScript passes the same object, which TypeSOL would copy (or cut to the parent's fields). Empty when
82
+ * the types are not related.
83
+ */
84
+ protected parentNote(from: FieldType | ValueType | undefined, want: FieldType | ValueType, node?: ts.Expression): string;
79
85
  protected storageValueType(t: FieldType): ValueType | undefined;
80
86
  /**
81
87
  * Write a struct or array into storage: from an object literal (field by field, every field
@@ -103,6 +109,16 @@ export declare abstract class StorageEmitter extends AliasEmitter {
103
109
  * expression can read yet, so a literal is built in it directly rather than in a temporary first.
104
110
  */
105
111
  protected writeAggregate(target: Ref, valueNode: ts.Expression, fresh?: boolean): void;
112
+ /**
113
+ * `{ ...p, x: 1n }` / `{ x: 1n, ...p }`: entries in source order, each evaluated once, a later one overwriting an
114
+ * earlier one, as in JS. `...p` copies p's fields at that point, as `field: p.field` would (a struct field is copied
115
+ * whole, as assignment copies). p is a struct of the literal's type, one it extends (its fields are copied), or one
116
+ * extending it (the literal's fields are copied from it); a struct account is one too. The value is built in a
117
+ * temporary unless the target is fresh, so `acct.p = { ...acct.p, x: acct.p.y }` reads the old fields.
118
+ */
119
+ private spreadLiteral;
120
+ /** The struct place `...value` copies from: a struct place, or a whole struct account. */
121
+ private spreadSource;
106
122
  /** `fixedVec([…])` or `[…]`: a list literal, which writeAggregate builds in a fresh target with its free slots zeroed. */
107
123
  protected isListLiteral(node: ts.Expression): boolean;
108
124
  /** The Vec view of a FixedVec stored at `lv` (`{ len, items[cap] }`). */