@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
@@ -375,6 +375,8 @@ export function analyze(entry, files) {
375
375
  /** Program-wide names (structs, enums, helpers) -> declaring file, for collision errors. */
376
376
  const declared = new Map();
377
377
  let entryImports = new Map();
378
+ /** The names of every interface and type alias, to tell which declarations failed (see brokenTypes). */
379
+ const typeDecls = new Set();
378
380
  const isExported = (n) => ts.canHaveModifiers(n) && (ts.getModifiers(n) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
379
381
  const declare = (name, file) => {
380
382
  // These prefixes name the IDL types TypeSOL generates for FixedString<N>, Option and data enums in account data.
@@ -410,22 +412,41 @@ export function analyze(entry, files) {
410
412
  }
411
413
  }
412
414
  else if (ts.isInterfaceDeclaration(stmt)) {
415
+ typeDecls.add(stmt.name.text);
413
416
  // A struct that is not exported is the file's own (helpers, locals): it stays out of the IDL (see
414
417
  // checkLocalStructs). An account group is part of the instructions' accounts, so it is exported.
415
418
  if (!isExported(stmt) && isAccountGroup(stmt, imports))
416
419
  reporter.fail(stmt, "account groups must be exported: export interface …");
417
420
  declare(stmt.name, file);
418
421
  // An interface of accounts is an account group (Anchor's composite `#[derive(Accounts)]` field), not a struct.
422
+ if (isAccountGroup(stmt, imports) && stmt.heritageClauses?.length)
423
+ reporter.fail(stmt.heritageClauses[0], "an account group cannot extend other types: list its accounts, or hold another group as a field (inner: OtherGroup)");
419
424
  if (isAccountGroup(stmt, imports))
420
425
  groups.set(stmt.name.text, { decl: stmt, imports });
421
426
  else
422
427
  interfaces.push({ decl: stmt, imports });
423
428
  }
424
429
  else if (ts.isTypeAliasDeclaration(stmt)) {
430
+ typeDecls.add(stmt.name.text);
425
431
  declare(stmt.name, file);
426
432
  const shape = aliasShape(stmt.type);
427
433
  if (stmt.typeParameters?.length)
428
- reporter.fail(stmt, shape === "alias" ? "type aliases cannot be generic: name one type, type Price = u64" : "data enums cannot be generic");
434
+ reporter.fail(stmt, shape === "alias"
435
+ ? "type aliases cannot be generic: name one type, type Price = u64"
436
+ : shape === "struct"
437
+ ? "structs cannot be generic: declare one struct per field type (type PairU64 = { a: u64; b: u64 })"
438
+ : "data enums cannot be generic");
439
+ // `type Point = { x: u64; y: u64 }`: a struct, as `interface Point { … }` is.
440
+ if (shape === "struct") {
441
+ if (isAccountGroup(stmt, imports))
442
+ reporter.fail(stmt, `account groups are interfaces: export interface ${stmt.name.text} { … }`);
443
+ interfaces.push({ decl: stmt, imports });
444
+ return;
445
+ }
446
+ if (shape === "literals")
447
+ reporter.fail(stmt.type, `a union of literal types (${stmt.type.getText()}) is not supported: use an enum (export enum ${stmt.name.text} { … }) for named choices, or the integer type itself`);
448
+ if (shape === "intersection")
449
+ reporter.fail(stmt.type, `intersection types (${stmt.type.getText()}) are not supported: declare an interface that extends the named structs and adds the other fields (interface ${stmt.name.text} extends Base { … })`);
429
450
  if (shape === "mixed")
430
451
  reporter.fail(stmt.type, 'a union of named types is not a data enum: list the variants as object types (type Event = { kind: "Fill"; price: u64 } | { kind: "Place"; … }), or alias a single type (type Price = u64, type Maybe = Point | null)');
431
452
  // `type Price = u64`: another name for a type, replaced by that type wherever it is used (substituteAliases).
@@ -538,6 +559,13 @@ export function analyze(entry, files) {
538
559
  functions.push({ node: stmt, imports });
539
560
  }
540
561
  else {
562
+ // A helper without a body: `declare function` (nothing to compile) or an overload signature.
563
+ if (!stmt.body) {
564
+ const declared = (ts.getModifiers(stmt) ?? []).some((m) => m.kind === ts.SyntaxKind.DeclareKeyword);
565
+ reporter.fail(stmt, declared
566
+ ? "declare function has no body to compile: a program calls only the helpers it defines and TypeSOL's built-ins (another program is called with a CPI)"
567
+ : "overload signatures are not supported: write one function, with an Option<T> parameter for an argument that may be left out");
568
+ }
541
569
  if (stmt.name)
542
570
  declare(stmt.name, file);
543
571
  if (stmt.name)
@@ -601,7 +629,7 @@ export function analyze(entry, files) {
601
629
  }
602
630
  }
603
631
  else {
604
- reporter.fail(stmt, unsupportedSyntax(stmt.kind, "top level"));
632
+ reporter.fail(stmt, unsupportedSyntax(stmt.kind, "top level", stmt));
605
633
  }
606
634
  });
607
635
  }
