@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
@@ -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();
@@ -1173,7 +1223,7 @@ function foldConstant(e, constants, reporter, width) {
1173
1223
  */
1174
1224
  function checkLocalStructs(structs, dataEnums, accountStructs, argStructs, events, reporter) {
1175
1225
  const local = (n) => structs.get(n)?.local === true;
1176
- 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}`;
1177
1227
  const named = (t) => t.kind === "struct"
1178
1228
  ? [t.name]
1179
1229
  : t.kind === "array" || t.kind === "vec"
@@ -1388,6 +1438,10 @@ function numericLiteralArg(node) {
1388
1438
  return undefined;
1389
1439
  return Number(node.literal.text);
1390
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
+ }
1391
1445
  /**
1392
1446
  * What a `type X = …` declares: a data enum (object types, `{ kind: "A"; … } | { kind: "B" }`), an alias of one type
1393
1447
  * (`u64`, `Point`, `FixedVec<u8, 32>`, `Point | null`), or a union mixing named types, which is neither.
@@ -1395,8 +1449,13 @@ function numericLiteralArg(node) {
1395
1449
  function aliasShape(t) {
1396
1450
  while (ts.isParenthesizedTypeNode(t))
1397
1451
  t = t.type;
1452
+ // One object type is a data enum of one variant when it names it (`kind: "Pause"`), a struct otherwise.
1398
1453
  if (ts.isTypeLiteralNode(t))
1399
- 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";
1400
1459
  if (!ts.isUnionTypeNode(t))
1401
1460
  return "alias";
1402
1461
  const members = t.types.filter((m) => !(ts.isLiteralTypeNode(m) && m.literal.kind === ts.SyntaxKind.NullKeyword));
@@ -1540,7 +1599,7 @@ function replaceChild(parent, from, to) {
1540
1599
  * Resolve every exported interface. Field types may name other interfaces, so names are
1541
1600
  * collected first; sizes are computed after, rejecting cycles.
1542
1601
  */
1543
- function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings, fixedVecs) {
1602
+ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings, fixedVecs, groupNames) {
1544
1603
  const names = new Set(items.map((d) => d.decl.name.text));
1545
1604
  const enumNames = new Set(aliases.map((a) => a.decl.name.text));
1546
1605
  const structs = new Map();
@@ -1639,6 +1698,11 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1639
1698
  }
1640
1699
  if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && names.has(node.typeName.text) && !targs.length)
1641
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);
1642
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));
1643
1707
  };
1644
1708
  // `BigVec<T>`: a u32 length, then elements to the end of the account (SPL's big_vec). Only the last field, so its
@@ -1648,21 +1712,75 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1648
1712
  const elemNode = node.typeArguments?.[0];
1649
1713
  if (!elemNode || node.typeArguments.length !== 1)
1650
1714
  reporter.fail(node, "BigVec<T> takes one element type: BigVec<ValidatorStakeInfo>");
1651
- if (decl.members.at(-1) !== m)
1715
+ if (structMembers(decl).at(-1) !== m)
1652
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)`);
1653
1717
  const elem = fieldType(elemNode);
1654
1718
  if (!isScalarField(elem) && elem.kind !== "struct")
1655
1719
  reporter.fail(elemNode, "BigVec elements are integers, booleans, Pubkeys, unit enums or fixed-size structs");
1656
1720
  return { kind: "vec", elem, big: true };
1657
1721
  };
1658
- 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 };
1659
1734
  scope = scopeFor(fileImports);
1660
1735
  imports = fileImports;
1661
1736
  reporter.guard(() => {
1662
- if (decl.typeParameters?.length || decl.heritageClauses?.length)
1663
- 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.
1664
1740
  const fields = [];
1665
- 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)) {
1666
1784
  if (!ts.isPropertySignature(m) || !m.type || !ts.isIdentifier(m.name))
1667
1785
  reporter.fail(m, "structs may only contain plain fields");
1668
1786
  if (m.questionToken)
@@ -1670,6 +1788,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1670
1788
  const name = m.name.text;
1671
1789
  if (RESERVED_FIELDS.has(name))
1672
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`);
1673
1793
  const problem = cNameProblem(name);
1674
1794
  if (problem)
1675
1795
  reporter.fail(m.name, problem);
@@ -1687,7 +1807,10 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1687
1807
  reporter.fail(nameTag, "@idlName takes the field's name in the IDL: @idlName _pad0");
1688
1808
  fields.push({ name, type, node: m, ...(idlBytes ? { idlBytes } : {}), ...(idlName ? { idlName } : {}) });
1689
1809
  }
1690
- 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);
1691
1814
  const name = decl.name.text;
1692
1815
  // `/** @layout borsh */`: stored as Anchor stores it.
1693
1816
  const layoutTag = ts.getJSDocTags(decl).find((t) => t.tagName.text === "layout");
@@ -1700,6 +1823,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1700
1823
  reporter.fail(big.node, "a @layout borsh struct cannot hold a BigVec: BigVec is read in place (loadRaw / loadRawMut) from a fixed layout");
1701
1824
  if (big && fields.some((f) => f !== big && growable(f)))
1702
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)`);
1703
1828
  // In a @layout borsh struct a Vec<T> is Anchor's: held on the heap while an instruction runs, any field, bounded
