@typesol/cli 0.42.0 → 0.44.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 (78) hide show
  1. package/CHANGELOG.md +350 -0
  2. package/NOTICE +71 -0
  3. package/README.md +35 -18
  4. package/SECURITY.md +32 -5
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.js +5 -5
  7. package/dist/cli.js +196 -72
  8. package/dist/compiler/analyze.js +447 -12
  9. package/dist/compiler/diagnostics.d.ts +1 -0
  10. package/dist/compiler/diagnostics.js +13 -0
  11. package/dist/compiler/emit/alias.d.ts +45 -1
  12. package/dist/compiler/emit/alias.js +143 -6
  13. package/dist/compiler/emit/base.d.ts +28 -1
  14. package/dist/compiler/emit/base.js +77 -9
  15. package/dist/compiler/emit/borsh.js +11 -5
  16. package/dist/compiler/emit/calls.d.ts +80 -0
  17. package/dist/compiler/emit/calls.js +612 -54
  18. package/dist/compiler/emit/cpi-core.d.ts +23 -4
  19. package/dist/compiler/emit/cpi-core.js +261 -12
  20. package/dist/compiler/emit/cpi.js +8 -2
  21. package/dist/compiler/emit/create.js +3 -0
  22. package/dist/compiler/emit/expressions.js +44 -8
  23. package/dist/compiler/emit/function.js +10 -0
  24. package/dist/compiler/emit/program.js +30 -1
  25. package/dist/compiler/emit/rbtree.d.ts +7 -0
  26. package/dist/compiler/emit/rbtree.js +142 -0
  27. package/dist/compiler/emit/shared.d.ts +25 -0
  28. package/dist/compiler/emit/shared.js +45 -4
  29. package/dist/compiler/emit/statements.d.ts +27 -1
  30. package/dist/compiler/emit/statements.js +305 -23
  31. package/dist/compiler/emit/storage.d.ts +25 -2
  32. package/dist/compiler/emit/storage.js +116 -64
  33. package/dist/compiler/emit/token.js +2 -2
  34. package/dist/compiler/emit/views.d.ts +60 -0
  35. package/dist/compiler/emit/views.js +523 -0
  36. package/dist/compiler/idl.js +2 -1
  37. package/dist/compiler/index.d.ts +15 -1
  38. package/dist/compiler/index.js +40 -3
  39. package/dist/compiler/model.d.ts +65 -4
  40. package/dist/compiler/model.js +14 -0
  41. package/dist/compiler/toolchain.d.ts +56 -1
  42. package/dist/compiler/toolchain.js +246 -12
  43. package/dist/testing-stake.d.ts +2 -1
  44. package/dist/testing-stake.js +2 -1
  45. package/dist/testing.js +6 -4
  46. package/dist/tools/clientgen.d.ts +15 -0
  47. package/dist/tools/clientgen.js +173 -7
  48. package/dist/tools/cpigen.d.ts +0 -15
  49. package/dist/tools/cpigen.js +19 -8
  50. package/dist/tools/doctor.d.ts +17 -2
  51. package/dist/tools/doctor.js +64 -4
  52. package/dist/tools/portgen.js +43 -18
  53. package/dist/workspace.d.ts +20 -0
  54. package/dist/workspace.js +173 -6
  55. package/docs/ai.md +10 -5
  56. package/docs/architecture.md +10 -3
  57. package/docs/audit.md +63 -17
  58. package/docs/case-study-escrow.md +1 -1
  59. package/docs/case-study-phoenix.md +226 -0
  60. package/docs/case-study-raydium-amm.md +3 -3
  61. package/docs/case-study-spl-stake-pool.md +5 -5
  62. package/docs/cli.md +17 -8
  63. package/docs/client.md +11 -3
  64. package/docs/errors.md +1 -1
  65. package/docs/language.md +148 -12
  66. package/docs/mainnet.md +21 -10
  67. package/docs/migrate-from-anchor.md +3 -1
  68. package/docs/runtime.md +12 -2
  69. package/docs/security-model.md +38 -6
  70. package/docs/stability.md +42 -4
  71. package/docs/testing.md +25 -0
  72. package/docs/troubleshooting.md +17 -2
  73. package/lib/typesol.d.ts +221 -4
  74. package/llms-full.txt +336 -65
  75. package/llms.txt +2 -2
  76. package/package.json +4 -2
  77. package/runtime/typesol_rt.h +429 -13
  78. package/test/programs/LICENSE-Apache-2.0.txt +201 -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",
