@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
@@ -9,6 +9,18 @@ export function accountLimit(model) {
9
9
  }
10
10
  /** Solana's limit on the seeds of one address, the bump included (MAX_SEEDS of solana-pubkey; each seed at most 32 bytes). */
11
11
  export const MAX_SEEDS = 16;
12
+ /**
13
+ * The runtime's derivation for a seed list the compiler proved within Solana's limits (`_fit`: no run-time check of
14
+ * the seed lengths and count, which cannot fail), or the checked one.
15
+ */
16
+ export const fitSuffix = (seeds) => (seeds.fit ? "_fit" : "");
17
+ /**
18
+ * Written after a call of an account-creating runtime helper (ts_create_pda, ts_create_owned, …) given a seed list
19
+ * the compiler could not prove within the limits: the program then keeps the run-time check in those helpers
20
+ * (program.ts defines TS_PDA_SEEDS_FIT only when no body has this mark).
21
+ */
22
+ export const SEEDS_CHECKED_MARK = "/* seed lengths checked at run time */";
23
+ export const seedsCheckedMark = (seeds) => (seeds.fit ? "" : ` ${SEEDS_CHECKED_MARK}`);
12
24
  /** Max instruction data an invoke() may build, and max event payload. */
13
25
  export const MAX_CPI_DATA = 1024;
14
26
  export const MAX_EVENT = 1024;
@@ -234,8 +246,11 @@ export const unreachableArg = (c, pubkey) => pubkey
234
246
  c === "params->program_id" ||
235
247
  /^\(&\(\*arg_\w+\)(?:\.\w+)+\)$/.test(c)
236
248
  : /^\w+$/.test(c) || /^\(\*p_\w+\)$/.test(c) || /^\(\*arg_\w+\)(?:\.\w+)+$/.test(c);