1704
1829
  // only by the account when it is written back.
1705
1830
  if (layoutText === "borsh")
@@ -1725,10 +1850,18 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1725
1850
  accountDiscriminator: accountDiscriminator(decl, name, reporter),
1726
1851
  eventDiscriminator: discriminator(`event:${name}`),
1727
1852
  node: decl,
1853
+ members,
1854
+ ...(ancestors.length ? { ancestors } : {}),
1728
1855
  layout: layoutText === "borsh" ? "borsh" : "fixed",
1729
1856
  });
1730
1857
  });
1731
- }
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);
1732
1865
  // Data enums: a union of object types, each with a string-literal `kind` naming the variant.
1733
1866
  for (const { decl, imports: fileImports } of aliases) {
1734
1867
  scope = scopeFor(fileImports);
@@ -2085,7 +2218,7 @@ function checkBorshLayout(s, structs, dataEnums, reporter) {
2085
2218
  };
2086
2219
  for (const f of s.fields) {
2087
2220
  const t = f.type;
2088
- 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;
2089
2222
  if (fixed(t) || t.kind === "fstring" || t.kind === "string")
2090
2223
  continue;
2091
2224
  if (t.kind === "dataEnum") {
@@ -2138,8 +2271,10 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
2138
2271
  const s = sn ? structs.get(sn) : undefined;
2139
2272
  if (s && (s.size === undefined || s.vec))
2140
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();
2141
2276
  if (!s)
2142
- 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");
2143
2278
  returns = { kind: "struct", name: s.name };
2144
2279
  }
2145
2280
  const params = fn.parameters
@@ -2189,7 +2324,12 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
2189
2324
  return { name: p.name.text, type: { kind: "account" }, account, node: p };
2190
2325
  });
2191
2326
  // `/** @noinline */` on the function (or on the `const f = …` declaring an arrow).
2192
- 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");
2193
2333
  return {
2194
2334
  name,
2195
2335
  display,
@@ -2199,6 +2339,7 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
2199
2339
  statements: bodyStatements(fn, !returns),
2200
2340
  imports: scope.imports,
2201
2341
  ...(noinline ? { noinline } : {}),
2342
+ ...(inline ? { inline } : {}),
2202
2343
  };
2203
2344
  }
2204
2345
  /**
@@ -2290,7 +2431,8 @@ function checkRecursion(sources, decls, checker, reporter) {
2290
2431
  }
2291
2432
  ts.forEachChild(n, visit);
2292
2433
  };
2293
- visit(h.node.body);
2434
+ if (h.node.body)
2435
+ visit(h.node.body);
2294
2436
  calls.set(h.name, out);
2295
2437
  }
2296
2438
  const state = new Map();
@@ -2366,9 +2508,72 @@ const ACCOUNT_TYPES = new Set([
2366
2508
  "SystemAccount",
2367
2509
  ]);
2368
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
+ }
2369
2574
  /** An interface with an account-typed field: an account group. */
2370
2575
  function isAccountGroup(decl, imports) {
2371
- 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) ?? ""));
2372
2577
  }
2373
2578
  function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
2374
2579
  const imports = scope.imports;