@@ -646,13 +674,35 @@ export function analyze(entry, files) {
646
674
  c.def.type = t;
647
675
  });
648
676
  }
649
- const structs = analyzeStructs(interfaces, aliases, dataEnums, reporter, scopeFor, fstrings, fixedVecs);
677
+ const structs = analyzeStructs(interfaces, aliases, dataEnums, reporter, scopeFor, fstrings, fixedVecs, new Set(groups.keys()));
678
+ brokenTypes = new Set([...typeDecls].filter((n) => !structs.has(n) && !groups.has(n) && !dataEnums.has(n) && ![...simpleAliases.keys()].some((d) => d.name.text === n)));
650
679
  // u256 is a computation type: nothing stores, sends or returns it (the IDL has no 256-bit integer).
651
680
  for (const s of structs.values())
652
681
  for (const f of s.fields)
653
682
  if (hasU256(f.type))
654
683
  reporter.error(s.node ?? interfaces[0].decl, `${s.name}.${f.name}: u256 is for computation; store a u128 (or two u128s)`);
655
684
  const checker = program.getTypeChecker();
685
+ // `{ ...p, x: 1n }` is a struct literal's: one whose type is a struct of the program (a typed local, a field, a helper
686
+ // parameter, a result). Elsewhere (a built-in's object argument) the entries are read by name, which a spread hides.
687
+ for (const file of programFiles(program, entryPath)) {
688
+ const visit = (n) => {
689
+ if (ts.isSpreadAssignment(n)) {
690
+ let t = checker.getContextualType(n.parent);
691
+ // An Option of a struct (`Point | null`): the struct.
692
+ if (t?.isUnion()) {
693
+ const some = t.types.filter((x) => !(x.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)));
694
+ t = some.length === 1 ? some[0] : undefined;
695
+ }
696
+ const sym = t?.aliasSymbol ?? t?.getSymbol();
697
+ const decls = sym?.declarations ?? [];
698
+ const s = sym && structs.get(sym.name);
699
+ if (!s || !decls.includes(s.node))
700
+ reporter.error(n, "spread (...) is supported in struct literals only (const q: Point = { ...p, x: 1n }); write this object's fields one by one");
701
+ }
702
+ ts.forEachChild(n, visit);
703
+ };
704
+ visit(file);
705
+ }
656
706
  // Local `const f = (…) => …` in any function body (and in those local functions): lifted to helpers.
657
707
  const locals = [];
658
708
  const taken = new Set();
@@ -1049,6 +1099,7 @@ export function analyze(entry, files) {
1049
1099
  },
1050
1100
  sourceFile,
1051
1101
  files: programFiles(program, entryPath).map((f) => f.fileName),
1102
+ texts: new Map(programFiles(program, entryPath).map((f) => [f.fileName, f.text])),
1052
1103
  imports: entryImports,
1053
1104
  reporter,
1054
1105
  checker,