237
- /** Helpers get the instruction's parameters (for CPIs and accounts), then their own, then the result slot. */
238
- export function helperSignature(h) {
249
+ /**
250
+ * Helpers get the instruction's parameters (for CPIs and accounts), then their own, then the result slot. `noinline`:
251
+ * the helpers (C names) the build keeps out of line to fit the stack, as if each were `@noinline`.
252
+ */
253
+ export function helperSignature(h, noinline) {
239
254
  const params = ["TsParams *params"];
240
255
  for (const p of h.params) {
241
256
  if (p.account) {
@@ -265,7 +280,7 @@ export function helperSignature(h) {
265
280
  }
266
281
  if (h.returns)
267
282
  params.push(h.returns.kind === "struct" ? `TSS_${h.returns.name} *ret` : h.returns.kind === "string" ? `TS_Str *ret` : `${scalarC(h.returns)} *ret`);
268
- return `${h.noinline ? "__attribute__((noinline)) " : ""}static uint64_t fn_${h.name}(${params.join(", ")})`;
283
+ return `${h.noinline || noinline?.has(`fn_${h.name}`) ? "__attribute__((noinline)) " : ""}static uint64_t fn_${h.name}(${params.join(", ")})`;
269
284
  }
270
285
  /** C type of a growable Vec stored after the first one of struct `s`: `{ uint32_t len; T items[]; }`. */
271
286
  export function laterVecC(s, field) {
@@ -10,7 +10,28 @@ interface CheckCall {
10
10
  }
11
11
  export declare abstract class StatementEmitter extends CpiEmitter {
12
12
  protected statement(stmt: ts.Statement, topLevel?: boolean): void;
13
+ /** Declarations that failed (a refused const, a nested function declaration): later uses are not reported again. */
14
+ private readonly brokenDecls;
15
+ private usesBrokenName;
13
16
  protected statementInner(stmt: ts.Statement, topLevel: boolean): void;
17
+ /**
18
+ * `outer: for (…) { … }` (any loop) or `done: { … }`: the statement, then a C label after it for `break outer`, emitted
19
+ * when a jump uses it. `continue outer` goes to the loop's own `continue` label, so the step of a `for` runs, as in
20
+ * JS.
21
+ */
22
+ protected labeled(stmt: ts.LabeledStatement): void;
23
+ /**
24
+ * `break outer` / `continue outer`: a jump to the label after the statement, or to the labeled loop's `continue`
25
+ * label. The views of loadAccountMut held by the loops it leaves are dropped first, as each loop drops them at the end
26
+ * of an iteration.
27
+ */
28
+ protected labeledJump(stmt: ts.BreakStatement | ts.ContinueStatement): void;
29
+ /**
30
+ * Before a `return` from a helper or a closure: the loadAccountMut views of the loops it leaves are dropped, as each
31
+ * loop drops them at the end of an iteration, so the caller may load the same accounts again (JavaScript has no such
32
+ * claims to leak). An instruction's own return needs none: nothing of the instruction runs after it.
33
+ */
34
+ protected releaseOnReturn(stmt: ts.ReturnStatement): void;
14
35
  protected returnStatement(stmt: ts.ReturnStatement): void;
15
36
  /** `switch` on integers, enums and `.kind` of data enums: a C switch, with JS fallthrough/break semantics. */
16
37
  protected switchStatement(stmt: ts.SwitchStatement): void;
@@ -144,7 +165,7 @@ export declare abstract class StatementEmitter extends CpiEmitter {
144
165
  /** `return` inside an expanded closure: the value goes to the closure's result, then past its body. */
145
166
  protected closureReturn(stmt: ts.ReturnStatement, frame: (typeof this.inlineFrames)[number]): void;
146
167
  /** Store a closure's result (fixing its type on the first one) and jump past the rest of its body. */
147
- protected closureResult(value: Value, at: ts.Expression, frame: (typeof this.inlineFrames)[number]): void;
168
+ protected closureResult(value: Value, at: ts.Expression, frame: (typeof this.inlineFrames)[number], ret?: ts.ReturnStatement): void;
148
169
  /** `do { … } while (cond)`: the body once, then the test; `continue` goes to the test. */
149
170
  protected doLoop(stmt: ts.DoStatement): void;
150
171
  /**
@@ -211,6 +232,12 @@ export declare abstract class StatementEmitter extends CpiEmitter {
211
232
  */
212
233
  protected refuseUnreadVerifier(name: ts.Identifier, value: ts.Expression): void;
213
234
  protected expressionStatement(e: ts.Expression, topLevel: boolean): void;
235
+ /**
236
+ * `x ||= b`, `x &&= b` (booleans) and `x ??= b` (Options), as JS runs them: the place is found once, its value read,
237
+ * and only when that decides it (false, true, empty) is `b` evaluated and written; otherwise nothing runs or is
238
+ * written.
239
+ */
240
+ protected logicalAssign(e: ts.BinaryExpression, op: ts.SyntaxKind): void;
214
241
  protected assign(target: ts.Expression, valueNode: ts.Expression, op?: ts.BinaryOperator, topLevel?: boolean): void;
215
242
  }
216
243
  export {};
@@ -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))
@@ -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)
@@ -1373,6 +1536,8 @@ export class StatementEmitter extends CpiEmitter {
1373
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});`);
@@ -1519,9 +1686,20 @@ export class StatementEmitter extends CpiEmitter {
1519
1686
  const c = `l_${name}_${this.temp++}`;
1520
1687
  const init = d.initializer;
1521
1688
  // `/** @heap */` names a list or struct type (checked again where such locals are made).
1522
- if ([d, d.parent?.parent].some((n) => n && ts.getJSDocTags(n).some((t) => t.tagName.text === "heap")) &&
1523
- !(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)
1524
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
+ }
1525
1703
  // Run-time offset views (loadRawAt, rawArrayAt, rbTreeAt) and references into a tree's nodes (views.ts).
1526
1704
  if (this.bindView(d, init, name, c, mutable))
1527
1705
  continue;
@@ -1677,8 +1855,11 @@ export class StatementEmitter extends CpiEmitter {
1677
1855
  // Struct values: `const p: Point = { x, y }` (or a copy of another Point) is a local of its own.
1678
1856
  const structType = d.type && structNameOf(d.type, this.scope) ? this.model.structs.get(structNameOf(d.type, this.scope)) : undefined;
1679
1857
  // `/** @heap */`: the local lives on the heap instead of the 4 KiB stack frame.
1680
- const heap = this.heapLocal(d, !!listType || !!structType);
1858
+ const tagged = this.heapLocal(d, !!listType || !!structType);
1859
+ const stackTag = this.stackTagged(d);
1681
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;
1682
1863
  if (heap)
1683
1864
  this.checkHeapRoom(this.fieldBytes(listType), d.type);
1684
1865
  else
@@ -1703,9 +1884,10 @@ export class StatementEmitter extends CpiEmitter {
1703
1884
  }
1704
1885
  if (structType) {
1705
1886
  if (mutable)
1706
- 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`);
1707
1888
  if (structType.size === undefined || structType.vec)
