@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
@@ -4,7 +4,7 @@ import { borshIdentical, borshMinSize, borshNativeStructUnsupported } from "./bo
4
4
  import { ANCHOR_ERRORS } from "../anchor-errors.js";
5
5
  import { decodeAddress } from "../../keys.js";
6
6
  import { INT_INFO, INT_NAMES, isScalar, isWritable, sameType, scalarSize, typeName, } from "../model.js";
7
- import { U64, U32, U8, I64, I32, BOOL, PUBKEY, STRING, HASH, cBytes, cString, scalarC, scalarStorageC, optC, valueC, fieldC, storageDecl, accountMismatch, vecCount, emptySizeC, vecLenCheck, passedByPointer, unreachableArg, } from "./shared.js";
7
+ import { U64, U32, U8, I64, I32, BOOL, PUBKEY, STRING, HASH, cBytes, cString, scalarC, scalarStorageC, optC, valueC, fieldC, storageDecl, accountMismatch, vecCount, emptySizeC, vecLenCheck, passedByPointer, unreachableArg, fitSuffix, } from "./shared.js";
8
8
  import { ExpressionEmitter } from "./expressions.js";
9
9
  /**
10
10
  * Calls: built-in functions, Vec methods, helpers, remaining accounts, foreign account reads and return data.
@@ -241,7 +241,7 @@ export class CallEmitter extends ExpressionEmitter {
241
241
  const b = this.tmp("bump");
242
242
  this.line(`uint8_t ${b} = ${bump.c};`);
243
243
  this.line(`${seeds.name}[${seeds.count}] = (SolSignerSeed){&${b}, 1};`);
244
- this.line(`TS_TRY(ts_require_pda(a_${a.name}, ${seeds.name}, ${seeds.count + 1}, params->program_id));`);
244
+ this.line(`TS_TRY(ts_require_pda${fitSuffix(seeds)}(a_${a.name}, ${seeds.name}, ${seeds.count + 1}, params->program_id));`);
245
245
  return undefined;
246
246
  }
247
247
  case "close": {
@@ -671,7 +671,7 @@ export class CallEmitter extends ExpressionEmitter {
671
671
  const t = this.tmp("pda");
672
672
  const b = this.tmp("bump");
673
673
  this.line(`SolPubkey ${t}; uint8_t ${b};`);
674
- this.line(`if (ts_find_pda(${seeds.name}, ${seeds.count}, ${program.c}, &${t}, &${b}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no program address for these seeds");`);
674
+ this.line(`if (ts_find_pda${fitSuffix(seeds)}(${seeds.name}, ${seeds.count}, ${program.c}, &${t}, &${b}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no program address for these seeds");`);
675
675
  return { c: `((uint64_t)${b})`, type: { kind: "int", name: "u8" } };
676
676
  }
677
677
  case "initAccount": {
@@ -707,7 +707,7 @@ export class CallEmitter extends ExpressionEmitter {
707
707
  const t = this.tmp("cpa");
708
708
  this.model.options.set("pubkey", PUBKEY);
709
709
  this.line(`${optC(PUBKEY)} ${t};`);
710
- this.line(`${t}.some = ts_create_pda_address(${seeds.name}, ${seeds.count}, ${program.c}, &${t}.v) == SUCCESS;`);
710
+ this.line(`${t}.some = ts_create_pda_address${fitSuffix(seeds)}(${seeds.name}, ${seeds.count}, ${program.c}, &${t}.v) == SUCCESS;`);
711
711
  return { c: t, type: { kind: "option", inner: PUBKEY } };
712
712
  }
713
713
  case "logBase64": {
@@ -738,7 +738,7 @@ export class CallEmitter extends ExpressionEmitter {
738
738
  const t = this.tmp("pda");
739
739
  const b = this.tmp("bump");
740
740
  this.line(`SolPubkey ${t}; uint8_t ${b};`);
741
- this.line(`if (ts_find_pda(${seeds.name}, ${seeds.count}, ${program.c}, &${t}, &${b}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no program address for these seeds");`);
741
+ this.line(`if (ts_find_pda${fitSuffix(seeds)}(${seeds.name}, ${seeds.count}, ${program.c}, &${t}, &${b}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no program address for these seeds");`);
742
742
  return { c: `(&${t})`, type: PUBKEY };
743
743
  }
744
744
  case "metadataAddress":
@@ -1222,6 +1222,15 @@ export class CallEmitter extends ExpressionEmitter {
1222
1222
  const hint = Object.hasOwn(hints, text) ? hints[text] : undefined;
1223
1223
  if (hint)
1224
1224
  return `unsupported call: ${text}; use ${hint}`;
1225
+ let bare = callee;
1226
+ while (ts.isParenthesizedExpression(bare))
1227
+ bare = bare.expression;
1228
+ if (ts.isArrowFunction(bare) || ts.isFunctionExpression(bare))
1229
+ return "a function called where it is written is not supported: bind it first (const f = (…) => …) and call f(…)";
1230
+ if (ts.isIdentifier(callee) && this.model.instructions.some((ix) => ix.node.name?.text === callee.text))
1231
+ return `${callee.text} is an instruction: one instruction cannot call another; move the shared code into a helper (a function that is not exported) and call it from both`;
1232
+ if (ts.isPropertyAccessExpression(callee) && ["call", "apply", "bind"].includes(callee.name.text) && !this.accountAt(callee.expression))
1233
+ return `${text}(…) is not supported: functions take what they use as parameters (there is no this); call ${callee.expression.getText()}(…) with them`;
1225
1234
  if (ts.isPropertyAccessExpression(callee) && this.accountAt(callee.expression))
1226
1235
  return `unsupported call: the account ${callee.expression.getText()} has no method ${callee.name.text}`;
1227
1236
  return `unsupported call: ${text.length > 60 ? `${text.slice(0, 57)}…` : text}`;
@@ -2731,6 +2740,18 @@ export class CallEmitter extends ExpressionEmitter {
2731
2740
  }
2732
2741
  const t = this.tmp();
2733
2742
  if (h.returns.kind === "struct") {
2743
+ const S = this.model.structs.get(h.returns.name);
2744
+ // To fit the stack, an instruction's result may live on the heap instead, one allocation per call site taken
2745
+ // when first reached (as a /** @heap */ local's), so a call in a loop reuses it as it reuses the stack slot.
2746
+ const decl = node.parent && ts.isParenthesizedExpression(node.parent) ? node.parent.parent : node.parent;
2747
+ const stackTag = !!decl && ts.isVariableDeclaration(decl) && this.stackTagged(decl);
2748
+ if (S?.size !== undefined && this.autoHeap(node, { name: `the result of ${h.display}()`, c: t, bytes: S.size, stack: stackTag })) {
2749
+ const sname = h.returns.name;
2750
+ this.hoistLazy(t, (n) => `TSS_${sname} *${n}`);
2751
+ this.line(`if (${t} == NULL) TS_TRY(ts_alloc(sizeof(TSS_${h.returns.name}), (uint8_t **)&${t}));`);
2752
+ this.line(`TS_TRY(fn_${h.name}(${[...args, t].join(", ")}));`);
2753
+ return { c: t, type: { kind: "structRef", struct: h.returns.name, writable: true } };
2754
+ }
2734
2755
  // The result lives in a local the caller owns: a reference to it reads and copies like any struct. Declared at