@@ -1084,7 +1135,8 @@ const CONST_OPS = new Set([
1084
1135
  * declared before it (in this file or an imported one). JS's bigint results (division truncates, `%` keeps the
1085
1136
  * dividend's sign, `>>` rounds down, as Rust's integers do). With `width` (a typed constant, `const X: u64 = …`), every
1086
1137
  * step must fit in that type, as Rust computes a typed const; without one the result is a literal, checked where it is
1087
- * used. Division by zero, a negative exponent or shift, and a value past 256 bits are compile errors.
1138
+ * used. Division by zero, a typed constant's signed minimum divided by or reduced modulo -1, a negative exponent or
1139
+ * shift, and a value past 256 bits are compile errors.
1088
1140
  */
1089
1141
  function foldConstant(e, constants, reporter, width) {
1090
1142
  const fit = (v, at) => {
@@ -1136,6 +1188,10 @@ function foldConstant(e, constants, reporter, width) {
1136
1188
  case ts.SyntaxKind.PercentToken:
1137
1189
  if (r === 0n)
1138
1190
  reporter.fail(b, `${b.getText()} divides by zero`);
1191
+ // A signed type's minimum by -1: its quotient does not fit, and its remainder fails with it, as at run time
1192
+ // (5100) and in Rust (`i8::MIN % -1` overflows), though JS's bigint gives 0.
1193
+ if (width && INT_INFO[width].signed && l === INT_INFO[width].min && r === -1n)
1194
+ reporter.fail(b, `${b.getText()} overflows ${width}: ${width}'s minimum divided by -1 does not fit, and its remainder fails with it`);
1139
1195
  return fit(b.operatorToken.kind === ts.SyntaxKind.SlashToken ? l / r : l % r, b);
1140
1196
  case ts.SyntaxKind.AsteriskAsteriskToken:
1141
1197
  if (r < 0n)
@@ -1167,7 +1223,7 @@ function foldConstant(e, constants, reporter, width) {
1167
1223
  */
1168
1224
  function checkLocalStructs(structs, dataEnums, accountStructs, argStructs, events, reporter) {
1169
1225
  const local = (n) => structs.get(n)?.local === true;
1170
- const fix = (n, what) => `${n} is not exported, but ${what} uses it, which puts it in the IDL: export interface ${n}`;
1226
+ const fix = (n, what) => `${n} is not exported, but ${what} uses it, which puts it in the IDL: export ${structs.get(n) && ts.isTypeAliasDeclaration(structs.get(n).node) ? "type" : "interface"} ${n}`;
1171
1227
  const named = (t) => t.kind === "struct"
1172
1228
  ? [t.name]
1173
1229
  : t.kind === "array" || t.kind === "vec"
@@ -1382,6 +1438,10 @@ function numericLiteralArg(node) {
1382
1438
  return undefined;
1383
1439
  return Number(node.literal.text);
1384
1440
  }
1441
+ /** `kind: "Name"`: the member naming a data enum's variant. */
1442
+ function isKindTag(m) {
1443
+ return ts.isIdentifier(m.name) && m.name.text === "kind" && !!m.type && ts.isLiteralTypeNode(m.type) && ts.isStringLiteral(m.type.literal);
1444
+ }
1385
1445
  /**
1386
1446
  * What a `type X = …` declares: a data enum (object types, `{ kind: "A"; … } | { kind: "B" }`), an alias of one type
1387
1447
  * (`u64`, `Point`, `FixedVec<u8, 32>`, `Point | null`), or a union mixing named types, which is neither.
@@ -1389,8 +1449,13 @@ function numericLiteralArg(node) {
1389
1449
  function aliasShape(t) {
1390
1450
  while (ts.isParenthesizedTypeNode(t))
1391
1451
  t = t.type;
1452
+ // One object type is a data enum of one variant when it names it (`kind: "Pause"`), a struct otherwise.
1392
1453
  if (ts.isTypeLiteralNode(t))
1393
- return "dataEnum";
1454
+ return t.members.some((m) => ts.isPropertySignature(m) && isKindTag(m)) ? "dataEnum" : "struct";
1455
+ if (ts.isIntersectionTypeNode(t))
1456
+ return "intersection";
1457
+ if (ts.isUnionTypeNode(t) && t.types.every((m) => ts.isLiteralTypeNode(m) && m.literal.kind !== ts.SyntaxKind.NullKeyword))
1458
+ return "literals";
1394
1459
  if (!ts.isUnionTypeNode(t))
1395
1460
  return "alias";
1396
1461
  const members = t.types.filter((m) => !(ts.isLiteralTypeNode(m) && m.literal.kind === ts.SyntaxKind.NullKeyword));
@@ -1534,7 +1599,7 @@ function replaceChild(parent, from, to) {
1534
1599
  * Resolve every exported interface. Field types may name other interfaces, so names are
1535
1600
  * collected first; sizes are computed after, rejecting cycles.
1536
1601
  */
1537
- function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings, fixedVecs) {
1602
+ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings, fixedVecs, groupNames) {
1538
1603
  const names = new Set(items.map((d) => d.decl.name.text));
1539
1604
  const enumNames = new Set(aliases.map((a) => a.decl.name.text));
1540
1605
  const structs = new Map();
@@ -1633,6 +1698,11 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1633
1698
  }
1634
1699
  if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && names.has(node.typeName.text) && !targs.length)
1635
1700
  return { kind: "struct", name: node.typeName.text };
1701
+ if (mentionsBroken(node))
1702
+ reporter.bail();
1703
+ const form = unsupportedTypeForm(node, imports);
1704
+ if (form)
1705
+ reporter.fail(node, form);
1636
1706
  reporter.fail(node, "field type must be an integer, boolean, Pubkey, FixedArray<T, N>, FixedString<N>, FixedVec<T, N>, Vec<T>, string (events only) or another struct", fieldTypeHint(node));
1637
1707
  };
1638
1708
  // `BigVec<T>`: a u32 length, then elements to the end of the account (SPL's big_vec). Only the last field, so its
@@ -1642,21 +1712,75 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1642
1712
  const elemNode = node.typeArguments?.[0];
1643
1713
  if (!elemNode || node.typeArguments.length !== 1)
1644
1714
  reporter.fail(node, "BigVec<T> takes one element type: BigVec<ValidatorStakeInfo>");
1645
- if (decl.members.at(-1) !== m)
1715
+ if (structMembers(decl).at(-1) !== m)
1646
1716
  reporter.fail(m, `BigVec<T> must be the last field of ${decl.name.text}: its elements run to the end of the account (move it after the others)`);
1647
1717
  const elem = fieldType(elemNode);
1648
1718
  if (!isScalarField(elem) && elem.kind !== "struct")
1649
1719
  reporter.fail(elemNode, "BigVec elements are integers, booleans, Pubkeys, unit enums or fixed-size structs");
1650
1720
  return { kind: "vec", elem, big: true };
1651
1721
  };
1652
- for (const { decl, imports: fileImports } of items) {
1722
+ // `interface B extends A, C`: B's fields are A's, then C's, then its own, so a parent is defined before its children.
1723
+ const byName = new Map(items.map((it) => [it.decl.name.text, it]));
1724
+ const defining = new Set();
1725
+ const failed = new Set();
1726
+ const define = (item) => {
1727
+ const { decl, imports: fileImports } = item;
1728
+ if (structs.has(decl.name.text) || failed.has(decl.name.text))
1729
+ return;
1730
+ if (defining.has(decl.name.text))
1731
+ reporter.fail(decl.name, `struct ${decl.name.text} extends itself`);
1732
+ defining.add(decl.name.text);
1733
+ const saved = { scope, imports };
1653
1734
  scope = scopeFor(fileImports);
1654
1735
  imports = fileImports;
1655
1736
  reporter.guard(() => {
1656
- if (decl.typeParameters?.length || decl.heritageClauses?.length)
1657
- reporter.fail(decl, "structs cannot be generic or extend other types");
1737
+ if (decl.typeParameters?.length)
1738
+ reporter.fail(decl, "structs cannot be generic: declare one struct per field type");
1739
+ // The parents' fields, in the order the extends clause names them; each parent once.
1658
1740
  const fields = [];
1659
- for (const m of decl.members) {
1741
+ const members = new Map();
1742
+ const ancestors = [];
1743
+ const inherited = new Map();
1744
+ for (const clause of (ts.isInterfaceDeclaration(decl) ? decl.heritageClauses : undefined) ?? []) {
1745
+ for (const h of clause.types) {
1746
+ if (!ts.isIdentifier(h.expression))
1747
+ reporter.fail(h, "a struct extends structs of this program by name: interface B extends A { … }");
1748
+ const pname = h.expression.text;
1749
+ if (h.typeArguments?.length)
1750
+ reporter.fail(h, `a struct cannot extend a generic type (${h.getText()}): extend structs of this program`);
1751
+ const parent = byName.get(pname);
1752
+ if (!parent)
1753
+ reporter.fail(h, enumNames.has(pname)
1754
+ ? `${decl.name.text} cannot extend the data enum ${pname}: a struct extends structs`
1755
+ : groupNames.has(pname)
1756
+ ? `${decl.name.text} cannot extend ${pname}, an account group: a struct extends structs; hold the group as a field of an account group instead`
1757
+ : `${decl.name.text} extends ${pname}, which is not a struct of this program: a struct extends interfaces or object types (type ${pname} = { … }) declared in it`);
1758
+ define(parent);
1759
+ const p = structs.get(pname);
1760
+ if (!p)
1761
+ reporter.bail(); // its own error says why
1762
+ if (ancestors.includes(pname))
1763
+ reporter.fail(h, `${decl.name.text} extends ${pname} twice`);
1764
+ ancestors.push(pname, ...(p.ancestors ?? []).filter((a) => !ancestors.includes(a)));
1765
+ for (const f of p.declared ? p.declared.map((n) => p.fields.find((x) => x.name === n)) : p.fields) {
1766
+ const prev = fields.find((x) => x.name === f.name);
1767
+ if (prev) {
1768
+ // `interface C extends A, B` with the same field in both: one field, if it has one type.
1769
+ if (JSON.stringify(prev.type) !== JSON.stringify(f.type) || prev.idlBytes !== f.idlBytes || prev.idlName !== f.idlName)
1770
+ reporter.fail(h, `${pname}.${f.name} and ${inherited.get(f.name)}.${f.name} have different types; ${decl.name.text} cannot extend both`);
1771
+ continue;
1772
+ }
1773
+ // A Vec is held on the heap by a @layout borsh struct only: the child's own layout decides (below).
1774
+ const type = f.type.kind === "vec" && f.type.heap ? (({ heap: _, ...rest }) => rest)(f.type) : f.type;
1775
+ fields.push({ ...f, type, node: h });
1776
+ inherited.set(f.name, pname);
1777
+ const m = p.members.get(f.name);
1778
+ if (m)
1779
+ members.set(f.name, m);
1780
+ }
1781
+ }
1782
+ }
1783
+ for (const m of structMembers(decl)) {
1660
1784
  if (!ts.isPropertySignature(m) || !m.type || !ts.isIdentifier(m.name))
1661
1785
  reporter.fail(m, "structs may only contain plain fields");
1662
1786
  if (m.questionToken)
@@ -1664,6 +1788,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1664
1788
  const name = m.name.text;
1665
1789
  if (RESERVED_FIELDS.has(name))
1666
1790
  reporter.fail(m.name, `"${name}" is reserved; pick another field name`);
1791
+ if (inherited.has(name))
1792
+ reporter.fail(m.name, `${decl.name.text} inherits "${name}" from ${inherited.get(name)}: a struct cannot declare an inherited field again; leave it out`);
1667
1793
  const problem = cNameProblem(name);
1668
1794
  if (problem)
1669
1795
  reporter.fail(m.name, problem);
@@ -1681,7 +1807,10 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1681
1807
  reporter.fail(nameTag, "@idlName takes the field's name in the IDL: @idlName _pad0");
1682
1808
  fields.push({ name, type, node: m, ...(idlBytes ? { idlBytes } : {}), ...(idlName ? { idlName } : {}) });
1683
1809
  }
1684
- checkSnakeDuplicates(decl.members.map((m) => ({ name: m.name.text, node: m })), "fields", reporter);
1810
+ checkSnakeDuplicates(fields.map((f) => ({ name: f.name, node: f.node ?? decl })), "fields", reporter);
1811
+ for (const f of fields)
1812
+ if (f.node && ts.isTypeElement(f.node))
1813
+ members.set(f.name, f.node);
1685
1814
  const name = decl.name.text;
1686
1815
  // `/** @layout borsh */`: stored as Anchor stores it.
1687
1816
  const layoutTag = ts.getJSDocTags(decl).find((t) => t.tagName.text === "layout");
@@ -1694,6 +1823,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1694
1823
  reporter.fail(big.node, "a @layout borsh struct cannot hold a BigVec: BigVec is read in place (loadRaw / loadRawMut) from a fixed layout");
1695
1824
  if (big && fields.some((f) => f !== big && growable(f)))
1696
1825
  reporter.fail(big.node, `${decl.name.text} has a Vec and a BigVec: only one list may run to the end of the account`);
1826
+ if (big && fields.at(-1) !== big)
1827
+ reporter.fail(decl.name, `${decl.name.text} adds fields after the BigVec it inherits; a BigVec is the last field (its elements run to the end of the account)`);
1697
1828
  // In a @layout borsh struct a Vec<T> is Anchor's: held on the heap while an instruction runs, any field, bounded
1698
1829
  // only by the account when it is written back.
1699
1830
  if (layoutText === "borsh")
@@ -1719,10 +1850,18 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1719
1850
  accountDiscriminator: accountDiscriminator(decl, name, reporter),
1720
1851
  eventDiscriminator: discriminator(`event:${name}`),
1721
1852
  node: decl,
1853
+ members,
1854
+ ...(ancestors.length ? { ancestors } : {}),
1722
1855
  layout: layoutText === "borsh" ? "borsh" : "fixed",
1723
1856
  });
1724
1857
  });
1725
- }
1858
+ if (!structs.has(decl.name.text))
1859
+ failed.add(decl.name.text);
1860
+ defining.delete(decl.name.text);
1861
+ ({ scope, imports } = saved);
1862
+ };
1863
+ for (const item of items)
1864
+ define(item);
1726
1865
  // Data enums: a union of object types, each with a string-literal `kind` naming the variant.
1727
1866
  for (const { decl, imports: fileImports } of aliases) {
1728
1867
  scope = scopeFor(fileImports);
@@ -2079,7 +2218,7 @@ function checkBorshLayout(s, structs, dataEnums, reporter) {
2079
2218
  };
2080
2219
  for (const f of s.fields) {
2081
2220
  const t = f.type;
2082
- const at = s.node.members.find((m) => m.name && ts.isIdentifier(m.name) && m.name.text === f.name) ?? s.node;
2221
+ const at = s.members.get(f.name) ?? s.node;
2083
2222
  if (fixed(t) || t.kind === "fstring" || t.kind === "string")
2084
2223
  continue;
2085
2224
  if (t.kind === "dataEnum") {
@@ -2132,8 +2271,10 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
2132
2271
  const s = sn ? structs.get(sn) : undefined;
2133
2272
  if (s && (s.size === undefined || s.vec))
2134
2273
  reporter.fail(fn.type, `${s.name} has variable-size fields and cannot be returned; return a struct of fixed size`);
2274
+ if (!s && mentionsBroken(fn.type))
2275
+ reporter.bail();
2135
2276
  if (!s)
2136
- reporter.fail(fn.type, "helpers return void, an integer, boolean, Pubkey, string, a struct or a type parameter");
2277
+ reporter.fail(fn.type, unsupportedTypeForm(fn.type, scope.imports) ?? "helpers return void, an integer, boolean, Pubkey, string, a struct or a type parameter");
2137
2278
  returns = { kind: "struct", name: s.name };
2138
2279
  }
2139
2280
  const params = fn.parameters
@@ -2183,7 +2324,12 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
2183
2324
  return { name: p.name.text, type: { kind: "account" }, account, node: p };
2184
2325
  });
2185
2326
  // `/** @noinline */` on the function (or on the `const f = …` declaring an arrow).
2186
- const noinline = [fn, ...(ts.isVariableDeclaration(fn.parent) ? [fn.parent] : [])].some((n) => ts.getJSDocTags(n).some((t) => t.tagName.text === "noinline"));
2327
+ const tagged = (tag) => [fn, ...(ts.isVariableDeclaration(fn.parent) ? [fn.parent] : [])].some((n) => ts.getJSDocTags(n).some((t) => t.tagName.text === tag));
2328
+ const noinline = tagged("noinline");
2329
+ // `/** @inline */`: the build never keeps it out of line on its own to fit the stack (clang may still).
2330
+ const inline = tagged("inline");
2331
+ if (noinline && inline)
2332
+ reporter.fail(fn, "a helper is either @noinline or @inline, not both");
2187
2333
  return {
2188
2334
  name,
2189
2335
  display,
@@ -2193,6 +2339,7 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
2193
2339
  statements: bodyStatements(fn, !returns),
2194
2340
  imports: scope.imports,
2195
2341
  ...(noinline ? { noinline } : {}),
2342
+ ...(inline ? { inline } : {}),
2196
2343
  };
2197
2344
  }
