@typesol/cli 0.41.0 → 0.43.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 (62) hide show
  1. package/CHANGELOG.md +319 -0
  2. package/README.md +11 -7
  3. package/dist/compiler/analyze.js +484 -13
  4. package/dist/compiler/diagnostics.d.ts +1 -0
  5. package/dist/compiler/diagnostics.js +13 -0
  6. package/dist/compiler/emit/alias.d.ts +44 -0
  7. package/dist/compiler/emit/alias.js +135 -4
  8. package/dist/compiler/emit/base.d.ts +65 -7
  9. package/dist/compiler/emit/base.js +91 -7
  10. package/dist/compiler/emit/borsh.d.ts +7 -0
  11. package/dist/compiler/emit/borsh.js +86 -1
  12. package/dist/compiler/emit/calls.d.ts +169 -2
  13. package/dist/compiler/emit/calls.js +1170 -81
  14. package/dist/compiler/emit/cpi-core.d.ts +28 -5
  15. package/dist/compiler/emit/cpi-core.js +238 -12
  16. package/dist/compiler/emit/cpi.js +16 -16
  17. package/dist/compiler/emit/create.d.ts +3 -3
  18. package/dist/compiler/emit/create.js +33 -25
  19. package/dist/compiler/emit/expressions.js +89 -9
  20. package/dist/compiler/emit/function.js +2 -2
  21. package/dist/compiler/emit/outline.d.ts +24 -0
  22. package/dist/compiler/emit/outline.js +100 -0
  23. package/dist/compiler/emit/program.js +37 -3
  24. package/dist/compiler/emit/rbtree.d.ts +7 -0
  25. package/dist/compiler/emit/rbtree.js +142 -0
  26. package/dist/compiler/emit/shared.d.ts +43 -1
  27. package/dist/compiler/emit/shared.js +18 -2
  28. package/dist/compiler/emit/statements.d.ts +58 -1
  29. package/dist/compiler/emit/statements.js +549 -22
  30. package/dist/compiler/emit/storage.d.ts +48 -1
  31. package/dist/compiler/emit/storage.js +220 -63
  32. package/dist/compiler/emit/token.d.ts +11 -8
  33. package/dist/compiler/emit/token.js +233 -104
  34. package/dist/compiler/emit/views.d.ts +60 -0
  35. package/dist/compiler/emit/views.js +523 -0
  36. package/dist/compiler/hints.js +6 -0
  37. package/dist/compiler/idl.js +2 -1
  38. package/dist/compiler/model.d.ts +84 -4
  39. package/dist/compiler/model.js +19 -0
  40. package/dist/compiler/toolchain.d.ts +15 -0
  41. package/dist/compiler/toolchain.js +146 -11
  42. package/dist/testing-stake.d.ts +216 -0
  43. package/dist/testing-stake.js +526 -0
  44. package/dist/testing.d.ts +1 -0
  45. package/dist/testing.js +1 -0
  46. package/docs/architecture.md +9 -2
  47. package/docs/case-study-phoenix.md +226 -0
  48. package/docs/case-study-spl-stake-pool.md +122 -0
  49. package/docs/errors.md +1 -1
  50. package/docs/language.md +244 -20
  51. package/docs/migrate-from-anchor.md +1 -0
  52. package/docs/runtime.md +1 -1
  53. package/docs/security-model.md +4 -0
  54. package/docs/stability.md +33 -1
  55. package/docs/test-your-program.md +47 -0
  56. package/docs/testing.md +19 -0
  57. package/docs/troubleshooting.md +5 -2
  58. package/lib/typesol.d.ts +462 -44
  59. package/llms-full.txt +338 -26
  60. package/llms.txt +1 -1
  61. package/package.json +2 -2
  62. package/runtime/typesol_rt.h +476 -0
@@ -2,7 +2,7 @@ import ts from "typescript";
2
2
  import { createHash } from "node:crypto";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
- import { CompileError, Reporter } from "./diagnostics.js";
5
+ import { CompileError, Reporter, markAliasUse } from "./diagnostics.js";
6
6
  import { decodeAddress } from "../keys.js";
7
7
  import { borshIdentical } from "./emit/borsh.js";
8
8
  import { hintForTypeScript, unsupportedSyntax } from "./hints.js";