@@ -82,6 +83,11 @@ const TYPE_EXPORTS = new Set([
82
83
  "FixedVec",
83
84
  "BigVec",
84
85
  "BigVecSlice",
86
+ "RawArray",
87
+ "ReadonlyRawArray",
88
+ "RedBlackTree",
89
+ "ReadonlyRedBlackTree",
90
+ "RbEntry",
85
91
  "InstructionBytes",
86
92
  "Program",
87
93
  "UncheckedProgram",
@@ -342,6 +348,8 @@ function programFiles(program, entry) {
342
348
  visit(entry);
343
349
  return order;
344
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"];
345
353
  export function analyze(entry, files) {
346
354
  const entryPath = path.resolve(entry);
347
355
  checkImports(entryPath, files);
@@ -359,6 +367,9 @@ export function analyze(entry, files) {
359
367
  const interfaces = [];
360
368
  const groups = new Map();
361
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();
362
373
  /** Program-wide names (structs, enums, helpers) -> declaring file, for collision errors. */
363
374
  const declared = new Map();
364
375
  let entryImports = new Map();
@@ -375,6 +386,7 @@ export function analyze(entry, files) {
375
386
  for (const file of programFiles(program, entryPath)) {
376
387
  const isEntry = file === sourceFile;
377
388
  const imports = new Map();
389
+ fileImports.set(file, imports);
378
390
  if (isEntry)
379
391
  entryImports = imports;
380
392
  for (const stmt of file.statements) {
@@ -396,8 +408,10 @@ export function analyze(entry, files) {
396
408
  }
397
409
  }
398
410
  else if (ts.isInterfaceDeclaration(stmt)) {
399
- if (!isExported(stmt))
400
- 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 …");
401
415
  declare(stmt.name, file);
402
416
  // An interface of accounts is an account group (Anchor's composite `#[derive(Accounts)]` field), not a struct.
403
417
  if (isAccountGroup(stmt, imports))
@@ -406,10 +420,20 @@ export function analyze(entry, files) {
406
420
  interfaces.push({ decl: stmt, imports });
407
421
  }
408
422
  else if (ts.isTypeAliasDeclaration(stmt)) {
409
- if (!isExported(stmt))
410
- reporter.fail(stmt, "data enums (type X = { kind: ... } | ...) must be exported");
411
423
  declare(stmt.name, file);
412
- 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
+ }
413
437
  }
414
438
  else if (ts.isEnumDeclaration(stmt)) {
415
439
  if (!isExported(stmt))
@@ -508,13 +532,26 @@ export function analyze(entry, files) {
508
532
  value = init.kind === ts.SyntaxKind.TrueKeyword;
509
533
  else if (ts.isStringLiteral(init))
510
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);
511
546
  else
512
- 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)');
513
548
  declare(d.name, file);
514
549
  const def = { name: d.name.text, value };
515
550
  constants.set(def.name, def);
516
- if (d.type)
517
- 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 });
518
555
  }
519
556
  }
520
557
  else {
@@ -526,14 +563,38 @@ export function analyze(entry, files) {
526
563
  const fstrings = new Set();
527
564
  const fixedVecs = new Map();
528
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);
529
571
  for (const c of pendingConstTypes) {
530
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
+ }
531
582
  const t = resolveScalarType(c.type, scopeFor(c.imports));
532
583
  if (!t || t.kind !== "int")
533
584
  reporter.fail(c.type, "annotate constants with an integer type, or leave the type out");
534
585
  if (typeof c.def.value !== "bigint")
535
586
  reporter.fail(c.type, "only integer constants take a type annotation");
536
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
+ }
537
598
  if (c.def.value < info.min || c.def.value > info.max)
538
599
  reporter.fail(c.type, `${c.def.value} does not fit in ${t.name}`);
539
600
  c.def.type = t;
@@ -902,6 +963,18 @@ export function analyze(entry, files) {
902
963
  if (instructions.length === 0 && reporter.diagnostics.length === 0)
903
964
  reporter.error(sourceFile, "a TypeSOL program needs at least one exported function (instruction) in its entry file");
904
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);
905
978
  return {
906
979
  model: {
907
980
  name: snakeCase(name).replace(/[^a-z0-9_]/g, "_"),
@@ -918,7 +991,7 @@ export function analyze(entry, files) {
918
991
  dataEnums,
919
992
  options,
920
993
  constants,
921
- events: collectEvents([...functions, ...helperNodes], structs),
994
+ events,
922
995
  accountStructs,
923
996
  foreignAccounts: new Set([...foreignStructs].filter((n) => !ownStructs.has(n))),
924
997
  argStructs,
@@ -926,6 +999,7 @@ export function analyze(entry, files) {
926
999
  fixedVecs,
927
1000
  localVecs: new Map(),
928
1001
  borshNative: new Set(),
1002
+ rbTrees: new Map(),
929
1003
  },
930
1004
  sourceFile,
931
1005
  files: programFiles(program, entryPath).map((f) => f.fileName),
@@ -936,6 +1010,147 @@ export function analyze(entry, files) {
936
1010
  };
937
1011
  }
938
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
+ }
939
1154
  function collectStructs(t, structs, dataEnums, out) {
940
1155
  const visitField = (f) => {
941
1156
  if (f.kind === "struct") {
@@ -1121,6 +1336,154 @@ function numericLiteralArg(node) {
1121
1336
  return undefined;
1122
1337
  return Number(node.literal.text);
1123
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
+ }
1124
1487
  /**
1125
1488
  * Resolve every exported interface. Field types may name other interfaces, so names are
1126
1489
  * collected first; sizes are computed after, rejecting cycles.
@@ -1302,6 +1665,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1302
1665
  const declared = fields.map((f) => f.name);
1303
1666
  structs.set(name, {
1304
1667
  ...(idlMeta ? { idlMeta } : {}),
1668
+ ...((ts.getModifiers(decl) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ? {} : { local: true }),
1305
1669
  ...(stored.some((f, i) => f.name !== declared[i]) ? { declared } : {}),
1306
1670
  name,
1307
1671
  fields: stored,
@@ -1324,7 +1688,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1324
1688
  const variants = [];
1325
1689
  for (const m of members) {
1326
1690
  if (!ts.isTypeLiteralNode(m))
1327
- 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>)');
1328
1692
  let vname;
1329
1693
  const fields = [];
1330
1694
  for (const p of m.members) {
@@ -1733,6 +2097,8 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
1733
2097
  // `p_<name>__n` carries a SignerSeeds count: "__" in a name could collide with it.
1734
2098
  if (p.name.text.includes("__") || p.name.text.includes("$"))
1735
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);
1736
2102
  const type = resolveValueType(p.type, scope, true) ?? resolveArgAggregate(p.type, scope, structs);
1737
2103
  if (type?.kind === "optionArg")
1738
2104
  reporter.fail(p.type, "helpers take the struct itself: check the Option argument is not null and pass it (or its fields)");
@@ -1770,7 +2136,70 @@ function analyzeHelper(fn, name, display, reporter, scope, structs, skip = new S
1770
2136
  reporter.fail(p.type, "helpers take accounts that exist: create Init/InitIfNeeded/Zeroed accounts in the instruction, then pass them as Mut<T>");
1771
2137
  return { name: p.name.text, type: { kind: "account" }, account, node: p };
1772
2138
  });
1773
- 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>`);
1774
2203
  }
1775
2204
  /** A function's statements; an arrow's expression body is a `return expr;` (or `expr;` when it returns void). */
1776
2205
  function bodyStatements(fn, isVoid) {
@@ -2137,6 +2566,10 @@ function analyzeInstruction(fn, reporter, scope, structs, groups = new Map()) {
2137
2566
  const dest = accounts.find((o) => o.name === c.closeTo);
2138
2567
  if (!dest)
2139
2568
  reporter.fail(a.node, `CloseTo<…, "${c.closeTo}">: add an account parameter named "${c.closeTo}"`);
2569
+ // Closing into itself would zero the account and then hand its own lamports back to it: the runtime refuses the
2570
+ // instruction (unbalanced), after everything else ran.
2571
+ if (dest === a)
2572
+ reporter.fail(a.node, `CloseTo<…, "${c.closeTo}">: the destination is the account being closed; name another writable account`);
2140
2573
  }
2141
2574
  });
2142
2575
  }
@@ -2497,6 +2930,8 @@ function resolveAccountKind(node, reporter, imports, structs) {
2497
2930
  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`);
2498
2931
  if (typesolName(node, imports) === "BigVec")
2499
2932
  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>");
2933
+ if (typesolName(node, imports) === "Inout")
2934
+ 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>");
2500
2935
  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<...>)");
2501
2936
  }
2502
2937
  export { isScalar };
@@ -14,6 +14,7 @@ export declare class CompileError extends Error {
14
14
  constructor(diagnostics: Diagnostic[]);
15
15
  }
16
16
  export declare function formatDiagnostic(d: Diagnostic): string;
17
+ export declare function markAliasUse(copy: ts.Node, use: ts.Node): void;
17
18
  export declare function diagnosticAt(node: ts.Node, message: string): Diagnostic;
18
19
  /** Collects diagnostics; `fail` records one and throws to unwind the current construct. */
19
20
  export declare class Reporter {
@@ -9,7 +9,20 @@ export class CompileError extends Error {
9
9
  export function formatDiagnostic(d) {
10
10
  return `${d.file}:${d.line}:${d.column} - error: ${d.message}`;
11
11
  }
12
+ /** Copies of a type alias's nodes put in place of one use of it, with that use (see substituteAliases). */
13
+ const aliasUses = new WeakMap();
14
+ export function markAliasUse(copy, use) {
15
+ aliasUses.set(copy, use);
16
+ }
12
17
  export function diagnosticAt(node, message) {
18
+ // A problem with an aliased type is reported where the alias is used.
19
+ for (let n = node; n; n = n.parent) {
20
+ const use = aliasUses.get(n);
21
+ if (use) {
22
+ node = use;
23
+ break;
24
+ }
25
+ }
13
26
  const sf = node.getSourceFile();
14
27
  const start = node.getStart(sf);
15
28
  const { line, character } = sf.getLineAndCharacterOfPosition(start);