2198
2345
  /**
@@ -2284,7 +2431,8 @@ function checkRecursion(sources, decls, checker, reporter) {
2284
2431
  }
2285
2432
  ts.forEachChild(n, visit);
2286
2433
  };
2287
- visit(h.node.body);
2434
+ if (h.node.body)
2435
+ visit(h.node.body);
2288
2436
  calls.set(h.name, out);
2289
2437
  }
2290
2438
  const state = new Map();
@@ -2360,9 +2508,72 @@ const ACCOUNT_TYPES = new Set([
2360
2508
  "SystemAccount",
2361
2509
  ]);
2362
2510
  const withoutNull = (t) => ts.isUnionTypeNode(t) && t.types.length === 2 ? (t.types.find((x) => !(ts.isLiteralTypeNode(x) && x.literal.kind === ts.SyntaxKind.NullKeyword)) ?? t) : t;
2511
+ /**
2512
+ * Struct, account group and data enum declarations of the program being analyzed that failed, with an error saying why:
2513
+ * a type naming one of them is not reported again (its error would only repeat that one).
2514
+ */
2515
+ let brokenTypes = new Set();
2516
+ /** Whether a type names a declaration that failed (brokenTypes). */
2517
+ function mentionsBroken(node) {
2518
+ if (!brokenTypes.size)
2519
+ return false;
2520
+ const visit = (n) => (ts.isTypeReferenceNode(n) && ts.isIdentifier(n.typeName) && brokenTypes.has(n.typeName.text)) || !!ts.forEachChild(n, visit);
2521
+ return visit(node);
2522
+ }
2523
+ /**
2524
+ * What to write instead of a TypeScript type form TypeSOL does not have (a parameter's, a field's, a result's or a
2525
+ * local's type), or undefined when the type is not one of those forms.
2526
+ */
2527
+ export function unsupportedTypeForm(node, imports) {
2528
+ while (ts.isParenthesizedTypeNode(node))
2529
+ node = node.type;
2530
+ if (ts.isTypeOperatorNode(node)) {
2531
+ if (node.operator === ts.SyntaxKind.KeyOfKeyword)
2532
+ return "keyof types are not supported: a program picks a field in code; use an enum for the choice (switch on it to read the field)";
2533
+ if (node.operator === ts.SyntaxKind.ReadonlyKeyword)
2534
+ return "readonly types are not supported: write the type itself (helper parameters are read-only already)";
2535
+ return "unique symbol types are not supported";
2536
+ }
2537
+ if (ts.isIndexedAccessTypeNode(node))
2538
+ return `indexed access types (${node.getText()}) are not supported: write the field's type itself`;
2539
+ if (ts.isTypeQueryNode(node))
2540
+ return `typeof in a type (${node.getText()}) is not supported: write the type itself`;
2541
+ if (ts.isTypePredicateNode(node))
2542
+ return "type predicates (x is T) are not supported: return a boolean, and test the data enum's kind where you use it";
2543
+ if (ts.isFunctionTypeNode(node))
2544
+ return "a function type is only a helper parameter's type (f: (x: u64) => u64): structs, results and arguments hold data";
2545
+ if (ts.isLiteralTypeNode(node) && node.literal.kind !== ts.SyntaxKind.NullKeyword)
2546
+ return `literal types (${node.getText()}) are not supported: take the integer, boolean or string type itself, or an enum for named choices`;
2547
+ if (ts.isUnionTypeNode(node)) {
2548
+ const rest = node.types.filter((t) => !(ts.isLiteralTypeNode(t) && t.literal.kind === ts.SyntaxKind.NullKeyword));
2549
+ if (rest.every((t) => ts.isLiteralTypeNode(t)))
2550
+ return `a union of literal types (${node.getText()}) is not supported: use an enum for named choices, or the integer type itself`;
2551
+ if (rest.length > 1)
2552
+ return `union types (${node.getText()}) are not supported: a value has one type; use a data enum (type V = { kind: "A"; … } | { kind: "B"; … }) for a value of several shapes`;
2553
+ }
2554
+ if (ts.isIntersectionTypeNode(node))
2555
+ return "intersection types (A & B) are not supported: declare an interface that extends the structs and adds the other fields";
2556
+ if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !imports.has(node.typeName.text)) {
2557
+ const name = node.typeName.text;
2558
+ if (name === "Readonly" || name === "ReadonlyArray")
2559
+ return `${name}<T> is not supported: write T itself (helper parameters are read-only already)`;
2560
+ if (["Pick", "Omit", "Partial", "Required", "Record", "Exclude", "Extract", "NonNullable", "ReturnType", "Parameters"].includes(name))
2561
+ return `${name}<…> is not supported: declare the struct it describes with its fields (interface Name { … })`;
2562
+ }
2563
+ return undefined;
2564
+ }
2565
+ /** The members of a struct's declaration: the interface's, or the object type's (`type P = { … }`). */
2566
+ export function structMembers(decl) {
2567
+ if (ts.isInterfaceDeclaration(decl))
2568
+ return decl.members;
2569
+ let t = decl.type;
2570
+ while (ts.isParenthesizedTypeNode(t))
2571
+ t = t.type;
2572
+ return t.members;
2573
+ }
2363
2574
  /** An interface with an account-typed field: an account group. */