@@ -69,6 +69,7 @@ const TYPE_EXPORTS = new Set([
69
69
  "AccountInfo",
70
70
  "Account",
71
71
  "Mut",
72
+ "Inout",
72
73
  "Init",
73
74
  "Seed",
74
75
  "TokenAccount",
@@ -80,6 +81,14 @@ const TYPE_EXPORTS = new Set([
80
81
  "FixedArray",
81
82
  "FixedString",
82
83
  "FixedVec",
84
+ "BigVec",
85
+ "BigVecSlice",
86
+ "RawArray",
87
+ "ReadonlyRawArray",
88
+ "RedBlackTree",
89
+ "ReadonlyRedBlackTree",
90
+ "RbEntry",
91
+ "InstructionBytes",
83
92
  "Program",
84
93
  "UncheckedProgram",
85
94
  "CpiAccount",
@@ -122,6 +131,7 @@ const TYPE_EXPORTS = new Set([
122
131
  "ProgramData",
123
132
  "SignerSeeds",
124
133
  "SystemAccount",
134
+ "EpochRewards",
125
135
  ]);
126
136
  /** Largest fixed array a struct may declare, and largest FixedString. */
127
137
  const MAX_ARRAY_LEN = 1_000_000;
@@ -338,6 +348,8 @@ function programFiles(program, entry) {
338
348
  visit(entry);
339
349
  return order;
340
350
  }
351
+ /** The failure-line constants that may be `null`: such failures return their error without logging anything. */
352
+ const SILENCEABLE_PREFIXES = ["ERROR_LOG_PREFIX", "PROGRAM_ERROR_LOG_PREFIX"];
341
353
  export function analyze(entry, files) {
342
354
  const entryPath = path.resolve(entry);
343
355
  checkImports(entryPath, files);
@@ -355,6 +367,9 @@ export function analyze(entry, files) {
355
367
  const interfaces = [];
356
368
  const groups = new Map();
357
369
  const aliases = [];
370
+ /** `type Price = u64`: plain aliases (not data enums) and the imports of the file declaring each. */
371
+ const simpleAliases = new Map();
372
+ const fileImports = new Map();
358
373
  /** Program-wide names (structs, enums, helpers) -> declaring file, for collision errors. */
359
374
  const declared = new Map();
360
375
  let entryImports = new Map();
@@ -371,6 +386,7 @@ export function analyze(entry, files) {
371
386
  for (const file of programFiles(program, entryPath)) {
372
387
  const isEntry = file === sourceFile;
373
388
  const imports = new Map();
389
+ fileImports.set(file, imports);
374
390
  if (isEntry)
375
391
  entryImports = imports;
376
392
  for (const stmt of file.statements) {
@@ -392,8 +408,10 @@ export function analyze(entry, files) {
392
408
  }
393
409
  }
394
410
  else if (ts.isInterfaceDeclaration(stmt)) {
395
- if (!isExported(stmt))
396
- reporter.fail(stmt, "structs must be exported");
411
+ // A struct that is not exported is the file's own (helpers, locals): it stays out of the IDL (see
412
+ // checkLocalStructs). An account group is part of the instructions' accounts, so it is exported.
413
+ if (!isExported(stmt) && isAccountGroup(stmt, imports))
414
+ reporter.fail(stmt, "account groups must be exported: export interface …");
397
415
  declare(stmt.name, file);
398
416
  // An interface of accounts is an account group (Anchor's composite `#[derive(Accounts)]` field), not a struct.
399
417
  if (isAccountGroup(stmt, imports))
@@ -402,10 +420,20 @@ export function analyze(entry, files) {
402
420
  interfaces.push({ decl: stmt, imports });
403
421
  }
404
422
  else if (ts.isTypeAliasDeclaration(stmt)) {
405
- if (!isExported(stmt))
406
- reporter.fail(stmt, "data enums (type X = { kind: ... } | ...) must be exported");
407
423
  declare(stmt.name, file);
408
- aliases.push({ decl: stmt, imports });
424
+ const shape = aliasShape(stmt.type);
425
+ if (stmt.typeParameters?.length)
426
+ reporter.fail(stmt, shape === "alias" ? "type aliases cannot be generic: name one type, type Price = u64" : "data enums cannot be generic");
427
+ if (shape === "mixed")
428
+ 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)');
429
+ // `type Price = u64`: another name for a type, replaced by that type wherever it is used (substituteAliases).
430
+ if (shape === "alias")
431
+ simpleAliases.set(stmt, imports);
432
+ else {
433
+ if (!isExported(stmt))
434
+ reporter.fail(stmt, "data enums (type X = { kind: ... } | ...) must be exported");
435
+ aliases.push({ decl: stmt, imports });
436
+ }
409
437
  }
410
438
  else if (ts.isEnumDeclaration(stmt)) {
411
439
  if (!isExported(stmt))
@@ -504,13 +532,26 @@ export function analyze(entry, files) {
504
532
  value = init.kind === ts.SyntaxKind.TrueKeyword;
505
533
  else if (ts.isStringLiteral(init))
506
534
  value = init.text;
535
+ // `const ERROR_LOG_PREFIX = null`: failures log nothing, as a native program returning an error.
536
+ else if (init.kind === ts.SyntaxKind.NullKeyword && SILENCEABLE_PREFIXES.includes(d.name.text)) {
537
+ if (d.type)
538
+ reporter.fail(d.type, `leave the type out: const ${d.name.text} = null`);
539
+ value = null;
540
+ }
541
+ else if (init.kind === ts.SyntaxKind.NullKeyword)
542
+ reporter.fail(init, `only ${SILENCEABLE_PREFIXES.join(" and ")} can be null (failures that log nothing); other constants are bigint, boolean or string literals, or pubkey("…")`);
543
+ // `const EVENT_ROOM = 1280n - 34n`, `const ASKS_AT = BIDS_AT + 2n * BOOK`: integers folded here.
544
+ else if (isConstantExpression(init))
545
+ value = foldConstant(init, constants, reporter);
507
546
  else
508
- reporter.fail(init, 'top-level constants must be bigint, boolean or string literals, or pubkey("…")');
547
+ reporter.fail(init, 'top-level constants are bigint, boolean or string literals, pubkey("…"), or integer expressions over literals and earlier constants (const ROOM = 1280n - 34n)');
509
548
  declare(d.name, file);
510
549
  const def = { name: d.name.text, value };
511
550
  constants.set(def.name, def);
512
- if (d.type)
513
- pendingConstTypes.push({ def, type: d.type, imports });
551
+ // Typed constants are folded again in their type below; untyped expressions are kept in order with them, as
552
+ // they may use one whose value that changes (`~` within an unsigned width).
553
+ if (d.type || (typeof value === "bigint" && isConstantExpression(init)))
554
+ pendingConstTypes.push({ def, type: d.type, imports, init });
514
555
  }
515
556
  }
516
557
  else {
@@ -522,14 +563,38 @@ export function analyze(entry, files) {
522
563
  const fstrings = new Set();
523
564
  const fixedVecs = new Map();
524
565
  const scopeFor = (imports) => ({ imports, enums, options, dataEnums });
566
+ if (simpleAliases.size)
567
+ substituteAliases(program, entryPath, simpleAliases, fileImports, reporter);
568
+ // Constants whose typed value differs from the first, untyped fold: untyped expressions using them are folded again.
569
+ const refolded = new Set();
570
+ const uses = (e) => (ts.isIdentifier(e) && refolded.has(e.text)) || !!ts.forEachChild(e, (n) => uses(n) || undefined);
525
571
  for (const c of pendingConstTypes) {
526
572
  reporter.guard(() => {
573
+ if (!c.type) {
574
+ if (!uses(c.init))
575
+ return;
576
+ const v = foldConstant(c.init, constants, reporter);
577
+ if (v !== c.def.value)
578
+ refolded.add(c.def.name);
579
+ c.def.value = v;
580
+ return;
581
+ }
527
582
  const t = resolveScalarType(c.type, scopeFor(c.imports));
528
583
  if (!t || t.kind !== "int")
529
584
  reporter.fail(c.type, "annotate constants with an integer type, or leave the type out");
530
585
  if (typeof c.def.value !== "bigint")
531
586
  reporter.fail(c.type, "only integer constants take a type annotation");
532
587
  const info = INT_INFO[t.name];
588
+ // An expression is computed in its type, as Rust's `const X: u64 = …` is: every step must fit, not only the result.
589
+ const literal = ts.isBigIntLiteral(c.init) ||
590
+ (ts.isPrefixUnaryExpression(c.init) && c.init.operator === ts.SyntaxKind.MinusToken && ts.isBigIntLiteral(c.init.operand));
591
+ // The typed fold is the value (`~1n` is 254 in a u8, not -2).
592
+ if (!literal && isConstantExpression(c.init)) {
593
+ const v = foldConstant(c.init, constants, reporter, t.name);
594
+ if (v !== c.def.value)
595
+ refolded.add(c.def.name);
596
+ c.def.value = v;
597
+ }
533
598
  if (c.def.value < info.min || c.def.value > info.max)
534
599
  reporter.fail(c.type, `${c.def.value} does not fit in ${t.name}`);
535
600
  c.def.type = t;
@@ -898,6 +963,18 @@ export function analyze(entry, files) {
898
963
  if (instructions.length === 0 && reporter.diagnostics.length === 0)
899
964
  reporter.error(sourceFile, "a TypeSOL program needs at least one exported function (instruction) in its entry file");
900
965
  const name = path.basename(sourceFile.fileName).replace(/\.ts$/, "");
966
+ const events = collectEvents([...functions, ...helperNodes], structs);
967
+ // What instructions take or return (collectStructs walks a returned struct only when given it as a reference).
968
+ const surface = new Set(argStructs);
969
+ for (const ix of instructions) {
970
+ if (ix.returns?.kind === "struct")
971
+ collectStructs({ kind: "structRef", struct: ix.returns.name, writable: false }, structs, dataEnums, surface);
972
+ // An Option<Struct> argument (`p: Pair | null`): its struct too.
973
+ for (const a of ix.args)
974
+ if (a.type.kind === "optionArg" && a.type.option.inner.kind === "struct")
975
+ collectStructs({ kind: "structRef", struct: a.type.option.inner.name, writable: false }, structs, dataEnums, surface);
976
+ }
977
+ checkLocalStructs(structs, dataEnums, accountStructs, surface, events, reporter);
901
978
  return {
902
979
  model: {
903
980
  name: snakeCase(name).replace(/[^a-z0-9_]/g, "_"),
@@ -914,13 +991,15 @@ export function analyze(entry, files) {
914
991
  dataEnums,
915
992
  options,
916
993
  constants,
917
- events: collectEvents([...functions, ...helperNodes], structs),
994
+ events,
918
995
  accountStructs,
919
996
  foreignAccounts: new Set([...foreignStructs].filter((n) => !ownStructs.has(n))),
920
997
  argStructs,
921
998
  fstrings,
922
999
  fixedVecs,
923
1000
  localVecs: new Map(),
1001
+ borshNative: new Set(),
1002
+ rbTrees: new Map(),
924
1003
  },
925
1004
  sourceFile,
926
1005
  files: programFiles(program, entryPath).map((f) => f.fileName),
@@ -931,6 +1010,147 @@ export function analyze(entry, files) {
931
1010
  };
932
1011
  }
933
1012
  /** Every struct an argument type contains (transitively), for IDL layout decisions. */
1013
+ /** An integer expression a top-level constant may be: operators, parentheses, bigint literals and names. */
1014
+ function isConstantExpression(e) {
1015
+ if (ts.isParenthesizedExpression(e))
1016
+ return isConstantExpression(e.expression);
1017
+ if (ts.isBigIntLiteral(e) || ts.isIdentifier(e))
1018
+ return true;
1019
+ if (ts.isPrefixUnaryExpression(e))
1020
+ return (e.operator === ts.SyntaxKind.MinusToken || e.operator === ts.SyntaxKind.TildeToken) && isConstantExpression(e.operand);
1021
+ return ts.isBinaryExpression(e) && CONST_OPS.has(e.operatorToken.kind) && isConstantExpression(e.left) && isConstantExpression(e.right);
1022
+ }
1023
+ const CONST_OPS = new Set([
1024
+ ts.SyntaxKind.PlusToken,
1025
+ ts.SyntaxKind.MinusToken,
1026
+ ts.SyntaxKind.AsteriskToken,
1027
+ ts.SyntaxKind.SlashToken,
1028
+ ts.SyntaxKind.PercentToken,
1029
+ ts.SyntaxKind.AsteriskAsteriskToken,
1030
+ ts.SyntaxKind.AmpersandToken,
1031
+ ts.SyntaxKind.BarToken,
1032
+ ts.SyntaxKind.CaretToken,
1033
+ ts.SyntaxKind.LessThanLessThanToken,
1034
+ ts.SyntaxKind.GreaterThanGreaterThanToken,
1035
+ ]);
1036
+ /**
1037
+ * A top-level constant's integer expression, folded when the program is compiled: literals and integer constants
1038
+ * declared before it (in this file or an imported one). JS's bigint results (division truncates, `%` keeps the
1039
+ * dividend's sign, `>>` rounds down, as Rust's integers do). With `width` (a typed constant, `const X: u64 = …`), every
1040
+ * step must fit in that type, as Rust computes a typed const; without one the result is a literal, checked where it is
1041
+ * used. Division by zero, a negative exponent or shift, and a value past 256 bits are compile errors.
1042
+ */
1043
+ function foldConstant(e, constants, reporter, width) {
1044
+ const fit = (v, at) => {
1045
+ if (width) {
1046
+ const info = INT_INFO[width];
1047
+ if (v < info.min || v > info.max)
1048
+ reporter.fail(at, `${at.getText()} is ${v}, which does not fit in ${width}: the constant is computed in its type`);
1049
+ }
1050
+ else if (v >= 1n << 256n || v < -(1n << 255n))
1051
+ reporter.fail(at, `${at.getText()} does not fit in 256 bits`);
1052
+ return v;
1053
+ };
1054
+ const fold = (n) => {
1055
+ if (ts.isParenthesizedExpression(n))
1056
+ return fold(n.expression);
1057
+ if (ts.isBigIntLiteral(n))
1058
+ return fit(BigInt(n.text.slice(0, -1).replace(/_/g, "")), n);
1059
+ if (ts.isIdentifier(n)) {
1060
+ const c = constants.get(n.text);
1061
+ if (!c)
1062
+ reporter.fail(n, `${n.text} is not a top-level constant declared before this one: a constant is folded from literals and earlier constants`);
1063
+ if (typeof c.value !== "bigint")
1064
+ reporter.fail(n, `${n.text} is not an integer constant`);
1065
+ return fit(c.value, n);
1066
+ }
1067
+ // A negative literal is one value (i128's minimum is written -170141183460469231731687303715884105728n).
1068
+ if (ts.isPrefixUnaryExpression(n) && n.operator === ts.SyntaxKind.MinusToken && ts.isBigIntLiteral(n.operand))
1069
+ return fit(-BigInt(n.operand.text.slice(0, -1).replace(/_/g, "")), n);
1070
+ if (ts.isPrefixUnaryExpression(n)) {
1071
+ const v = fold(n.operand);
1072
+ if (n.operator === ts.SyntaxKind.MinusToken)
1073
+ return fit(-v, n);
1074
+ // `~x` within the type's width, as at run time; without a type, JS's -x - 1
1075
+ if (width && !INT_INFO[width].signed)
1076
+ return fit(INT_INFO[width].max ^ v, n);
1077
+ return fit(-v - 1n, n);
1078
+ }
1079
+ const b = n;
1080
+ const l = fold(b.left);
1081
+ const r = fold(b.right);
1082
+ switch (b.operatorToken.kind) {
1083
+ case ts.SyntaxKind.PlusToken:
1084
+ return fit(l + r, b);
1085
+ case ts.SyntaxKind.MinusToken:
1086
+ return fit(l - r, b);
1087
+ case ts.SyntaxKind.AsteriskToken:
1088
+ return fit(l * r, b);
1089
+ case ts.SyntaxKind.SlashToken:
1090
+ case ts.SyntaxKind.PercentToken:
1091
+ if (r === 0n)
1092
+ reporter.fail(b, `${b.getText()} divides by zero`);
1093
+ return fit(b.operatorToken.kind === ts.SyntaxKind.SlashToken ? l / r : l % r, b);
1094
+ case ts.SyntaxKind.AsteriskAsteriskToken:
1095
+ if (r < 0n)
1096
+ reporter.fail(b, `${b.getText()} has a negative exponent`);
1097
+ if (r > 256n && l !== 0n && l !== 1n && l !== -1n)
1098
+ reporter.fail(b, `${b.getText()} does not fit in 256 bits`);
1099
+ return fit(l ** r, b);
1100
+ case ts.SyntaxKind.AmpersandToken:
1101
+ return fit(l & r, b);
1102
+ case ts.SyntaxKind.BarToken:
1103
+ return fit(l | r, b);
1104
+ case ts.SyntaxKind.CaretToken:
1105
+ return fit(l ^ r, b);
1106
+ default: {
1107
+ // << and >>: an amount from 0 up to the width (256 without a type), and << may not lose bits (as at run time)
1108
+ const bits = width ? INT_INFO[width].bytes * 8 : 256;
1109
+ if (r < 0n || r >= BigInt(bits))
1110
+ reporter.fail(b, `${b.getText()} shifts by ${r}: the amount is 0 to ${bits - 1}`);
1111
+ return fit(b.operatorToken.kind === ts.SyntaxKind.LessThanLessThanToken ? l << r : l >> r, b);
1112
+ }
1113
+ }
1114
+ };
1115
+ return fold(e);
1116
+ }
1117
+ /**
1118
+ * A struct that is not exported (`interface Pair { … }`) is its file's own: helpers, locals and other such structs use
1119
+ * it, and the IDL leaves it out. What the IDL describes cannot hold one: account data, instruction arguments and
1120
+ * results, events, an exported struct's fields, a data enum's variants. Each such use is one error naming the fix.
1121
+ */
1122
+ function checkLocalStructs(structs, dataEnums, accountStructs, argStructs, events, reporter) {
1123
+ const local = (n) => structs.get(n)?.local === true;
1124
+ const fix = (n, what) => `${n} is not exported, but ${what} uses it, which puts it in the IDL: export interface ${n}`;
1125
+ const named = (t) => t.kind === "struct"
1126
+ ? [t.name]
1127
+ : t.kind === "array" || t.kind === "vec"
1128
+ ? named(t.elem)
1129
+ : t.kind === "option" && (t.inner.kind === "struct" || t.inner.kind === "array")
1130
+ ? named(t.inner)
1131
+ : [];
1132
+ for (const s of structs.values()) {
1133
+ if (s.local) {
1134
+ if (accountStructs.has(s.name))
1135
+ reporter.error(s.node.name, fix(s.name, "account data"));
1136
+ else if (argStructs.has(s.name))
1137
+ reporter.error(s.node.name, fix(s.name, "an instruction's arguments or result"));
1138
+ else if (events.has(s.name))
1139
+ reporter.error(s.node.name, fix(s.name, "an event"));
1140
+ continue;
1141
+ }
1142
+ for (const f of s.fields)
1143
+ for (const n of named(f.type))
1144
+ if (local(n))
1145
+ reporter.error(structs.get(n).node.name, fix(n, `the exported struct ${s.name} (field ${f.name})`));
1146
+ }
1147
+ for (const e of dataEnums.values())
1148
+ for (const v of e.variants)
1149
+ for (const f of v.fields)
1150
+ for (const n of named(f.type))
1151
+ if (local(n))
1152
+ reporter.error(structs.get(n).node.name, fix(n, `the data enum ${e.name} (${v.name}.${f.name})`));
1153
+ }
934
1154
  function collectStructs(t, structs, dataEnums, out) {
935
1155
  const visitField = (f) => {
936
1156
  if (f.kind === "struct") {
@@ -1116,6 +1336,154 @@ function numericLiteralArg(node) {
1116
1336
  return undefined;
1117
1337
  return Number(node.literal.text);
1118
1338
  }
1339
+ /**
1340
+ * What a `type X = …` declares: a data enum (object types, `{ kind: "A"; … } | { kind: "B" }`), an alias of one type
1341
+ * (`u64`, `Point`, `FixedVec<u8, 32>`, `Point | null`), or a union mixing named types, which is neither.
1342
+ */
1343
+ function aliasShape(t) {
1344
+ while (ts.isParenthesizedTypeNode(t))
1345
+ t = t.type;
1346
+ if (ts.isTypeLiteralNode(t))
1347
+ return "dataEnum";
1348
+ if (!ts.isUnionTypeNode(t))
1349
+ return "alias";
1350
+ const members = t.types.filter((m) => !(ts.isLiteralTypeNode(m) && m.literal.kind === ts.SyntaxKind.NullKeyword));
1351
+ if (members.every((m) => ts.isTypeLiteralNode(m)))
1352
+ return "dataEnum";
1353
+ // `Point | null` (an Option) is one type; two named types are not.
1354
+ return members.length === 1 && !members.some((m) => ts.isTypeLiteralNode(m)) ? "alias" : "mixed";
1355
+ }
1356
+ /**
1357
+ * Replace every use of a plain alias (`type Price = u64`) in the program's files by the type it names, so everything
1358
+ * after sees the type itself. The checker says which declaration a name refers to (a type parameter or a local name
1359
+ * may hide an alias). The aliased type keeps its own file's names: the TypeSOL imports it needs are added to the using
1360
+ * file's (the same name meaning two things there is an error).
1361
+ */
1362
+ function substituteAliases(program, entry, simple, fileImports, reporter) {
1363
+ const checker = program.getTypeChecker();
1364
+ const aliasOf = (ref) => {
1365
+ if (!ts.isIdentifier(ref.typeName) || ref.typeArguments?.length)
1366
+ return undefined;
1367
+ let sym = checker.getSymbolAtLocation(ref.typeName);
1368
+ if (sym && sym.flags & ts.SymbolFlags.Alias)
1369
+ sym = checker.getAliasedSymbol(sym);
1370
+ const decl = sym?.declarations?.find((x) => ts.isTypeAliasDeclaration(x) && simple.has(x));
1371
+ return decl;
1372
+ };
1373
+ // The type an alias stands for, itself without aliases (`type A = B; type B = u64`).
1374
+ const resolved = new Map();
1375
+ const resolving = new Set();
1376
+ const target = (decl) => {
1377
+ const done = resolved.get(decl);
1378
+ if (done)
1379
+ return done;
1380
+ if (resolving.has(decl))
1381
+ reporter.fail(decl.name, `type ${decl.name.text} refers to itself`);
1382
+ resolving.add(decl);
1383
+ let t = decl.type;
1384
+ while (ts.isParenthesizedTypeNode(t))
1385
+ t = t.type;
1386
+ if (ts.isTypeReferenceNode(t) && aliasOf(t))
1387
+ t = target(aliasOf(t));
1388
+ else
1389
+ replaceAliases(t);
1390
+ resolving.delete(decl);
1391
+ resolved.set(decl, t);
1392
+ return t;
1393
+ };
1394
+ const replaceAliases = (root) => {
1395
+ const found = [];
1396
+ const visit = (n) => {
1397
+ if (ts.isTypeAliasDeclaration(n) && simple.has(n))
1398
+ return; // resolved on its own
1399
+ if (ts.isTypeReferenceNode(n)) {
1400
+ const decl = aliasOf(n);
1401
+ if (decl) {
1402
+ found.push({ ref: n, decl });
1403
+ return;
1404
+ }
1405
+ }
1406
+ ts.forEachChild(n, visit);
1407
+ };
1408
+ visit(root);
1409
+ for (const { ref, decl } of found)
1410
+ reporter.guard(() => {
1411
+ const to = target(decl);
1412
+ if (!replaceChild(ref.parent, ref, copyForUse(to, ref)))
1413
+ reporter.fail(ref, `type ${decl.name.text} cannot be used here; write the type it names`);
1414
+ // The names the aliased type uses, from its own file's imports, become the using file's too.
1415
+ const from = simple.get(decl);
1416
+ const into = fileImports.get(ref.getSourceFile());
1417
+ if (!into || into === from)
1418
+ return;
1419
+ const names = new Set();
1420
+ const collect = (n) => {
1421
+ if (ts.isIdentifier(n))
1422
+ names.add(n.text);
1423
+ ts.forEachChild(n, collect);
1424
+ };
1425
+ collect(to);
1426
+ for (const name of names) {
1427
+ const meant = from.get(name);
1428
+ if (meant === undefined)
1429
+ continue;
1430
+ const here = into.get(name);
1431
+ if (here !== undefined && here !== meant)
1432
+ reporter.fail(ref, `type ${decl.name.text} uses ${name} (${meant} from "typesol"), which names ${here} in this file; rename one import`);
1433
+ into.set(name, meant);
1434
+ }
1435
+ });
1436
+ };
1437
+ for (const file of programFiles(program, entry))
1438
+ replaceAliases(file);
1439
+ }
1440
+ /**
1441
+ * A copy of an alias's type for one use of it: the same nodes field by field (positions, text and parents still in the
1442
+ * alias's file, so names and source text read as before), but objects of their own, recorded as standing for `use`, so
1443
+ * a diagnostic about the type is reported where the alias is used rather than at its declaration.
1444
+ */
1445
+ function copyForUse(node, use, parent = node.parent) {
1446
+ const copy = Object.assign(Object.create(Object.getPrototypeOf(node)), node);
1447
+ copy.parent = parent;
1448
+ markAliasUse(copy, use);
1449
+ const nodes = new Set();
1450
+ const lists = new Set();
1451
+ ts.forEachChild(node, (n) => void nodes.add(n), (l) => void lists.add(l));
1452
+ const fields = copy;
1453
+ for (const key of Object.keys(fields)) {
1454
+ if (key === "parent")
1455
+ continue;
1456
+ const v = fields[key];
1457
+ if (nodes.has(v))
1458
+ fields[key] = copyForUse(v, use, copy);
1459
+ else if (lists.has(v)) {
1460
+ const l = v;
1461
+ fields[key] = Object.assign(l.map((n) => copyForUse(n, use, copy)), { pos: l.pos, end: l.end, hasTrailingComma: l.hasTrailingComma });
1462
+ }
1463
+ }
1464
+ return copy;
1465
+ }
1466
+ /** Put `to` where `from` is among `parent`'s children (a property or an element of a node list). */
1467
+ function replaceChild(parent, from, to) {
1468
+ const p = parent;
1469
+ for (const key of Object.keys(p)) {
1470
+ if (key === "parent")
1471
+ continue;
1472
+ const v = p[key];
1473
+ if (v === from) {
1474
+ p[key] = to;
1475
+ return true;
1476
+ }
1477
+ if (Array.isArray(v)) {
1478
+ const i = v.indexOf(from);
1479
+ if (i >= 0) {
1480
+ v[i] = to;
1481
+ return true;
1482
+ }
1483
+ }
1484
+ }
1485
+ return false;
1486
+ }
1119
1487
  /**
1120
1488
  * Resolve every exported interface. Field types may name other interfaces, so names are
1121
1489
  * collected first; sizes are computed after, rejecting cycles.
@@ -1182,6 +1550,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1182
1550
  }
1183
1551
  const ext = typesolName(node, imports);
1184
1552
  const targs = node.typeArguments ?? [];
1553
+ if (ext === "BigVec")
1554
+ reporter.fail(node, "BigVec<T> is only the last field of a struct (its elements run to the end of the account), not inside another type");
1185
1555
  if (ext === "FixedArray") {
1186
1556
  if (!targs[0])
1187
1557
  reporter.fail(node, "FixedArray<T, N> needs an element type");
@@ -1219,6 +1589,20 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1219
1589
  return { kind: "struct", name: node.typeName.text };
1220
1590
  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");
1221
1591
  };
1592
+ // `BigVec<T>`: a u32 length, then elements to the end of the account (SPL's big_vec). Only the last field, so its
1593
+ // elements are the account's remaining bytes; T is a scalar or a fixed-size struct.
1594
+ const bigVecField = (m, decl) => {
1595
+ const node = m.type;
1596
+ const elemNode = node.typeArguments?.[0];
1597
+ if (!elemNode || node.typeArguments.length !== 1)
1598
+ reporter.fail(node, "BigVec<T> takes one element type: BigVec<ValidatorStakeInfo>");
1599
+ if (decl.members.at(-1) !== m)
1600
+ 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)`);
1601
+ const elem = fieldType(elemNode);
1602
+ if (!isScalarField(elem) && elem.kind !== "struct")
1603
+ reporter.fail(elemNode, "BigVec elements are integers, booleans, Pubkeys, unit enums or fixed-size structs");
1604
+ return { kind: "vec", elem, big: true };
1605
+ };
1222
1606
  for (const { decl, imports: fileImports } of items) {
1223
1607
  scope = scopeFor(fileImports);
1224
1608
  imports = fileImports;
@@ -1237,7 +1621,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1237
1621
  const problem = cNameProblem(name);
1238
1622
  if (problem)
1239
1623
  reporter.fail(m.name, problem);
1240
- const type = fieldType(m.type);
1624
+ const type = typesolName(m.type, imports) === "BigVec" ? bigVecField(m, decl) : fieldType(m.type);
1241
1625
  // `/** @bytes */`: an integer the IDL describes as its bytes (Marginfi's WrappedI80F48 { value: [u8; 16] }), or a
1242
1626
  // FixedArray of them, each its bytes (Marginfi's HealthCache.prices: [[u8; 8]; 16], f64 bits).
1243
1627
  const bytesTag = ts.getJSDocTags(m).find((t) => t.tagName.text === "bytes");
@@ -1259,6 +1643,11 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1259
1643
  if (layoutTag && layoutText !== "borsh" && layoutText !== "fixed")
1260
1644
  reporter.fail(layoutTag, "@layout is borsh (Anchor's account bytes) or fixed (the default)");
1261
1645
  const growable = (f) => f.type.kind === "vec" && f.type.cap === undefined;
1646
+ const big = fields.find((f) => f.type.kind === "vec" && f.type.big);
1647
+ if (big && layoutText === "borsh")
1648
+ reporter.fail(big.node, "a @layout borsh struct cannot hold a BigVec: BigVec is read in place (loadRaw / loadRawMut) from a fixed layout");
1649
+ if (big && fields.some((f) => f !== big && growable(f)))
1650
+ reporter.fail(big.node, `${decl.name.text} has a Vec and a BigVec: only one list may run to the end of the account`);
1262
1651
  // In a @layout borsh struct a Vec<T> is Anchor's: held on the heap while an instruction runs, any field, bounded
1263
1652
  // only by the account when it is written back.
1264
1653
  if (layoutText === "borsh")
@@ -1276,6 +1665,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1276
1665
  const declared = fields.map((f) => f.name);
1277
1666
  structs.set(name, {
1278
1667
  ...(idlMeta ? { idlMeta } : {}),
1668
+ ...((ts.getModifiers(decl) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ? {} : { local: true }),
1279
1669
  ...(stored.some((f, i) => f.name !== declared[i]) ? { declared } : {}),
1280
1670
  name,
1281
1671
  fields: stored,
@@ -1298,7 +1688,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1298
1688
  const variants = [];
1299
1689
  for (const m of members) {
1300
1690
  if (!ts.isTypeLiteralNode(m))
1301
- reporter.fail(m, 'each variant is an object type: { kind: "Name"; field: Type }');
1691
+ reporter.fail(m, 'each variant of a data enum is an object type, { kind: "Name"; field: Type } (null is not a variant: use Option<Enum>)');
1302
1692
  let vname;
1303
1693
  const fields = [];
1304
1694
  for (const p of m.members) {
@@ -1407,6 +1797,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1407
1797
  visit(s);
1408
1798
  if (s.size === undefined)
1409
1799
  reporter.fail(at, `${t.name} has a string field and cannot be nested; use FixedString<N>`);
1800
+ if (s.bigVec)
1801
+ reporter.fail(at, `${t.name} ends in a BigVec and cannot be nested: read it with loadRaw / loadRawMut`);
1410
1802
  if (s.vec)
1411
1803
  reporter.fail(at, `${t.name} has a growable Vec and can only be account data, not nested`);
1412
1804
  return s.size;
@@ -1478,6 +1870,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1478
1870
  (s.vecs ??= []).push({ name: f.name, elem: f.type.elem, elemSize });
1479
1871
  }
1480
1872
  s.vec = s.vecs?.[0];
1873
+ if (s.vec && s.fields.some((f) => f.name === s.vec.name && f.type.kind === "vec" && f.type.big))
1874
+ s.bigVec = s.vec;
1481
1875
  // The C struct holds the first Vec's length; each further one adds its own when the account is created.
1482
1876
  if (s.vecs && s.size !== undefined)
1483
1877
  s.size -= 4 * (s.vecs.length - 1);
@@ -1703,6 +2097,8 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
1703
2097
  // `p_<name>__n` carries a SignerSeeds count: "__" in a name could collide with it.
1704
2098
  if (p.name.text.includes("__") || p.name.text.includes("$"))
1705
2099
  reporter.error(p.name, `"${p.name.text}": "__" and "$" are reserved in names`);
2100
+ if (typesolName(p.type, scope.imports) === "Inout")
2101
+ return inoutParam(p, reporter, scope, structs);
1706
2102
  const type = resolveValueType(p.type, scope, true) ?? resolveArgAggregate(p.type, scope, structs);
1707
2103
  if (type?.kind === "optionArg")
1708
2104
  reporter.fail(p.type, "helpers take the struct itself: check the Option argument is not null and pass it (or its fields)");
@@ -1710,6 +2106,9 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
1710
2106
  reporter.fail(p.type, "helpers take the list itself: check the Option argument is not null and pass it");
1711
2107
  if (type)
1712
2108
  return { name: p.name.text, type, node: p };
2109
+ // The instruction data (or a slice of it), read-only: a view like a Vec<u8> argument.
2110
+ if (typesolName(p.type, scope.imports) === "InstructionBytes")
2111
+ return { name: p.name.text, type: { kind: "vecArg", elem: { kind: "int", name: "u8" } }, node: p };
1713
2112
  if (typesolName(p.type, scope.imports) === "SignerSeeds")
1714
2113
  return { name: p.name.text, type: { kind: "signerSeeds" }, node: p };
1715
2114
  // One of the remaining accounts (remainingAccounts().get(i)), as the instruction holds it: read with readData or
@@ -1737,7 +2136,70 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
1737
2136
  reporter.fail(p.type, "helpers take accounts that exist: create Init/InitIfNeeded/Zeroed accounts in the instruction, then pass them as Mut<T>");
1738
2137
  return { name: p.name.text, type: { kind: "account" }, account, node: p };
1739
2138
  });
1740
- return { name, display, params, returns, node: fn, statements: bodyStatements(fn, !returns), imports: scope.imports };
2139
+ // `/** @noinline */` on the function (or on the `const f = …` declaring an arrow).
2140
+ const noinline = [fn, ...(ts.isVariableDeclaration(fn.parent) ? [fn.parent] : [])].some((n) => ts.getJSDocTags(n).some((t) => t.tagName.text === "noinline"));
2141
+ return {
2142
+ name,
2143
+ display,
2144
+ params,
2145
+ returns,
2146
+ node: fn,
2147
+ statements: bodyStatements(fn, !returns),
2148
+ imports: scope.imports,
2149
+ ...(noinline ? { noinline } : {}),
2150
+ };
2151
+ }
2152
+ /**
2153
+ * A helper parameter typed `Inout<T>`: a place of the caller's that the helper may change, passed as a pointer. T is a
2154
+ * fixed-size struct, a FixedArray or a FixedVec, which JS passes by reference too; values (integers, Pubkeys, strings,
2155
+ * Options) JS copies, so they are refused with what to write instead.
2156
+ */
2157
+ function inoutParam(p, reporter, scope, structs) {
2158
+ const name = p.name.text;
2159
+ const args = p.type.typeArguments ?? [];
2160
+ if (args.length !== 1)
2161
+ reporter.fail(p.type, "Inout<T> takes one type: a struct, FixedArray<T, N> or FixedVec<T, N>");
2162
+ const t = args[0];
2163
+ const list = typesolName(t, scope.imports);
2164
+ if (list === "FixedVec") {
2165
+ const [e, n] = t.typeArguments ?? [];
2166
+ const cap = numericLiteralArg(n);
2167
+ let elem = e && resolveScalarType(e, scope);
2168
+ if (!elem && e && typesolName(e, scope.imports) === "FixedString") {
2169
+ const fcap = numericLiteralArg(e.typeArguments?.[0]);
2170
+ if (fcap !== undefined && Number.isInteger(fcap) && fcap >= 1 && fcap <= MAX_STRING_CAP)
2171
+ elem = { kind: "fstring", cap: fcap };
2172
+ }
2173
+ if (!elem && e) {
2174
+ const s = structs.get(structNameOf(e, scope) ?? "");
2175
+ if (s && s.size !== undefined && !s.vec && !heapVecOf(s))
2176
+ elem = { kind: "struct", name: s.name };
2177
+ }
2178
+ if (!elem || cap === undefined || !Number.isInteger(cap) || cap < 1)
2179
+ reporter.fail(t, "Inout<FixedVec<T, N>>: T is an integer, boolean, Pubkey, enum, FixedString<N> or a struct of fixed size, N a literal of at least 1");
2180
+ return { name, type: { kind: "vecArg", elem, cap }, inout: { kind: "vec", elem, cap }, node: p };
2181
+ }
2182
+ const agg = resolveArgAggregate(t, scope, structs);
2183
+ if (agg?.kind === "structRef")
2184
+ return { name, type: { ...agg, writable: true }, inout: { kind: "struct", name: agg.struct }, node: p };
2185
+ if (agg?.kind === "arrayArg")
2186
+ return { name, type: agg, inout: agg.array, node: p };
2187
+ const what = t.getText();
2188
+ const scalar = resolveScalarType(t, scope);
2189
+ if (scalar || t.kind === ts.SyntaxKind.StringKeyword || optionInner(t, scope) || list === "FixedString")
2190
+ reporter.fail(p.type, `Inout<${what}>: a ${scalar ? typeName(scalar) : what} is a value, which JS copies into a function too, so the helper cannot change the caller's. Return the new value (x = f(x)), or keep it in a struct and take Inout<ThatStruct>`);
2191
+ if (list === "Vec" || list === "BigVec")
2192
+ reporter.fail(p.type, `Inout<${what}>: a growable list's elements move when it grows; take Inout<FixedVec<T, N>> (fixed room), the struct holding a BigVec's view stays in the function that loaded it`);
2193
+ if (list && ACCOUNT_TYPES.has(list))
2194
+ reporter.fail(p.type, `Inout<${what}>: accounts are passed as they are (Mut<T> is already written in place); Inout<T> takes a struct, FixedArray or FixedVec`);
2195
+ const s = structs.get(structNameOf(t, scope) ?? "");
2196
+ if (s)
2197
+ reporter.fail(p.type, s.bigVec
2198
+ ? `Inout<${s.name}>: ${s.name} ends in a BigVec, whose room depends on its account; pass the account (RemainingAccount) and load it with loadRawMut in the helper, or pass the fields the helper changes`
2199
+ : `Inout<${s.name}>: ${s.name} has variable-size fields; Inout<T> takes a struct of fixed size`);
2200
+ if (ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) && scope.dataEnums?.has(t.typeName.text))
2201
+ reporter.fail(p.type, `Inout<${what}>: a data enum cannot be passed to change yet; keep it in a struct and take Inout<ThatStruct>`);
2202
+ reporter.fail(p.type, `Inout<${what}>: Inout<T> takes a struct of fixed size, a FixedArray<T, N> or a FixedVec<T, N>`);
1741
2203
  }
1742
2204
  /** A function's statements; an arrow's expression body is a `return expr;` (or `expr;` when it returns void). */
1743
2205
  function bodyStatements(fn, isVoid) {
@@ -2305,6 +2767,8 @@ function resolveAccountKind(node, reporter, imports, structs) {
2305
2767
  const s = ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) ? structs.get(t.typeName.text) : undefined;
2306
2768
  if (s && s.size === undefined)
2307
2769
  reporter.fail(t, `${s.name} has a variable-length string field and cannot be account data; use FixedString<N>`);
2770
+ if (s?.bigVec)
2771
+ reporter.fail(t, `${s.name} ends in a BigVec, which is a native program's zero-copy list: take the account as AccountInfo (or a remaining account) and read it with loadRaw<${s.name}> / loadRawMut<${s.name}>`);
2308
2772
  if (s)
2309
2773
  checkAccountMembers(s, t, reporter);
2310
2774
  return s;
@@ -2457,6 +2921,13 @@ function resolveAccountKind(node, reporter, imports, structs) {
2457
2921
  reporter.fail(t, "Mut<T> takes a struct, Signer, AccountInfo, TokenAccount or Mint");
2458
2922
  }
2459
2923
  }
2924
+ const bare = ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) ? structs.get(node.typeName.text) : undefined;
2925
+ if (bare?.bigVec)
2926
+ reporter.fail(node, `${bare.name} ends in a BigVec, so it is account data, not an argument: read it with loadRaw<${bare.name}> / loadRawMut<${bare.name}> from an AccountInfo or a remaining account`);
2927
+ if (typesolName(node, imports) === "BigVec")
2928
+ 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>");
2929
+ if (typesolName(node, imports) === "Inout")
2930
+ 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>");
2460
2931
  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<...>)");
2461
2932
  }
2462
2933
  export { isScalar };