1708
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;
1709
1891
  if (heap) {
1710
1892
  this.checkHeapRoom(structType.size, d.type);
1711
1893
  this.hoistLazy(`${c}__h`, (n) => `TSS_${structType.name} *${n}`);
@@ -1730,7 +1912,8 @@ export class StatementEmitter extends CpiEmitter {
1730
1912
  let ptr;
1731
1913
  let writable = true;
1732
1914
  let paths = [`@${c}`];
1733
- 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))) {
1734
1917
  name2 = enumType.name;
1735
1918
  this.line(`TSE_${name2} ${c}__v;`);
1736
1919
  this.writeAggregate({ lv: `${c}__v`, type: { kind: "dataEnum", name: name2 }, writable: true }, init);
@@ -1739,7 +1922,7 @@ export class StatementEmitter extends CpiEmitter {
1739
1922
  else {
1740
1923
  const r = this.ref(init);
1741
1924
  if (!r || r.type.kind !== "dataEnum" || (enumType && r.type.name !== enumType.name))
1742
- 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`);
1743
1926
  name2 = r.type.name;
1744
1927
  ptr = `(&${r.lv})`;
1745
1928
  writable = r.writable;
@@ -1776,7 +1959,7 @@ export class StatementEmitter extends CpiEmitter {
1776
1959
  else if (d.type) {
1777
1960
  declared = resolveValueType(d.type, this.scope);
1778
1961
  if (!declared || declared.kind === "vecArg")
1779
- 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");
1780
1963
  }
1781
1964
  // `const bump = acct.create(...)` / `const fresh = acct.createIfNeeded(...)` count as top-level statements.
1782
1965
  const isCreate = topLevel && ts.isCallExpression(init) && ts.isPropertyAccessExpression(init.expression) && /^create(IfNeeded)?$/.test(init.expression.name.text);
@@ -1913,7 +2096,7 @@ export class StatementEmitter extends CpiEmitter {
1913
2096
  const key = address ? `l_${address}_${this.temp++}` : this.tmp("pda");
1914
2097
  const b = bump ? `l_${bump}_${this.temp++}` : this.tmp("bump");
1915
2098
  this.line(`SolPubkey ${key}; uint8_t ${b};`);
1916
- 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");`);
1917
2100
  if (address)
1918
2101
  this.scopes.at(-1).set(address, { c: key, type: PUBKEY, mutable: false });
1919
2102
  if (bump)
@@ -2158,6 +2341,8 @@ export class StatementEmitter extends CpiEmitter {
2158
2341
  const base = compound[op];
2159
2342
  if (base !== undefined)
2160
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);
2161
2346
  if (op === ts.SyntaxKind.AsteriskAsteriskEqualsToken) {
2162
2347
  // x **= n is x = x ** n; the target is read twice, so it must not run anything (no calls in it).
2163
2348
  let hasCall = false;
@@ -2195,8 +2380,55 @@ export class StatementEmitter extends CpiEmitter {
2195
2380
  this.call(e, topLevel);
2196
2381
  return;
2197
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)");
2198
2385
  this.fail(e, "this expression has no effect; only assignments and calls can be statements");
2199
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
+ }
2200
2432
  assign(target, valueNode, op, topLevel = false) {
2201
2433
  // The place is resolved before the right side runs (JS order). A right side that can resize a Vec of the account
2202
2434
  // would move the element out from under it: the write would land in the bytes that follow.
@@ -2221,24 +2453,35 @@ export class StatementEmitter extends CpiEmitter {
2221
2453
  const local = cur === current.c && place.write("X") === `${cur} = X`;
2222
2454
  const bare = (e) => (ts.isParenthesizedExpression(e) ? bare(e.expression) : e);
2223
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;
2224
2461
  if (local && ts.isTemplateExpression(rhsNode)) {
2225
2462
  const pieces = this.templatePieces(rhsNode);
2463
+ const to = old();
2226
2464
  if (pieces.text !== undefined)
2227
- 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")})));`);
2228
2466
  else if (pieces.only !== undefined)
2229
- this.line(`TS_TRY(ts_str_append(&${cur}, ${pieces.only}));`);
2467
+ this.line(`TS_TRY(ts_str_append(&${to}, ${pieces.only}));`);
2230
2468
  else
2231
- 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) + ";");
2232
2472
  return;
2233
2473
  }
2234
2474
  const rhs = this.toText(valueNode);
2475
+ const from = old();
2235
2476
  if (local) {
2236
- 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) + ";");
2237
2480
  return;
2238
2481
  }
2239
2482
  const t = this.tmp("cat");
2240
2483
  this.line(`TS_Str ${t};`);
2241
- this.line(`TS_TRY(ts_str_concat(${cur}, ${rhs}, &${t}));`);
2484
+ this.line(`TS_TRY(ts_str_concat(${from}, ${rhs}, &${t}));`);
2242
2485
  this.line(place.write(t) + ";");
2243
2486
  return;
2244
2487
  }
@@ -2311,3 +2554,15 @@ function commaList(e) {
2311
2554
  return [...commaList(e.left), ...commaList(e.right)];
2312
2555
  return [e];
2313
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] }`). */