2364
2575
  function isAccountGroup(decl, imports) {
2365
- return decl.members.some((m) => ts.isPropertySignature(m) && m.type && ACCOUNT_TYPES.has(typesolName(withoutNull(m.type), imports) ?? ""));
2576
+ return structMembers(decl).some((m) => ts.isPropertySignature(m) && m.type && ACCOUNT_TYPES.has(typesolName(withoutNull(m.type), imports) ?? ""));
2366
2577
  }
2367
2578
  function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
2368
2579
  const imports = scope.imports;
@@ -2811,6 +3022,8 @@ function unwrapConstraints(node, reporter, imports, out) {
2811
3022
  /** Solana: an account grows at most this many bytes per instruction. */
2812
3023
  const MAX_PERMITTED_DATA_INCREASE = 10_240;
2813
3024
  function resolveAccountKind(node, reporter, imports, structs) {
3025
+ if (mentionsBroken(node))
3026
+ reporter.bail();
2814
3027
  const outer = typesolName(node, imports);
2815
3028
  const ref = node;
2816
3029
  const inner = () => {
@@ -2983,6 +3196,7 @@ function resolveAccountKind(node, reporter, imports, structs) {
2983
3196
  reporter.fail(node, "BigVec<T> is the last field of a native account's struct (read with loadRaw), not an argument; a list argument is a Vec<T>");
2984
3197
  if (typesolName(node, imports) === "Inout")
2985
3198
  reporter.fail(node, "Inout<T> is for helper parameters (a place of the caller's the helper may change); an instruction takes struct arguments by value and accounts as Mut<T>");
2986
- reporter.fail(node, "parameter type must be an integer, boolean, Pubkey, string, or an account type (Signer, Account<T>, Mut<T>, Init<T>, AccountInfo, TokenAccount, Mint, SystemProgram, TokenProgram, Token2022Program, TokenInterface, Program<...>)");
3199
+ reporter.fail(node, unsupportedTypeForm(node, imports) ??
3200
+ "parameter type must be an integer, boolean, Pubkey, string, or an account type (Signer, Account<T>, Mut<T>, Init<T>, AccountInfo, TokenAccount, Mint, SystemProgram, TokenProgram, Token2022Program, TokenInterface, Program<...>)");
2987
3201
  }
2988
3202
  export { isScalar };
@@ -22,7 +22,11 @@ export declare class Reporter {
22
22
  /** `hint`: what to write instead, shown as the message's last line ("hint: …") and given to tools as `hint`. */
23
23
  error(node: ts.Node, message: string, hint?: string): void;
24
24
  fail(node: ts.Node, message: string, hint?: string): never;
25
+ /** Unwind the current construct without a message: one already reported explains it. */
26
+ bail(): never;
25
27
  /** Run `fn`, swallowing a `fail` so analysis can continue with the next construct. */
26
28
  guard<T>(fn: () => T): T | undefined;
27
29
  throwIfAny(): void;
28
30
  }
31
+ export declare class Bail extends Error {
32
+ }
@@ -42,6 +42,10 @@ export class Reporter {
42
42
  this.error(node, message, hint);
43
43
  throw new Bail();
44
44
  }
45
+ /** Unwind the current construct without a message: one already reported explains it. */
46
+ bail() {
47
+ throw new Bail();
48
+ }
45
49
  /** Run `fn`, swallowing a `fail` so analysis can continue with the next construct. */
46
50
  guard(fn) {
47
51
  try {
@@ -58,5 +62,5 @@ export class Reporter {
58
62
  throw new CompileError(this.diagnostics);
59
63
  }
60
64
  }
61
- class Bail extends Error {
65
+ export class Bail extends Error {
62
66
  }
@@ -2,7 +2,7 @@ import ts from "typescript";
2
2
  import { type Analysis, type TypeArg, type TypeScope } from "../analyze.js";
3
3
  import type { Reporter } from "../diagnostics.js";
4
4
  import { type AccountParam, type GenericHelper, type Helper, type IdlSeed, type Instruction, type ProgramModel, type ValueType } from "../model.js";
5
- import { type Value, type Ref, type Local, type Closure, type FunctionChoice, type EmitOptions, type CpiProgram } from "./shared.js";
5
+ import { type Value, type Ref, type Local, type Closure, type FunctionChoice, type EmitOptions, type CpiProgram, type HeapCandidate, type StackPlan } from "./shared.js";
6
6
  /**
7
7
  * State of one function being lowered, and the primitives every layer uses: emitting lines, temporaries,
8
8
  * scopes, evaluation-order snapshots and account lookups.
@@ -66,6 +66,21 @@ export declare abstract class EmitterBase {
66
66
  protected readonly inlining: Set<ts.Node>;
67
67
  /** Enclosing loops, innermost last; each has a `continue` label. */
68
68
  protected readonly loops: string[];
69
+ /**
70
+ * Enclosing labeled statements (`outer: for …`, `done: { … }`), innermost last: the name, the `loops` depth its loop
71
+ * has (its `continue` label is `loops[depth]` while its body is emitted), the C label after it that `break name`
72
+ * jumps to, and whether a jump used that label.
73
+ */
74
+ protected readonly labels: {
75
+ name: string;
76
+ node: ts.LabeledStatement;
77
+ depth: number;
78
+ brk: string;
79
+ loop: ts.IterationStatement | undefined;
80
+ used: boolean;
81
+ }[];
82
+ /** The claim slots each loop body drops at its iteration's end (see iterationClaims), for a labeled jump out of it. */
83
+ protected readonly loopClaims: Map<ts.Node, string[]>;
69
84
  /** loadAccountMut calls whose claim a loop drops at each iteration's end: the C variable that records it. */
70
85
  protected readonly claimSlots: Map<ts.Node, string>;
71
86
  protected readonly ix: Instruction | undefined;
@@ -84,6 +99,12 @@ export declare abstract class EmitterBase {
84
99
  */
85
100
  protected panicAt: string | undefined;
86
101
  protected readonly profile: boolean;
102
+ /** The layout chosen for a program that does not fit the stack otherwise (empty: none). */
103
+ protected readonly stack: StackPlan;
104
+ /** This function's statements each get a C block of their own (StackPlan.scope; see statement()). */
105
+ protected readonly scopeTemps: boolean;
106
+ /** The blocks opened for scopeTemps, numbered within the function. */
107
+ protected scopeBlocks: number;
87
108
  constructor(analysis: Analysis, target: Instruction | Helper, opts?: EmitOptions);
88
109
  /** The helper a call runs: a function, a const arrow function (top-level or local), or a generic one's instance. */
89
110
  protected helperOf(node: ts.CallExpression): Helper | undefined;
@@ -100,6 +121,14 @@ export declare abstract class EmitterBase {
100
121
  /** A generic call's type arguments: written out (`max<u64>(a, b)`), or the types of the arguments in `T` positions. */
101
122
  protected typeArgsOf(node: ts.CallExpression, g: GenericHelper): TypeArg[];
102
123
  protected line(s: string): void;
124
+ /**
125
+ * A list or struct this instruction holds itself, which the build may keep on the heap to fit the stack: the key of
126
+ * `node` (a declaration or a helper call) and whether StackPlan.heap names it. Only in an instruction's own body (not
127
+ * in a closure or a helper expanded into it), and recorded among StackPlan.candidates when the build asks for them.
128
+ */
129
+ protected autoHeap(node: ts.Node, what: Omit<HeapCandidate, "key" | "fn" | "at">): boolean;
130
+ /** `/** @stack *\/` on a declaration (or its statement): never kept on the heap by the build. */
131
+ protected stackTagged(d: ts.VariableDeclaration): boolean;
103
132
  /** `file.ts:line` of a node, for messages. */
104
133
  protected location(node: ts.Node): string;
105
134
  protected tmp(prefix?: string): string;
@@ -137,10 +166,11 @@ export declare abstract class EmitterBase {
137
166
  * `const PANIC_STYLE = "solana-1.14"` / `"solana-1.18"`: a Rust panic logs what that solana-program's panic handler
138
167
  * logs and then aborts, so the runtime reports "SBF program panicked". rustc before 1.73 (solana-program 1.14 to
139
168
  * 1.17) formats a panic as `panicked at '<message>', <file>:<line>:<col>`; from 1.73 (solana-program 1.18's toolchain)
140
- * as `panicked at <file>:<line>:<col>:\n<message>`, one log line holding the newline. By default it logs the message
141
- * and calls sol_panic_ with the location.
169
+ * as `panicked at <file>:<line>:<col>:\n<message>`, one log line holding the newline. `"pinocchio"`: pinocchio's
170
+ * `default_panic_handler!` hook logs the location's file alone, then "** PANICKED **", and std aborts. By default it
171
+ * logs the message and calls sol_panic_ with the location.
142
172
  */
143
- protected panicStyle(): "solana-1.14" | "solana-1.18" | undefined;
173
+ protected panicStyle(): "solana-1.14" | "solana-1.18" | "pinocchio" | undefined;
144
174
  /** The C statements of a Rust panic with `message` (undefined: nothing logged) at `location` ("file:line:col"). */
145
175
  protected panicC(message: string | undefined, location: string): string[];
146
176
  /** `file.ts:line:column` of a node (1-based, as Rust reports a location). */
@@ -185,6 +215,7 @@ export declare abstract class EmitterBase {
185
215
  name: string;
186
216
  count: number;
187
217
  idl: IdlSeed[] | undefined;
218
+ fit: boolean;
188
219
  };
189
220
  protected abstract recordPda(account: AccountParam, idl: IdlSeed[] | undefined): void;
190
221
  protected abstract create(node: ts.CallExpression, target: AccountParam, topLevel: boolean, ifNeeded?: boolean): Value;