@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
@@ -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
  /**
@@ -86,7 +86,15 @@ export declare abstract class ExpressionEmitter extends StorageEmitter {
86
86
  * that overflows then would make the result overflow too). A negative exponent aborts, as JS throws a RangeError.
87
87
  */
88
88
  protected power(node: ts.BinaryExpression, hint?: ValueType): Value;
89
+ private powerOf;
89
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;
90
98
  /** Checked integer arithmetic into a fresh temporary. */
91
99
  protected arith(op: ts.BinaryOperator, left: Value, right: Value, node: ts.Node): Value;
92
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). */
@@ -900,6 +912,18 @@ export class ExpressionEmitter extends StorageEmitter {
900
912
  const exp = this.expr(node.right);
901
913
  // JS reads the base first: if the exponent ran statements (a helper that changes it), use the value read before.
902
914
  base = this.settle(base, mark);
915
+ // Inside panicsAt the operands keep its location, but `**` itself keeps TypeSOL's failure (5100 on overflow):
916
+ // Rust's `pow` panics with other messages, so its multiplications do not take the panic.
917
+ const outer = this.panicAt;
918
+ this.panicAt = undefined;
919
+ try {
920
+ return this.powerOf(node, hint, base, exp);
921
+ }
922
+ finally {
923
+ this.panicAt = outer;
924
+ }
925
+ }
926
+ powerOf(node, hint, base, exp) {
903
927
  this.refuseF64(node, "**", base, exp);
904
928
  if (base.literal !== undefined)
905
929
  base = this.literal(base.literal, hint?.kind === "int" ? hint : U64, node.left);
@@ -1039,6 +1063,8 @@ export class ExpressionEmitter extends StorageEmitter {
1039
1063
  this.fail(node.operatorToken, ">>> does not exist for bigint; use >>");
1040
1064
  const isBit = op === K.AmpersandToken || op === K.BarToken || op === K.CaretToken;
1041
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()}`);
1042
1068
  if (!isEq && !isCmp && !isArith)
1043
1069
  this.fail(node.operatorToken, `operator ${node.operatorToken.getText()} is not supported`);
1044
1070
  // Lower the non-literal side first so a literal on the other side takes its type.
@@ -1060,6 +1086,7 @@ export class ExpressionEmitter extends StorageEmitter {
1060
1086
  const neg = op === K.ExclamationEqualsEqualsToken || op === K.ExclamationEqualsToken;
1061
1087
  const opt = (left.type.kind === "option" ? left.type : right.type);
1062
1088
  const inner = opt.inner;
1089
+ this.refuseReferenceEquality(node, opt);
1063
1090
  const valueEq = (a, b) => inner.kind === "pubkey" ? `ts_key_eq(&${a}, &${b})` : inner.kind === "bool" ? `((${a} != 0) == (${b} != 0))` : `(${a} == ${b})`;
1064
1091
  const hold = (v, nodeOf) => {
1065
1092
  const t = this.tmp("oq");
@@ -1102,6 +1129,7 @@ export class ExpressionEmitter extends StorageEmitter {
1102
1129
  this.fail(node, `operands have different types: ${typeName(left.type)} and ${typeName(right.type)}; convert with u64(...) etc.`);
1103
1130
  if (isEq) {
1104
1131
  const neg = op === K.ExclamationEqualsEqualsToken || op === K.ExclamationEqualsToken;
1132
+ this.refuseReferenceEquality(node, left.type);
1105
1133
  const c = left.type.kind === "pubkey"
1106
1134
  ? `ts_key_eq(${left.c}, ${right.c})`
1107
1135
  : left.type.kind === "string"
@@ -1119,6 +1147,47 @@ export class ExpressionEmitter extends StorageEmitter {
1119
1147
  return { c: `(${left.c} ${node.operatorToken.getText()} ${right.c})`, type: BOOL };
1120
1148
  return this.arith(op, left, right, node);
1121
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
+ }
1122
1191
  /** Checked integer arithmetic into a fresh temporary. */
1123
1192
  arith(op, left, right, node) {
1124
1193
  this.refuseF64(node, ts.tokenToString(op) ?? "arithmetic", left, right);
@@ -1291,3 +1360,11 @@ export class ExpressionEmitter extends StorageEmitter {
1291
1360
  return { c: t, type: to };
1292
1361
  }
1293
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;
@@ -64,7 +110,7 @@ export class FunctionEmitter extends StatementEmitter {
64
110
  const n = k.struct.accountDiscriminator.length;
65
111
  // A shorter discriminator (another program's zero-copy account): AccountLoader's checks with its length.
66
112
  if (n !== 8)
67
- head.push(` if (!ts_key_eq(&${v}->owner, ${owner})) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: ${a.name} is not owned by the expected program");`, ` if (${v}->data_len < ${n}) TS_FAIL(TS_ERR_DISC_NOT_FOUND, "TypeSOL: ${a.name} has no discriminator");`, ` if (!ts_mem_eq(${v}->data, TS_DISC_${k.struct.name}, ${n})) TS_FAIL(TS_ERR_DISCRIMINATOR, "TypeSOL: ${a.name}: discriminator mismatch");`, ` if (${v}->data_len < ${n} + ${emptySizeC(k.struct)}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: ${a.name} is too small");`);
113
+ head.push(` if (!ts_key_eq(&${v}->owner, ${owner})) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: ${a.name} is not owned by the expected program");`, ` if (${v}->data_len < ${n}) TS_FAIL(TS_ERR_DISC_NOT_FOUND, "TypeSOL: ${a.name} has no discriminator");`, ` if (!ts_mem_eq(${v}->data, TS_DISC_${k.struct.name}, ${n})) TS_FAIL(TS_ERR_DISCRIMINATOR, "TypeSOL: ${a.name}: discriminator mismatch");`, ` if (${v}->data_len < ${n} + ${k.struct.layout === "borsh" ? borshMinSize(k.struct, this.model) : emptySizeC(k.struct)}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: ${a.name} is too small");`);
68
114
  else
69
115
  head.push(k.struct.idlMeta?.serialization?.startsWith("bytemuck")
70
116
  ? ` TS_TRY(ts_check_loader_account(${v}, ${owner}, TS_DISC_${k.struct.name}, ${emptySizeC(k.struct)}));`
@@ -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)
@@ -144,15 +190,18 @@ export class FunctionEmitter extends StatementEmitter {
144
190
  // unused slots start as zero: ts_unpack_* only writes what the Borsh bytes hold.
145
191
  const S = k.struct.name;
146
192
  head.push(` TSS_${S} *d_${a.name} = NULL;`, ` TS_TRY(ts_alloc(sizeof(TSS_${S}), (uint8_t **)&d_${a.name}));`);
193
+ // The Borsh bytes start after the discriminator, of whichever length the struct declares (the checks above
194
+ // ensured the account holds it and the smallest Borsh form after it).
195
+ const n = k.struct.accountDiscriminator.length;
147
196
  if (k.kind === "account")
148
- head.push(` TS_TRY(ts_unpack_${S}(${v}->data + 8, ${v}->data_len - 8, d_${a.name}, NULL));`);
197
+ head.push(` TS_TRY(ts_unpack_${S}(${v}->data + ${n}, ${v}->data_len - ${n}, d_${a.name}, NULL));`);
149
198
  }
150
199
  else if (k.kind === "account" || k.kind === "init" || k.kind === "zeroed" || k.kind === "initIfNeeded") {
151
200
  head.push(` TSS_${k.struct.name} *d_${a.name} = (TSS_${k.struct.name} *)(${v}->data + ${k.struct.accountDiscriminator.length});`);
152
201
  if (k.struct.vec) {
153
202
  head.push(` uint64_t entry_${a.name} = ${v}->data_len;`, ` (void)entry_${a.name};`);
154
203
  if (k.kind === "account")
155
- head.push(...vecLenCheck(k.struct, v, `d_${a.name}`));
204
+ head.push(...vecLenCheck(k.struct, v, `d_${a.name}`, " ", k.struct.accountDiscriminator.length));
156
205
  }
157
206
  }
158
207
  // realloc(x, …) needs the size the account had when the instruction started (the 10 KiB growth limit), as does
@@ -366,7 +415,7 @@ export class FunctionEmitter extends StatementEmitter {
366
415
  const ft = a.type.kind === "structRef" ? { kind: "struct", name: a.type.struct } : a.type.array;
367
416
  const size = this.fieldBytes(ft);
368
417
  need(String(size));
369
- head.push(` ${decl};`, ` TS_TRY(ts_alloc(${size}, (uint8_t **)&${v}));`, ` ts_memcpy(${v}, ${at}, ${size});`, ` off += ${size};`);
418
+ head.push(` ${decl};`, ` TS_TRY(ts_alloc(${size}, (uint8_t **)&${v}));`, ` TS_MEMCPY(${v}, ${at}, ${size});`, ` off += ${size};`);
370
419
  head.push(...this.validation(`(*${v})`, ft, " "));
371
420
  }
372
421
  else if (a.type.kind === "dataEnumArg") {
@@ -374,7 +423,7 @@ export class FunctionEmitter extends StatementEmitter {
374
423
  const e = this.model.dataEnums.get(a.type.name);
375
424
  const v = `arg_${a.name}__v`;
376
425
  need("1");
377
- head.push(` TSE_${e.name} ${v};`, ` ts_memzero(&${v}, sizeof(${v}));`, ` ${v}.tag = *(${at});`, ` off += 1;`);
426
+ head.push(` TSE_${e.name} ${v};`, ` TS_ZERO_LOCAL(&${v}, sizeof(${v}));`, ` ${v}.tag = *(${at});`, ` off += 1;`);
378
427
  head.push(` switch (${v}.tag) {`);
379
428
  e.variants.forEach((variant, i) => {
380
429
  head.push(` case ${i}: {`);
@@ -394,7 +443,7 @@ export class FunctionEmitter extends StatementEmitter {
394
443
  const lv = `${v}.v.${variant.name}.${f.name}`;
395
444
  const size = this.fieldBytes(f.type);
396
445
  head.push(` if (params->data_len < off + ${size}) TS_FAIL(TS_ERR_INSTRUCTION_DATA, "TypeSOL: instruction data too short");`);
397
- head.push(` ts_memcpy(&${lv}, params->data + off, ${size});`, ` off += ${size};`);
446
+ head.push(` TS_MEMCPY(&${lv}, params->data + off, ${size});`, ` off += ${size};`);
398
447
  head.push(...this.validation(lv, f.type, " "));
399
448
  continue;
400
449
  }
@@ -496,7 +545,8 @@ export class FunctionEmitter extends StatementEmitter {
496
545
  // The Clock cache is declared first: a constraint (in the head) may read the Clock before the body does.
497
546
  const clock = this.hoisted.filter((l) => l.includes("ts_clk_ok"));
498
547
  const hoisted = this.hoisted.filter((l) => !clock.includes(l));
499
- 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;
500
550
  }
501
551
  /**
502
552
  * How many statements at the start of `body` create this instruction's Init / InitIfNeeded accounts
@@ -549,14 +599,15 @@ export class FunctionEmitter extends StatementEmitter {
549
599
  .map((a) => {
550
600
  const v = `a_${a.name}`;
551
601
  const S = a.kind.struct.name;
552
- return `if (${a.optional ? `${v} != NULL && ` : ""}${v}->data_len >= 8 && ts_key_eq(&${v}->owner, params->program_id)) TS_TRY(ts_pack_${S}(d_${a.name}, ${v}->data + 8, ${v}->data_len - 8, NULL));`;
602
+ const n = a.kind.struct.accountDiscriminator.length;
603
+ return `if (${a.optional ? `${v} != NULL && ` : ""}${v}->data_len >= ${n} && ts_key_eq(&${v}->owner, params->program_id)) TS_TRY(ts_pack_${S}(d_${a.name}, ${v}->data + ${n}, ${v}->data_len - ${n}, NULL));`;
553
604
  });
554
605
  return [
555
606
  ...packs,
556
607
  ...this.ix.accounts
557
608
  .filter((a) => a.constraints.closeTo)
558
609
  .map((a) => {
559
- const line = `TS_TRY(ts_close(a_${a.name}, a_${a.constraints.closeTo}));`;
610
+ const line = `TS_TRY(${this.closeCall(a, `a_${a.constraints.closeTo}`)});`;
560
611
  const optional = this.optionalIn(line);
561
612
  return optional.length ? `if (${optional.map((n) => `a_${n} != NULL`).join(" && ")}) ${line}` : line;
562
613
  }),
@@ -757,6 +808,9 @@ export class FunctionEmitter extends StatementEmitter {
757
808
  const c = a.constraints;
758
809
  const parts = [];
759
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;
760
814
  for (const named of c.seeds.names) {
761
815
  // "@name" refers to an account parameter (its key) or an argument (its bytes); anything else is a literal.
762
816
  // "@name:be" takes an integer's bytes most significant first (Rust's `to_be_bytes()`).
@@ -812,8 +866,10 @@ export class FunctionEmitter extends StatementEmitter {
812
866
  parts.push(intSeed(`arg_${n}`, scalarSize(t)));
813
867
  else if (notInt())
814
868
  return out;
815
- else if (t.kind === "string")
869
+ else if (t.kind === "string") {
816
870
  parts.push(`{arg_${n}.ptr, arg_${n}.len}`);
871
+ fit = false;
872
+ }
817
873
  else if (t.kind === "pubkey")
818
874
  parts.push(`{(const uint8_t *)&arg_${n}, 32}`);
819
875
  else if (t.kind === "enum")
@@ -857,13 +913,13 @@ export class FunctionEmitter extends StatementEmitter {
857
913
  // The account's own bump field, or "@acct.field": one stored in another struct account.
858
914
  const bump = c.seeds.bump.startsWith("@") ? `d_${c.seeds.bump.slice(1).replace(".", "->")}` : `d_${a.name}->${c.seeds.bump}`;
859
915
  out.push(` ${seeds}[${parts.length}] = (SolSignerSeed){&${bump}, 1};`);
860
- 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}));`);
861
917
  this.bumps.set(a.name, bump);
862
918
  }
863
919
  else {
864
920
  bumpDecls.push(` uint8_t sb_${a.name}; (void)sb_${a.name};`);
865
921
  out.push(` { SolPubkey pda_${a.name};`);
866
- 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"); }`);
867
923
  this.bumps.set(a.name, `sb_${a.name}`);
868
924
  }
869
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;