2735
2756
  // the top of the function, so a reference taken inside a block (a ternary's branch) stays valid after it.
2736
2757
  this.hoisted.push(` TSS_${h.returns.name} ${t};`);
@@ -2822,7 +2843,7 @@ export class CallEmitter extends ExpressionEmitter {
2822
2843
  if (r && r.type.kind === "option" && sameType(r.type.inner, want))
2823
2844
  r = this.someValue(r);
2824
2845
  if (!r || !sameType(r.type, want))
2825
- this.fail(n, `expected a ${typeName(want)}`);
2846
+ this.fail(n, `expected a ${typeName(want)}${this.parentNote(r?.type, want, n)}`);
2826
2847
  return this.snapshotPlace(r.lv, want, h, n);
2827
2848
  }
2828
2849
  case "dataEnumArg": {
@@ -9,11 +9,14 @@ export declare abstract class CpiCoreEmitter extends ViewEmitter {
9
9
  * the seeds in Anchor IDL terms when every element is a constant, an argument or an account path.
10
10
  * `withBump`: the list ends with its bump (signer seeds, createProgramAddress), so it may hold MAX_SEEDS entries;
11
11
  * otherwise the derivation adds the bump, and the list holds one fewer.
12
+ * `fit`: every seed's length is known here (at most 32 bytes; only a `string` value's is not), so a derivation can
13
+ * leave out the run-time check of the limits (the count is checked here in every case).
12
14
  */
13
15
  protected seeds(node: ts.Expression, extra: number, bound?: boolean, withBump?: boolean): {
14
16
  name: string;
15
17
  count: number;
16
18
  idl: IdlSeed[] | undefined;
19
+ fit: boolean;
17
20
  };
18
21
  /**
19
22
  * Whether evaluating `n` may run code or write (a call other than a pure one, an assignment, ++ / --). `readers`:
@@ -11,6 +11,8 @@ export class CpiCoreEmitter extends ViewEmitter {
11
11
  * the seeds in Anchor IDL terms when every element is a constant, an argument or an account path.
12
12
  * `withBump`: the list ends with its bump (signer seeds, createProgramAddress), so it may hold MAX_SEEDS entries;
13
13
  * otherwise the derivation adds the bump, and the list holds one fewer.
14
+ * `fit`: every seed's length is known here (at most 32 bytes; only a `string` value's is not), so a derivation can
15
+ * leave out the run-time check of the limits (the count is checked here in every case).
14
16
  */
15
17
  seeds(node, extra, bound = false, withBump = false) {
16
18
  if (!ts.isArrayLiteralExpression(node))
@@ -21,6 +23,7 @@ export class CpiCoreEmitter extends ViewEmitter {
21
23
  this.fail(node, `at most ${MAX_SEEDS - 1} seeds: the bump the derivation adds makes ${MAX_SEEDS}, Solana's limit`);
22
24
  const parts = [];
23
25
  let idl = [];
26
+ let fit = true;
24
27
  // The array points at its seeds, which are read when the CPI runs. Seeds that are not constants are copied when
25
28
  // the list is written, as JS reads them then, unless nothing can run between the list and the CPI that reads it:
26
29
  // no calls or writes among the seeds, nor in the other arguments of the call consuming the list (evaluated before
@@ -89,6 +92,9 @@ export class CpiCoreEmitter extends ViewEmitter {
89
92
  const t = this.tmp("seed");
90
93
  this.line(`TS_Str ${t} = ${this.ownedString(v).c};`);
91
94
  parts.push(`{${t}.ptr, ${t}.len}`);
95
+ // A string constant's length is known here; any other string's only at run time.
96
+ if (v.stringLiteral === undefined || Buffer.byteLength(v.stringLiteral, "utf8") > 32)
97
+ fit = false;
92
98
  }
93
99
  else if (v.type.kind === "int") {
94
100
  const typed = v.literal !== undefined ? this.literal(v.literal, U64, el) : v;
@@ -113,13 +119,13 @@ export class CpiCoreEmitter extends ViewEmitter {
113
119
  const reusable = extra === 0 && parts.length > 0 && this.lines.length === mark;
114
120
  const known = reusable ? this.seedArrays.get(key) : undefined;
115
121
  if (known && this.scopes.includes(known.scope) && this.lines[known.at]?.trim() === known.text)
116
- return { name: known.name, count: parts.length, idl };
122
+ return { name: known.name, count: parts.length, idl, fit };
117
123
  const name = this.tmp("seeds");
118
124
  const slots = parts.length + extra;
119
125
  this.line(`SolSignerSeed ${name}[${Math.max(slots, 1)}] = {${parts.join(", ")}};`);
120
126
  if (reusable)
121
127
  this.seedArrays.set(key, { name, scope: this.scopes[this.scopes.length - 1], at: this.lines.length - 1, text: this.lines.at(-1).trim() });
122
- return { name, count: parts.length, idl };
128
+ return { name, count: parts.length, idl, fit };
123
129
  }
124
130
  /**
125
131
  * Whether evaluating `n` may run code or write (a call other than a pure one, an assignment, ++ / --). `readers`:
@@ -264,7 +264,7 @@ export class CpiEmitter extends MetaplexEmitter {
264
264
  else if (ts.isShorthandPropertyAssignment(p))
265
265
  given.set(p.name.text, p.name);
266
266
  else
267
- this.fail(p, "use plain `field: value` entries");
267
+ this.fail(p, ts.isSpreadAssignment(p) ? "spread (...) is not supported in emit<T>(…): write each field, field: value" : "use plain `field: value` entries");
268
268
  }
269
269
  for (const k of given.keys())
270
270
  if (!s.fields.some((f) => f.name === k))
@@ -305,7 +305,9 @@ export class CpiEmitter extends MetaplexEmitter {
305
305
  else if (ts.isShorthandPropertyAssignment(p))
306
306
  fields.set(p.name.text, p.name);
307
307
  else
308
- this.fail(p, "use plain `field: value` entries");
308
+ this.fail(p, ts.isSpreadAssignment(p)
309
+ ? "spread (...) is not supported in an event's nested struct: write each field, field: value"
310
+ : "use plain `field: value` entries");
309
311
  }
310
312
  for (const k of fields.keys())
311
313
  if (!sd.fields.some((x) => x.name === k))
@@ -2,7 +2,7 @@ import ts from "typescript";
2
2
  import { heapVecOf } from "../analyze.js";
3
3
  import { borshMinSize } from "./borsh.js";
4
4
  import { isWritable } from "../model.js";
5
- import { U64, U8, BOOL, PUBKEY, scalarStorageC, optC, emptySizeC } from "./shared.js";
5
+ import { U64, U8, BOOL, PUBKEY, scalarStorageC, optC, emptySizeC, seedsCheckedMark } from "./shared.js";
6
6
  import { CpiCoreEmitter } from "./cpi-core.js";
7
7
  /** Creating accounts: `create` / `createIfNeeded` of program accounts, mints, token accounts and ATAs (with Token-2022 mint extensions), System transfers and createAccount. */
8
8
  export class CreateEmitter extends CpiCoreEmitter {
@@ -66,14 +66,14 @@ export class CreateEmitter extends CpiCoreEmitter {
66
66
  // Returns whether it was created now; an existing account must be this PDA, ours, and a ${s.name}.
67
67
  const created = this.tmp("created");
68
68
  this.line(`bool ${created};`);
69
- this.line(`TS_TRY(ts_create_pda_if_needed(params, a_${payer.name}, a_${target.name}, ${seeds.name}, ${seeds.count}, TS_DISC_${s.name}, ${space}, 8 + ${s.layout === "borsh" ? borshMinSize(s, this.model) : `sizeof(TSS_${s.name})`}, &${b}, &${created}));`);
69
+ this.line(`TS_TRY(ts_create_pda_if_needed(params, a_${payer.name}, a_${target.name}, ${seeds.name}, ${seeds.count}, TS_DISC_${s.name}, ${space}, 8 + ${s.layout === "borsh" ? borshMinSize(s, this.model) : `sizeof(TSS_${s.name})`}, &${b}, &${created}));${seedsCheckedMark(seeds)}`);
70
70
  // An existing @layout borsh account is unpacked now (a new one starts from the zeroed struct).
71
71
  if (s.layout === "borsh")
72
72
  this.line(`if (!${created}) TS_TRY(ts_unpack_${s.name}(a_${target.name}->data + 8, a_${target.name}->data_len - 8, d_${target.name}, NULL));`);
73
73
  done();
74
74
  return { c: created, type: BOOL };
75
75
  }
76
- this.line(`TS_TRY(ts_create_pda(params, a_${payer.name}, a_${target.name}, ${seeds.name}, ${seeds.count}, TS_DISC_${s.name}, ${space}, &${b}));`);
76
+ this.line(`TS_TRY(ts_create_pda(params, a_${payer.name}, a_${target.name}, ${seeds.name}, ${seeds.count}, TS_DISC_${s.name}, ${space}, &${b}));${seedsCheckedMark(seeds)}`);
77
77
  done();
78
78
  return { c: b, type: U8 };
79
79
  }
@@ -127,7 +127,7 @@ export class CreateEmitter extends CpiCoreEmitter {
127
127
  const tp = `a_${programs[0].name}`;
128
128
  const acct = `a_${target.name}`;
129
129
  // Seeds, then the values, in source order.
130
- let seeds = { name: "NULL", count: 0 };
130
+ let seeds = { name: "NULL", count: 0, fit: true };
131
131
  if (a[1].kind !== ts.SyntaxKind.NullKeyword) {
132
132
  const s = this.seeds(a[1], 1);
133
133
  this.recordPda(target, s.idl);
@@ -175,14 +175,14 @@ export class CreateEmitter extends CpiCoreEmitter {
175
175
  const createLines = [];
176
176
  if (isMint) {
177
177
  const [decimals, authority, freeze] = vals;
178
- createLines.push(`TS_TRY(ts_create_owned(params, a_${payer.name}, ${acct}, ${seeds.name}, ${seeds.count}, &${tp}->key, ${mintSpace}, &${b}));`, ...extLines, `TS_TRY(ts_token_init_mint(params, ${tp}, ${acct}, (uint8_t)(${decimals.c}), ${authority.c}, ${freeze ? freeze.c : "NULL"}));`);
178
+ createLines.push(`TS_TRY(ts_create_owned(params, a_${payer.name}, ${acct}, ${seeds.name}, ${seeds.count}, &${tp}->key, ${mintSpace}, &${b}));${seedsCheckedMark(seeds)}`, ...extLines, `TS_TRY(ts_token_init_mint(params, ${tp}, ${acct}, (uint8_t)(${decimals.c}), ${authority.c}, ${freeze ? freeze.c : "NULL"}));`);
179
179
  if (ifNeeded) {
180
180
  this.line(`bool ${created} = ts_key_eq(&${acct}->owner, &TS_SYSTEM_PROGRAM_ID);`);
181
181
  this.line(`if (${created}) {`);
182
182
  for (const l of createLines)
183
183
  this.line(` ${l}`);
184
184
  this.line(`} else {`);
185
- this.line(` TS_TRY(ts_token_existing(params, ${acct}, ${tp}, ${seeds.name}, ${seeds.count}, &${b}));`);
185
+ this.line(` TS_TRY(ts_token_existing(params, ${acct}, ${tp}, ${seeds.name}, ${seeds.count}, &${b}));${seedsCheckedMark(seeds)}`);
186
186
  this.line(` TS_TRY(ts_check_mint(${acct}));`);
187
187
  this.line(` TS_TRY(ts_check_mint_is(${acct}, (uint8_t)(${decimals.c}), ${authority.c}, ${freeze ? freeze.c : "NULL"}));`);
188
188
  for (const l of extChecks)
@@ -196,14 +196,14 @@ export class CreateEmitter extends CpiCoreEmitter {
196
196
  else {
197
197
  const [authority] = vals;
198
198
  const space = this.tmp("space");
199
- createLines.push(`uint64_t ${space};`, `TS_TRY(ts_token_account_space(params, ${tp}, a_${mint.name}, &${space}));`, `TS_TRY(ts_create_owned(params, a_${payer.name}, ${acct}, ${seeds.name}, ${seeds.count}, &${tp}->key, ${space}, &${b}));`, `TS_TRY(ts_token_init_account(params, ${tp}, ${acct}, a_${mint.name}, ${authority.c}));`);
199
+ createLines.push(`uint64_t ${space};`, `TS_TRY(ts_token_account_space(params, ${tp}, a_${mint.name}, &${space}));`, `TS_TRY(ts_create_owned(params, a_${payer.name}, ${acct}, ${seeds.name}, ${seeds.count}, &${tp}->key, ${space}, &${b}));${seedsCheckedMark(seeds)}`, `TS_TRY(ts_token_init_account(params, ${tp}, ${acct}, a_${mint.name}, ${authority.c}));`);
200
200
  if (ifNeeded) {
201
201
  this.line(`bool ${created} = ts_key_eq(&${acct}->owner, &TS_SYSTEM_PROGRAM_ID);`);
202
202
  this.line(`if (${created}) {`);
203
203
  for (const l of createLines)
204
204
  this.line(` ${l}`);
205
205
  this.line(`} else {`);
206
- this.line(` TS_TRY(ts_token_existing(params, ${acct}, ${tp}, ${seeds.name}, ${seeds.count}, &${b}));`);
206
+ this.line(` TS_TRY(ts_token_existing(params, ${acct}, ${tp}, ${seeds.name}, ${seeds.count}, &${b}));${seedsCheckedMark(seeds)}`);
207
207
  this.line(` TS_TRY(ts_check_token_account(${acct}));`);
208
208
  this.line(` if (!ts_key_eq(ts_token_mint(${acct}), &a_${mint.name}->key)) TS_FAIL(TS_ERR_TOKEN_MINT, "TypeSOL: ${target.name} is not a token account of ${mint.name}");`);
209
209
  this.line(` if (!ts_key_eq(ts_token_owner(${acct}), ${authority.c})) TS_FAIL(TS_ERR_TOKEN_OWNER, "TypeSOL: ${target.name} has another owner");`);
@@ -607,7 +607,7 @@ export class CreateEmitter extends CpiCoreEmitter {
607
607
  this.recordPda(ap, seeds.idl);
608
608
  const b = this.tmp("bump");
609
609
  this.line(`uint8_t ${b};`);
610
- this.line(`TS_TRY(ts_create_pda_owned(params, ${payer.c}, ${acct.c}, ${seeds.name}, ${seeds.count}, &${owner}, ${space}, &${b}));`);
610
+ this.line(`TS_TRY(ts_create_pda_owned(params, ${payer.c}, ${acct.c}, ${seeds.name}, ${seeds.count}, &${owner}, ${space}, &${b}));${seedsCheckedMark(seeds)}`);
611
611
  return { c: b, type: U8 };
612
612
  }
613
613
  /** systemProgram.allocate(account, space, signerSeeds?) / systemProgram.assign(account, owner, signerSeeds?). */
@@ -1,5 +1,5 @@
1
1
  import ts from "typescript";
2
- import { type IntName, type ScalarType, type ValueType } from "../model.js";
2
+ import { type FieldType, type IntName, type ScalarType, type ValueType } from "../model.js";
3
3
  import { type Value } from "./shared.js";
4
4
  import { StorageEmitter } from "./storage.js";
5
5
  /**
@@ -88,6 +88,13 @@ export declare abstract class ExpressionEmitter extends StorageEmitter {
88
88
  protected power(node: ts.BinaryExpression, hint?: ValueType): Value;
89
89
  private powerOf;
90
90
  protected binary(node: ts.BinaryExpression, hint?: ValueType): Value;
91
+ /**
92
+ * `===`, `!==`, `==` and `!=` compare integers, booleans, enums, Pubkeys and strings by value. Every other value is
93
+ * held in C by a pointer (or a view), and comparing those would compare where the values are, not what they hold:
94
+ * the compiler copies structs, lists and data enums where JavaScript would pass the same object (a helper's
95
+ * argument, a local declared with its type), so the result would not be JavaScript's. Refused, with what to compare.
96
+ */
97
+ protected refuseReferenceEquality(node: ts.BinaryExpression, type: ValueType | FieldType): void;
91
98
  /** Checked integer arithmetic into a fresh temporary. */
92
99
  protected arith(op: ts.BinaryOperator, left: Value, right: Value, node: ts.Node): Value;
93
100
  /** u256 arithmetic through the runtime's limb routines (checked like the other integers). */
@@ -232,6 +232,8 @@ export class ExpressionEmitter extends StorageEmitter {
232
232
  if (ts.isAsExpression(node) && ts.isTypeReferenceNode(node.type) && ts.isIdentifier(node.type.typeName) && node.type.typeName.text === "const")
233
233
  return this.expr(node.expression, hint);
234
234
  const t = resolveValueType(node.type, this.scope);
235
+ if ((!t || t.kind === "vecArg" || t.kind === "dataEnumArg") && ts.isSatisfiesExpression(node))
236
+ this.fail(node.type, `satisfies ${node.type.getText()} is not supported here: annotate the binding instead (const q: ${node.type.getText()} = …)`);
235
237
  if (!t || t.kind === "vecArg" || t.kind === "dataEnumArg")
236
238
  this.fail(node.type, "`as` names an integer, boolean, Pubkey, enum, option or string type the value already has");
237
239
  const v = this.expr(node.expression, t);
@@ -365,8 +367,16 @@ export class ExpressionEmitter extends StorageEmitter {
365
367
  return { c: `ts_u256_bit(${typed.c}, ts_u256_lit(~0ULL, ~0ULL, ~0ULL, ~0ULL), 2)`, type: typed.type };
366
368
  return { c: `((${INT_INFO[typed.type.name].c})~${typed.c})`, type: typed.type };
367
369
  }
370
+ if (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken)
371
+ this.fail(node, incrementAsValue(node));
368
372
  this.fail(node, "this operator is not supported");
369
373
  }
374
+ if (ts.isPostfixUnaryExpression(node))
375
+ this.fail(node, incrementAsValue(node));
376
+ if (ts.isVoidExpression(node))
377
+ this.fail(node, "void is not supported: call the function as a statement (its result is then unused)");
378
+ if (ts.isNewExpression(node))
379
+ this.fail(node, `new is not supported: ${/^new\s+(Map|Set)\b/.test(node.getText()) ? "a program has no Map or Set; keep entries in a FixedVec<T, N> of structs (or a FixedArray), or one account per key (a PDA)" : "there are no classes; build structs with object literals and lists with fixedVec([…]) / fixedArray<T, N>(fill)"}`);
370
380
  if (ts.isBinaryExpression(node))
371
381
  return this.binary(node, hint);
372
382
  if (ts.isConditionalExpression(node))
@@ -668,6 +678,8 @@ export class ExpressionEmitter extends StorageEmitter {
668
678
  // Surface the more specific message a call might give (e.g. loadAccount used inline).
669
679
  if (ts.isCallExpression(node.expression))
670
680
  this.call(node.expression, false);
681
+ if (node.expression.kind === ts.SyntaxKind.ThisKeyword)
682
+ this.fail(node.expression, "there is no this in TypeSOL: a function takes what it uses as parameters (p: Point, then p.x)");
671
683
  this.fail(node, "unsupported property access");
672
684
  }
673
685
  /** Whether TypeScript sees this expression as a string (decides `+` between concatenation and arithmetic). */
@@ -1051,6 +1063,8 @@ export class ExpressionEmitter extends StorageEmitter {
1051
1063
  this.fail(node.operatorToken, ">>> does not exist for bigint; use >>");
1052
1064
  const isBit = op === K.AmpersandToken || op === K.BarToken || op === K.CaretToken;
1053
1065
  const isArith = op === K.PlusToken || op === K.MinusToken || op === K.AsteriskToken || op === K.SlashToken || op === K.PercentToken || isBit;
1066
+ if (!isEq && !isCmp && !isArith && op >= K.FirstAssignment && op <= K.LastAssignment)
1067
+ this.fail(node.operatorToken, `an assignment (${node.operatorToken.getText()}) is a statement in TypeSOL, not a value: write ${node.left.getText()} ${node.operatorToken.getText()} …; on its own line, then read ${node.left.getText()}`);
1054
1068
  if (!isEq && !isCmp && !isArith)
1055
1069
  this.fail(node.operatorToken, `operator ${node.operatorToken.getText()} is not supported`);
1056
1070
  // Lower the non-literal side first so a literal on the other side takes its type.
@@ -1072,6 +1086,7 @@ export class ExpressionEmitter extends StorageEmitter {
1072
1086
  const neg = op === K.ExclamationEqualsEqualsToken || op === K.ExclamationEqualsToken;
1073
1087
  const opt = (left.type.kind === "option" ? left.type : right.type);
1074
1088
  const inner = opt.inner;
1089
+ this.refuseReferenceEquality(node, opt);
1075
1090
  const valueEq = (a, b) => inner.kind === "pubkey" ? `ts_key_eq(&${a}, &${b})` : inner.kind === "bool" ? `((${a} != 0) == (${b} != 0))` : `(${a} == ${b})`;
1076
1091
  const hold = (v, nodeOf) => {
1077
1092
  const t = this.tmp("oq");
@@ -1114,6 +1129,7 @@ export class ExpressionEmitter extends StorageEmitter {
1114
1129
  this.fail(node, `operands have different types: ${typeName(left.type)} and ${typeName(right.type)}; convert with u64(...) etc.`);
1115
1130
  if (isEq) {
1116
1131
  const neg = op === K.ExclamationEqualsEqualsToken || op === K.ExclamationEqualsToken;
1132
+ this.refuseReferenceEquality(node, left.type);
1117
1133
  const c = left.type.kind === "pubkey"
1118
1134
  ? `ts_key_eq(${left.c}, ${right.c})`
1119
1135
  : left.type.kind === "string"
@@ -1131,6 +1147,47 @@ export class ExpressionEmitter extends StorageEmitter {
1131
1147
  return { c: `(${left.c} ${node.operatorToken.getText()} ${right.c})`, type: BOOL };
1132
1148
  return this.arith(op, left, right, node);
1133
1149
  }
1150
+ /**
1151
+ * `===`, `!==`, `==` and `!=` compare integers, booleans, enums, Pubkeys and strings by value. Every other value is
1152
+ * held in C by a pointer (or a view), and comparing those would compare where the values are, not what they hold:
1153
+ * the compiler copies structs, lists and data enums where JavaScript would pass the same object (a helper's
1154
+ * argument, a local declared with its type), so the result would not be JavaScript's. Refused, with what to compare.
1155
+ */
1156
+ refuseReferenceEquality(node, type) {
1157
+ // The token's own text: the comparison may be one the compiler built (no source text behind it).
1158
+ const op = ts.tokenToString(node.operatorToken.kind) ?? "this comparison";
1159
+ const t = type;
1160
+ switch (t.kind) {
1161
+ case "int":
1162
+ case "bool":
1163
+ case "enum":
1164
+ case "pubkey":
1165
+ case "string":
1166
+ return;
1167
+ case "option":
1168
+ case "optionArg":
1169
+ if (t.kind === "option" && t.inner && ["int", "bool", "enum", "pubkey"].includes(t.inner.kind))
1170
+ return;
1171
+ this.fail(node, `${op} on two Options of a struct is not supported (it would compare where they are held, not their contents): compare each with null, then compare the fields you need`);
1172
+ case "struct":
1173
+ case "structRef":
1174
+ this.fail(node, `${op} on two structs is not supported: it would compare where they are held, not their contents, and a struct passed to a helper or declared with its type is a copy; compare the fields you need (a.x === b.x && …)`);
1175
+ case "dataEnum":
1176
+ case "enumRef":
1177
+ case "dataEnumArg":
1178
+ this.fail(node, `${op} on two data enums is not supported: it would compare where they are held, not their contents; compare .kind, then the fields of the narrowed variants`);
1179
+ case "vec":
1180
+ case "vecArg":
1181
+ case "array":
1182
+ case "arrayArg":
1183
+ case "rawArray":
1184
+ this.fail(node, `${op} on two lists is not supported: it would compare where they are held, not their contents; compare .length and the elements (.get(i))`);
1185
+ case "account":
1186
+ this.fail(node, `${op} on two accounts is not supported: it would compare where their records are held; compare their addresses (a.key === b.key)`);
1187
+ default:
1188
+ this.fail(node, `${op} is not supported on ${typeName(type)} values: compare their fields or their integer values`);
1189
+ }
1190
+ }
1134
1191
  /** Checked integer arithmetic into a fresh temporary. */
1135
1192
  arith(op, left, right, node) {
1136
1193
  this.refuseF64(node, ts.tokenToString(op) ?? "arithmetic", left, right);
@@ -1303,3 +1360,11 @@ export class ExpressionEmitter extends StorageEmitter {
1303
1360
  return { c: t, type: to };
1304
1361
  }
1305
1362
  }
1363
+ /** `const old = i++`: what to write for ++ / -- used as a value. */
1364
+ function incrementAsValue(node) {
1365
+ const op = node.operator === ts.SyntaxKind.PlusPlusToken ? "++" : "--";
1366
+ const x = node.operand.getText();
1367
+ return ts.isPostfixUnaryExpression(node)
1368
+ ? `${x}${op} is a statement in TypeSOL, not a value: read ${x} into a const first, then write ${x}${op}; on its own line`
1369
+ : `${op}${x} is a statement in TypeSOL, not a value: write ${x}${op}; on its own line, then read ${x}`;
1370
+ }
@@ -6,6 +6,8 @@ import { StatementEmitter } from "./statements.js";
6
6
  * argument decoding), the body, and the epilogue.
7
7
  */
8
8
  export declare class FunctionEmitter extends StatementEmitter {
9
+ /** The C types of the program's structs and data enums with no pointer field (settleScopes). */
10
+ private pointerFreeStructs;
9
11
  emitHelper(): string;
10
12
  emitInstruction(): string;
11
13
  /**
@@ -3,13 +3,58 @@ import { snakeCase, argIdlName, fieldIdlName } from "../analyze.js";
3
3
  import { decodeAddress } from "../../keys.js";
4
4
  import { INT_INFO, isScalar, isWritable, scalarSize, typeName, } from "../model.js";
5
5
  import { borshIdentical, borshMinSize } from "./borsh.js";
6
- import { BOOL, accountLimit, ATA_PROGRAM_BYTES, cBytes, cString, optC, fieldC, storageDecl, helperSignature, emptySizeC, vecLenCheck } from "./shared.js";
6
+ import { BOOL, accountLimit, ATA_PROGRAM_BYTES, cBytes, cString, optC, fixedVecC, fieldC, storageDecl, helperSignature, emptySizeC, vecLenCheck, fitSuffix, } from "./shared.js";
7
7
  import { StatementEmitter } from "./statements.js";
8
+ import { settleScopes } from "./outline.js";
8
9
  /**
9
10
  * One instruction or helper as a C function: the instruction prologue (account checks, constraints and
10
11
  * argument decoding), the body, and the epilogue.
11
12
  */
12
13
  export class FunctionEmitter extends StatementEmitter {
14
+ /** The C types of the program's structs and data enums with no pointer field (settleScopes). */
15
+ pointerFreeStructs() {
16
+ const seen = new Map();
17
+ const free = (t) => {
18
+ switch (t.kind) {
19
+ case "string":
20
+ return false;
21
+ case "array":
22
+ return free(t.elem);
23
+ case "option":
24
+ return free(t.inner);
25
+ case "vec":
26
+ return !t.heap && free(t.elem);
27
+ case "struct":
28
+ case "dataEnum": {
29
+ const key = `${t.kind}:${t.name}`;
30
+ if (!seen.has(key)) {
31
+ seen.set(key, false); // a cycle has no C layout anyway
32
+ const fields = t.kind === "struct" ? this.model.structs.get(t.name)?.fields : this.model.dataEnums.get(t.name)?.variants.flatMap((v) => v.fields);
33
+ seen.set(key, !!fields && fields.every((f) => free(f.type)));
34
+ }
35
+ return seen.get(key);
36
+ }
37
+ default:
38
+ return true;
39
+ }
40
+ };
41
+ const out = new Set();
42
+ for (const s of this.model.structs.values())
43
+ if (s.size !== undefined && free({ kind: "struct", name: s.name }))
44
+ out.add(`TSS_${s.name}`);
45
+ for (const e of this.model.dataEnums.values())
46
+ if (free({ kind: "dataEnum", name: e.name }))
47
+ out.add(`TSE_${e.name}`);
48
+ for (const inner of this.model.options.values())
49
+ if (free({ kind: "option", inner }))
50
+ out.add(optC(inner));
51
+ for (const cap of this.model.fstrings)
52
+ out.add(`TS_FStr${cap}`);
53
+ for (const t of this.model.localVecs.values())
54
+ if (t.cap !== undefined && free(t))
55
+ out.add(fixedVecC(t));
56
+ return out;
57
+ }
13
58
  emitHelper() {
14
59
  const h = this.helper;
15
60
  this.scopes = [new Map()];
@@ -21,7 +66,8 @@ export class FunctionEmitter extends StatementEmitter {
21
66
  this.reporter.guard(() => this.statement(stmt));
22
67
  // A helper with a result must return one; falling off the end would leave it unset.
23
68
  const end = h.returns ? ` TS_FAIL(TS_ERR_NO_RETURN, "TypeSOL: ${h.display} ended without returning a value");` : ` return SUCCESS;`;
24
- return [...this.outlinedLoops, `${helperSignature(h)} {`, ...this.hoisted, ...this.lines, end, `}`].join("\n");
69
+ const text = [...this.outlinedLoops, `${helperSignature(h, this.stack.noinline)} {`, ...this.hoisted, ...this.lines, end, `}`].join("\n");
70
+ return this.scopeTemps ? settleScopes(text, this.pointerFreeStructs()) : text;
25
71
  }
26
72
  emitInstruction() {
27
73
  const ix = this.ix;
@@ -86,7 +132,7 @@ export class FunctionEmitter extends StatementEmitter {
86
132
  head.push(` TS_TRY(ts_check_address(${v}, &TS_INSTRUCTIONS_SYSVAR_ID));`);
87
133
  if (k.kind === "eventAuthority" && this.eventAuthorityByAddress)
88
134
  // Anchor 1.x: the address is checked among the constraints (constraintChecks); here only the PDA and its bump.
89
- head.push(` uint8_t eb_${a.name};`, ` SolPubkey ek_${a.name};`, ` { SolSignerSeed s = {(const uint8_t *)"__event_authority", 17}; if (ts_find_pda(&s, 1, params->program_id, &ek_${a.name}, &eb_${a.name}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no event authority"); }`);
135
+ head.push(` uint8_t eb_${a.name};`, ` SolPubkey ek_${a.name};`, ` { SolSignerSeed s = {(const uint8_t *)"__event_authority", 17}; if (ts_find_pda_fit(&s, 1, params->program_id, &ek_${a.name}, &eb_${a.name}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no event authority"); }`);
90
136
  else if (k.kind === "eventAuthority")
91
137
  head.push(` uint8_t eb_${a.name};`, ` TS_TRY(ts_check_event_authority(${v}, params->program_id, &eb_${a.name}));`);
92
138
  if (k.kind === "selfProgram" && !this.eventAuthorityByAddress)
@@ -499,7 +545,8 @@ export class FunctionEmitter extends StatementEmitter {
499
545
  // The Clock cache is declared first: a constraint (in the head) may read the Clock before the body does.
500
546
  const clock = this.hoisted.filter((l) => l.includes("ts_clk_ok"));
501
547
  const hoisted = this.hoisted.filter((l) => !clock.includes(l));
502
- return [...this.outlinedLoops, head[0], ...clock, ...head.slice(1), ...hoisted, ...this.lines, ...end, `}`].join("\n");
548
+ const text = [...this.outlinedLoops, head[0], ...clock, ...head.slice(1), ...hoisted, ...this.lines, ...end, `}`].join("\n");
549
+ return this.scopeTemps ? settleScopes(text, this.pointerFreeStructs()) : text;
503
550
  }
504
551
  /**
505
552
  * How many statements at the start of `body` create this instruction's Init / InitIfNeeded accounts
@@ -761,6 +808,9 @@ export class FunctionEmitter extends StatementEmitter {
761
808
  const c = a.constraints;
762
809
  const parts = [];
763
810
  const idl = [];
811
+ // Every seed's length known here (only a string argument's is not; the count was checked when the seeds were
812
+ // read): the derivation leaves out the run-time check of the limits.
813
+ let fit = true;
764
814
  for (const named of c.seeds.names) {
765
815
  // "@name" refers to an account parameter (its key) or an argument (its bytes); anything else is a literal.
766
816
  // "@name:be" takes an integer's bytes most significant first (Rust's `to_be_bytes()`).
@@ -816,8 +866,10 @@ export class FunctionEmitter extends StatementEmitter {
816
866
  parts.push(intSeed(`arg_${n}`, scalarSize(t)));
817
867
  else if (notInt())
818
868
  return out;
819
- else if (t.kind === "string")
869
+ else if (t.kind === "string") {
820
870
  parts.push(`{arg_${n}.ptr, arg_${n}.len}`);
871
+ fit = false;
872
+ }
821
873
  else if (t.kind === "pubkey")
822
874
  parts.push(`{(const uint8_t *)&arg_${n}, 32}`);
823
875
  else if (t.kind === "enum")
@@ -861,13 +913,13 @@ export class FunctionEmitter extends StatementEmitter {
861
913
  // The account's own bump field, or "@acct.field": one stored in another struct account.
862
914
  const bump = c.seeds.bump.startsWith("@") ? `d_${c.seeds.bump.slice(1).replace(".", "->")}` : `d_${a.name}->${c.seeds.bump}`;
863
915
  out.push(` ${seeds}[${parts.length}] = (SolSignerSeed){&${bump}, 1};`);
864
- out.push(` TS_TRY(ts_require_pda(a_${a.name}, ${seeds}, ${parts.length + 1}, ${program}));`);
916
+ out.push(` TS_TRY(ts_require_pda${fitSuffix({ fit })}(a_${a.name}, ${seeds}, ${parts.length + 1}, ${program}));`);
865
917
  this.bumps.set(a.name, bump);
866
918
  }
867
919
  else {
868
920
  bumpDecls.push(` uint8_t sb_${a.name}; (void)sb_${a.name};`);
869
921
  out.push(` { SolPubkey pda_${a.name};`);
870
- out.push(` if (ts_find_pda(${seeds}, ${parts.length}, ${program}, &pda_${a.name}, &sb_${a.name}) != SUCCESS || !ts_key_eq(&pda_${a.name}, &a_${a.name}->key)) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: ${a.name} is not the expected PDA"); }`);
922
+ out.push(` if (ts_find_pda${fitSuffix({ fit })}(${seeds}, ${parts.length}, ${program}, &pda_${a.name}, &sb_${a.name}) != SUCCESS || !ts_key_eq(&pda_${a.name}, &a_${a.name}->key)) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: ${a.name} is not the expected PDA"); }`);
871
923
  this.bumps.set(a.name, `sb_${a.name}`);
872
924
  }
873
925
  return out;
@@ -22,3 +22,38 @@ export declare function declaredNames(toks: string[]): Set<string>;
22
22
  export declare function isGlobalName(n: string): boolean;
23
23
  /** A C parameter list (`TsParams *params, uint64_t p_rest`) as name → declaration. */
24
24
  export declare function parameterDecls(signature: string): Map<string, string>;
25
+ /** The comment that marks the C blocks StackPlan.scope opens around statements: `ts_scope_3{` before the `{`, `ts_scope_3}` before the `}`. */
26
+ export declare const SCOPE_MARK = "ts_scope_";
27
+ /**
28
+ * The C of a function (with the loops moved out of it) whose statements were put in blocks of their own: each block
29
+ * stays, without its mark, unless taking its names out of scope could change the program, and then only its braces
30
+ * go. A block keeps its braces only when all of these hold (`own`: the names it declares, C's own types and the
31
+ * runtime's declaring macros included):
32
+ *
33
+ * 1. no name of `own` is used after it (a bump a later check reads, a seed list a later statement reuses);
34
+ * 2. no assignment to a variable declared outside it stores `&x` or an array, pointer or aggregate it declares not
35
+ * read through a field or an index (storesAddress);
36
+ * 3. no address of its storage can reach memory that outlives it (leaksAddress), with or without an `=`.
37
+ *
38
+ * Rule 3 follows, through every statement of the block until nothing changes, which expressions may hold an address
39
+ * of the block's storage: `&x` of a local of `own` (`&p->f` through a pointer of `own` points where the pointer does),
40
+ * an array of `own` not indexed, a local of `own` that was assigned such an expression (a *holder*, read whole or in
41
+ * part), and what ts_str and ts_fstr_view build of one; a field or element of a local of `own` may be an array that
42
+ * decays to such an address, which a number or a struct cannot take. The block loses its braces when such an
43
+ * expression
44
+ *
45
+ * - is assigned to anything but a local of `own`: a variable declared outside it, or a place reached through a
46
+ * pointer, a cast or a macro (`*p`, `p->f`, `p[i]`, `*(T *)…`, the meta list a TS_METAS macro declares, which may
47
+ * be heap scratch); a field or element only counts where a pointer may be, not in a number or in a struct of a
48
+ * type with no pointer field (`pointerFree`: the program's types, from the emitter) reached by fields, indexes and
49
+ * one dereference;
50
+ * - is returned;
51
+ * - is an argument of a call other than the runtime functions and macros that keep nothing of their arguments
52
+ * (KEEPS_NOTHING, the program's helpers and loops among them) and copies (COPIES), or of any call through a
53
+ * field or a local; a copy takes them away only when what it moves may itself hold such an address (a holder's
54
+ * own bytes, or what a holder pointing at a holder points to).
55
+ *
56
+ * Anything the analysis cannot follow (a function or macro not on the lists, an unknown declaration) is taken to keep
57
+ * what it is given, so the braces stay only where no address of the block can be read after it.
58
+ */
59
+ export declare function settleScopes(c: string, pointerFree?: ReadonlySet<string>): string;