@@ -2817,6 +3022,8 @@ function unwrapConstraints(node, reporter, imports, out) {
2817
3022
  /** Solana: an account grows at most this many bytes per instruction. */
2818
3023
  const MAX_PERMITTED_DATA_INCREASE = 10_240;
2819
3024
  function resolveAccountKind(node, reporter, imports, structs) {
3025
+ if (mentionsBroken(node))
3026
+ reporter.bail();
2820
3027
  const outer = typesolName(node, imports);
2821
3028
  const ref = node;
2822
3029
  const inner = () => {
@@ -2989,6 +3196,7 @@ function resolveAccountKind(node, reporter, imports, structs) {
2989
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>");
2990
3197
  if (typesolName(node, imports) === "Inout")
2991
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>");
2992
- 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<...>)");
2993
3201
  }
2994
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;
@@ -186,6 +215,7 @@ export declare abstract class EmitterBase {
186
215
  name: string;
187
216
  count: number;
188
217
  idl: IdlSeed[] | undefined;
218
+ fit: boolean;
189
219
  };
190
220
  protected abstract recordPda(account: AccountParam, idl: IdlSeed[] | undefined): void;
191
221
  protected abstract create(node: ts.CallExpression, target: AccountParam, topLevel: boolean, ifNeeded?: boolean): Value;
@@ -50,6 +50,14 @@ export class EmitterBase {
50
50
  inlining = new Set();
51
51
  /** Enclosing loops, innermost last; each has a `continue` label. */
52
52
  loops = [];
53
+ /**
54
+ * Enclosing labeled statements (`outer: for …`, `done: { … }`), innermost last: the name, the `loops` depth its loop
55
+ * has (its `continue` label is `loops[depth]` while its body is emitted), the C label after it that `break name`
56
+ * jumps to, and whether a jump used that label.
57
+ */
58
+ labels = [];
59
+ /** The claim slots each loop body drops at its iteration's end (see iterationClaims), for a labeled jump out of it. */
60
+ loopClaims = new Map();
53
61
  /** loadAccountMut calls whose claim a loop drops at each iteration's end: the C variable that records it. */
54
62
  claimSlots = new Map();
55
63
  ix;
@@ -68,8 +76,16 @@ export class EmitterBase {
68
76
  */
69
77
  panicAt;
70
78
  profile;
79
+ /** The layout chosen for a program that does not fit the stack otherwise (empty: none). */
80
+ stack;
81
+ /** This function's statements each get a C block of their own (StackPlan.scope; see statement()). */
82
+ scopeTemps;
83
+ /** The blocks opened for scopeTemps, numbered within the function. */
84
+ scopeBlocks = 0;
71
85
  constructor(analysis, target, opts = {}) {
72
86
  this.profile = !!opts.profile;
87
+ this.stack = opts.stack ?? {};
88
+ this.scopeTemps = !!this.stack.scope?.has("accounts" in target ? `ix_${target.name}` : `fn_${target.name}`);
73
89
  this.reporter = analysis.reporter;
74
90
  this.model = analysis.model;
75
91
  // Each function resolves `typesol` names through its own file's imports.
@@ -243,7 +259,7 @@ export class EmitterBase {
243
259
  const t = probe.type;
244
260
  return t.kind === "pubkey" ? (t.hash ? { kind: "pubkey", hash: true } : { kind: "pubkey" }) : t;
245
261
  }
246
- return this.fail(node, `cannot tell what ${tp} is from literal arguments; ${usage}`);
262
+ return this.fail(node, `cannot tell what ${tp} is from these arguments (literals, lists and functions do not say); ${usage}`);
247
263
  });
248
264
  }
249
265
  line(s) {
@@ -254,6 +270,24 @@ export class EmitterBase {
254
270
  s = s.replace(/\*\(&(\w+->(?:key|owner))\)/g, "$1");
255
271
  this.lines.push(" ".repeat(this.indent) + s);
256
272
  }
273
+ /**
274
+ * A list or struct this instruction holds itself, which the build may keep on the heap to fit the stack: the key of
275
+ * `node` (a declaration or a helper call) and whether StackPlan.heap names it. Only in an instruction's own body (not
276
+ * in a closure or a helper expanded into it), and recorded among StackPlan.candidates when the build asks for them.
277
+ */
278
+ autoHeap(node, what) {
279
+ if (!this.ix || this.helper || node.flags & ts.NodeFlags.Synthesized || node.pos < 0)
280
+ return false;
281
+ if (ts.findAncestor(node.parent, ts.isFunctionLike) !== this.ix.node)
282
+ return false;
283
+ const key = `${node.getSourceFile().fileName}:${node.getStart()}`;
284
+ this.stack.candidates?.push({ key, fn: `ix_${this.ix.name}`, at: this.location(node), ...what });
285
+ return !what.stack && !what.heap && !!this.stack.heap?.has(key);
286
+ }
287
+ /** `/** @stack *\/` on a declaration (or its statement): never kept on the heap by the build. */
288
+ stackTagged(d) {
289
+ return [d, d.parent?.parent].some((n) => n && ts.getJSDocTags(n).some((t) => t.tagName.text === "stack"));
290
+ }
257
291
  /** `file.ts:line` of a node, for messages. */
258
292
  location(node) {
259
293
  const sf = node.getSourceFile();
@@ -371,6 +405,7 @@ export class EmitterBase {
371
405
  scopes: this.scopes.length,
372
406
  indent: this.indent,
373
407
  loops: this.loops.length,
408
+ labels: this.labels.length,
374
409
  frames: this.inlineFrames.length,
375
410
  created: new Set(this.created),
376
411
  pendingInit: new Set(this.pendingInit),
@@ -389,6 +424,7 @@ export class EmitterBase {
389
424
  this.scopes.length = saved.scopes;
390
425
  this.indent = saved.indent;
391
426
  this.loops.length = saved.loops;
427
+ this.labels.length = saved.labels;
392
428
  this.inlineFrames.length = saved.frames;
393
429
  for (const [set, from] of [
394
430
  [this.created, saved.created],