@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
@@ -84,11 +84,34 @@ export type ValueType = ScalarType | {
84
84
  | {
85
85
  kind: "epochRewards";
86
86
  }
87
- /** A struct loaded from a remaining account with loadAccount / loadAccountMut. */
87
+ /**
88
+ * A struct loaded from a remaining account with loadAccount / loadAccountMut. `nullable`: a RedBlackTree's
89
+ * `get(k)` / `remove(k)` of a struct value, NULL when the key is absent (narrowed with `x !== null` before use).
90
+ */
88
91
  | {
89
92
  kind: "structRef";
90
93
  struct: string;
91
94
  writable: boolean;
95
+ nullable?: boolean;
96
+ }
97
+ /** `rawArrayAt<T>(acct, offset, capacity)`: `capacity` elements in place at a run-time offset (`T *` + count). */
98
+ | {
99
+ kind: "rawArray";
100
+ elem: FieldType;
101
+ writable: boolean;
102
+ }
103
+ /** `rbTreeAt<K, V>(acct, offset, capacity, compare?)`: lib-sokoban's RedBlackTree in place (a `TsRbt`). */
104
+ | {
105
+ kind: "rbTree";
106
+ inst: string;
107
+ writable: boolean;
108
+ }
109
+ /** A node of a RedBlackTree (min / max / nodeAt / for … of): a `TsRbtEntry`; `nullable` for min / max. */
110
+ | {
111
+ kind: "rbEntry";
112
+ inst: string;
113
+ writable: boolean;
114
+ nullable?: boolean;
92
115
  }
93
116
  /** A data-enum place (local value, argument, or alias into account data): `TS_DE_<name> *`. */
94
117
  | {
@@ -134,7 +157,8 @@ export type FieldType = ScalarType | {
134
157
  * room for N elements. With `heap`, a `Vec<T>` in a `@layout borsh` struct: Anchor's Vec, held on the heap while the
135
158
  * instruction runs (`TSH_*`: length, capacity, elements) and bounded only by the account when it is written back.
136
159
  * With `big`, a `BigVec<T>` (the last field of a struct read with loadRaw): stored like a trailing Vec, its room set by
137
- * the account's size, never resized.
160
+ * the account's size, never resized. With `raw` (and `big`), a `rawArrayAt` view: a run-time count of elements in
161
+ * place, no stored length.
138
162
  */
139
163
  | {
140
164
  kind: "vec";
@@ -143,6 +167,7 @@ export type FieldType = ScalarType | {
143
167
  heap?: true;
144
168
  optional?: true;
145
169
  big?: true;
170
+ raw?: true;
146
171
  };
147
172
  export interface StructField {
148
173
  name: string;
@@ -187,6 +212,8 @@ export interface StructDef {
187
212
  accountDiscriminator: number[];
188
213
  eventDiscriminator: number[];
189
214
  node: ts.InterfaceDeclaration;
215
+ /** Not exported (`interface Pair { … }`): its file's own, for helpers and locals, and left out of the IDL. */
216
+ local?: true;
190
217
  /**
191
218
  * How account data stores it: "fixed" (every field at a fixed offset, the default) or "borsh" (`@layout borsh`:
192
219
  * Anchor's bytes, where strings, Vecs and Options take only what they hold).
@@ -438,6 +465,13 @@ export interface HelperParam {
438
465
  /** `{ kind: "account" }` for account parameters (then `account` says which kind). */
439
466
  type: ValueType;
440
467
  account?: ParamKind;
468
+ /**
469
+ * `Inout<T>`: the caller's place itself, which the helper may change (a pointer, never a copy). `type` is then a
470
+ * writable structRef, an arrayArg, or (for a FixedVec) a vecArg standing in for the place; code reads `inout` first.
471
+ */
472
+ inout?: FieldType & {
473
+ kind: "struct" | "array" | "vec";
474
+ };
441
475
  node: ts.ParameterDeclaration;
442
476
  }
443
477
  /** A function written as `function f(…)`, `const f = (…) => …` or `const f = function (…) {…}`. */
@@ -472,14 +506,19 @@ export interface Helper {
472
506
  fnArgIndexes?: number[];
473
507
  /** The declaring file's `typesol` imports (local name -> export name). */
474
508
  imports: Map<string, string>;
509
+ /** `/** @noinline *\/`: a C function of its own that clang never inlines, so its locals get a stack frame of their own. */
510
+ noinline?: boolean;
475
511
  }
476
512
  /** A top-level compile-time constant. `type` is set when annotated (`const FEE: u16 = 30n`). */
477
513
  export interface ConstDef {
478
514
  name: string;
479
- /** `{ pubkey }` for `const ADMIN = pubkey("…")`: the decoded 32 bytes. */
515
+ /**
516
+ * `{ pubkey }` for `const ADMIN = pubkey("…")`: the decoded 32 bytes; `null` only for ERROR_LOG_PREFIX /
517
+ * PROGRAM_ERROR_LOG_PREFIX (failures that log nothing).
518
+ */
480
519
  value: bigint | boolean | string | {
481
520
  pubkey: number[];
482
- };
521
+ } | null;
483
522
  type?: ScalarType;
484
523
  }
485
524
  /** A data-carrying enum: `export type Action = { kind: "Deposit"; amount: u64 } | { kind: "Pause" }`. */
@@ -574,6 +613,28 @@ export interface ProgramModel {
574
613
  }>;
575
614
  /** Structs read or written with loadBorsh / storeBorsh, filled in while emitting: their ts_bdec_ / ts_benc_ codecs. */
576
615
  borshNative: Set<string>;
616
+ /** RedBlackTree instances (key, value, comparator), filled in while emitting: their per-tree C functions. */
617
+ rbTrees: Map<string, RbTreeInst>;
618
+ /**
619
+ * The program makes views of native accounts (loadRaw, loadRawAt, rawArrayAt, rbTreeAt and their Mut forms): their
620
+ * owner checks share one cache (ts_owned), forgotten at every CPI and owner write. Set before any body is emitted.
621
+ */
622
+ ownerCache?: boolean;
623
+ }
624
+ /**
625
+ * One `rbTreeAt<K, V>(…, compare?)` instantiation: lib-sokoban 0.3's RedBlackTree<K, V, N> over K and V (N is the
626
+ * run-time capacity). `c` is the prefix of its C functions (`ts_rbt<n>_find` …); `compare` the helper ordering keys
627
+ * (`compare(searched, nodeKey)`: negative, 0 or positive), or none for the default order.
628
+ */
629
+ export interface RbTreeInst {
630
+ key: string;
631
+ c: string;
632
+ keyType: FieldType;
633
+ valueType: FieldType;
634
+ keySize: number;
635
+ valueSize: number;
636
+ stride: number;
637
+ compare?: Helper;
577
638
  }
578
639
  export declare function isWritable(k: ParamKind): boolean;
579
640
  export declare function typeName(t: ValueType | FieldType): string;
@@ -61,6 +61,8 @@ export function typeName(t) {
61
61
  case "vec":
62
62
  if (t.optional)
63
63
  return `Option<Vec<${typeName(t.elem)}>>`;
64
+ if (t.raw)
65
+ return `RawArray<${typeName(t.elem)}>`;
64
66
  if (t.big)
65
67
  return `BigVec<${typeName(t.elem)}>`;
66
68
  return t.cap === undefined ? `Vec<${typeName(t.elem)}>` : `FixedVec<${typeName(t.elem)}, ${t.cap}>`;
@@ -82,6 +84,12 @@ export function typeName(t) {
82
84
  return "EpochRewards";
83
85
  case "structRef":
84
86
  return t.struct;
87
+ case "rawArray":
88
+ return `RawArray<${typeName(t.elem)}>`;
89
+ case "rbTree":
90
+ return "RedBlackTree";
91
+ case "rbEntry":
92
+ return "RbEntry";
85
93
  }
86
94
  }
87
95
  export function sameType(a, b) {
@@ -109,6 +117,7 @@ export function sameType(a, b) {
109
117
  !a.heap === !b.heap &&
110
118
  !a.optional === !b.optional &&
111
119
  !a.big === !b.big &&
120
+ !a.raw === !b.raw &&
112
121
  sameType(a.elem, b.elem));
113
122
  case "vecArg":
114
123
  return !a.optional === !b.optional && sameType(a.elem, b.elem);
@@ -118,6 +127,11 @@ export function sameType(a, b) {
118
127
  return sameType(a.option, b.option);
119
128
  case "structRef":
120
129
  return a.struct === b.struct;
130
+ case "rawArray":
131
+ return sameType(a.elem, b.elem);
132
+ case "rbTree":
133
+ case "rbEntry":
134
+ return a.inst === b.inst;
121
135
  case "dataEnum":
122
136
  case "dataEnumArg":
123
137
  case "enumRef":
@@ -17,5 +17,60 @@ export declare function findToolchain(sbpf?: Sbpf): Toolchain;
17
17
  /** The SBF stack frame of one function. */
18
18
  export declare const STACK_FRAME = 4096;
19
19
  export declare function buildSharedObject(cFile: string, outSo: string, sbpf?: Sbpf, tc?: Toolchain): void;
20
- /** The clang version string, for build manifests. */
20
+ /**
21
+ * The toolchain this release is tested with: CI installs exactly this Agave CLI and platform-tools, and every
22
+ * execution, differential and fuzz test runs on binaries this clang built. The C TypeSOL emits is only checked
23
+ * against this backend; another clang can compile it differently (how struct arguments are passed, for one), so
24
+ * binaries from another toolchain are outside what the tests cover. Changing it is a release note.
25
+ */
26
+ export declare const TESTED_TOOLCHAIN: {
27
+ readonly agave: "3.1.10";
28
+ readonly platformTools: "v1.52";
29
+ readonly clang: "clang version 20.1.7-rust-dev (https://github.com/anza-xyz/llvm-project.git 78496716176191b2dfb728e5e38501812e7467db)";
30
+ };
31
+ /** The commands that install the tested toolchain (the Agave CLI, then its platform-tools). */
32
+ export declare const INSTALL_TESTED_TOOLCHAIN: readonly ["sh -c \"$(curl -sSfL https://release.anza.xyz/v3.1.10/install)\"", "cargo-build-sbf --install-only --force-tools-install --tools-version v1.52"];
33
+ /** The clang version string (the first line of `clang --version`), for build manifests. */
21
34
  export declare function toolchainVersion(tc?: Toolchain): string;
35
+ /**
36
+ * The platform-tools version of an SDK, or undefined when it cannot be told for sure. cargo-build-sbf records the
37
+ * installed version as an empty `dependencies/platform-tools-<version>.md` next to `dependencies/platform-tools`,
38
+ * which links into `~/.cache/solana/<version>/platform-tools`; both have to agree when both are there.
39
+ */
40
+ export declare function platformToolsVersion(tc?: Pick<Toolchain, "sdk">): string | undefined;
41
+ /** A clang version line made short enough for a message: `clang 20.1.7-rust-dev (anza-xyz/llvm-project 78496716)`. */
42
+ export declare function shortClang(version: string): string;
43
+ export interface ToolchainInfo {
44
+ clang: string;
45
+ platformTools?: string;
46
+ /** The clang is the one the release is tested with. */
47
+ tested: boolean;
48
+ }
49
+ /** The active toolchain's versions, and whether it is the tested one (the clang is what compiles, so it decides). */
50
+ export declare function toolchainInfo(tc?: Toolchain): ToolchainInfo;
51
+ /** What to say about a toolchain that is not the tested one; undefined for the tested one. */
52
+ export declare function untestedToolchainMessage(info: ToolchainInfo): string | undefined;
53
+ /** `--toolchain-strict`: refuse an untested toolchain for the rest of the process, as TYPESOL_TOOLCHAIN=strict does. */
54
+ export declare function setToolchainStrict(on?: boolean): void;
55
+ /** Whether an untested toolchain is an error: `--toolchain-strict` or TYPESOL_TOOLCHAIN=strict ("warn", the default). */
56
+ export declare function toolchainStrict(): boolean;
57
+ /**
58
+ * Before a build: an untested toolchain gets one warning per process on stderr (a workspace or a test run builds many
59
+ * programs), or an error in strict mode. `info` is the active toolchain's, unless given.
60
+ */
61
+ export declare function checkToolchain(info?: ToolchainInfo, warn?: (message: string) => void): ToolchainInfo;
62
+ /** One variable slot of a function's stack frame as clang laid it out: its size and the C variables sharing it. */
63
+ export interface FrameSlot {
64
+ size: number;
65
+ vars: {
66
+ name: string;
67
+ line: number;
68
+ }[];
69
+ }
70
+ /** clang's `-Rpass-analysis=stack-frame-layout` remarks: each function's variable slots. */
71
+ export declare function frameLayouts(remarks: string): Map<string, FrameSlot[]>;
72
+ /**
73
+ * clang's frame-size errors in the program's terms: which instruction or helper, how much, the locals that take the
74
+ * room (from `layouts`, clang's frame layout of the generated C `c`) and what to do.
75
+ */
76
+ export declare function stackError(message: string, layouts?: Map<string, FrameSlot[]>, c?: string): Error;
@@ -1,5 +1,5 @@
1
- import { execFileSync } from "node:child_process";
2
- import { existsSync, readdirSync, rmSync } from "node:fs";
1
+ import { execFileSync, spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
@@ -79,7 +79,18 @@ export function buildSharedObject(cFile, outSo, sbpf = "v0", tc = findToolchain(
79
79
  run(tc.clang, [...cflags, ...incs, "-o", obj, "-c", cFile]);
80
80
  }
81
81
  catch (e) {
82
- throw stackError(e.message) ?? e;
82
+ const message = e.message;
83
+ if (!STACK_OVER.test(message))
84
+ throw e;
85
+ // Compiled again with debug info for clang's frame layout: which locals take the room.
86
+ const layoutFlags = cflags.filter((f) => f !== "-Werror" && !f.startsWith("-Wframe-larger-than"));
87
+ const res = spawnSync(tc.clang, [...layoutFlags, ...incs, "-g", "-w", "-Rpass-analysis=stack-frame-layout", "-o", obj, "-c", cFile], {
88
+ encoding: "utf8",
89
+ // A large program's remarks (one per function, every slot listed) run past the default 1 MiB.
90
+ maxBuffer: 256 * 1024 * 1024,
91
+ });
92
+ rmSync(obj, { force: true });
93
+ throw stackError(message, frameLayouts(res.stderr ?? ""), readFileSync(cFile, "utf8"));
83
94
  }
84
95
  run(tc.lld, [
85
96
  "-z",
@@ -105,15 +116,142 @@ export function buildSharedObject(cFile, outSo, sbpf = "v0", tc = findToolchain(
105
116
  ]);
106
117
  rmSync(obj, { force: true }); // the object file is only an intermediate
107
118
  }
108
- /** The clang version string, for build manifests. */
119
+ /**
120
+ * The toolchain this release is tested with: CI installs exactly this Agave CLI and platform-tools, and every
121
+ * execution, differential and fuzz test runs on binaries this clang built. The C TypeSOL emits is only checked
122
+ * against this backend; another clang can compile it differently (how struct arguments are passed, for one), so
123
+ * binaries from another toolchain are outside what the tests cover. Changing it is a release note.
124
+ */
125
+ export const TESTED_TOOLCHAIN = {
126
+ agave: "3.1.10",
127
+ platformTools: "v1.52",
128
+ clang: "clang version 20.1.7-rust-dev (https://github.com/anza-xyz/llvm-project.git 78496716176191b2dfb728e5e38501812e7467db)",
129
+ };
130
+ /** The commands that install the tested toolchain (the Agave CLI, then its platform-tools). */
131
+ export const INSTALL_TESTED_TOOLCHAIN = [
132
+ `sh -c "$(curl -sSfL https://release.anza.xyz/v${TESTED_TOOLCHAIN.agave}/install)"`,
133
+ `cargo-build-sbf --install-only --force-tools-install --tools-version ${TESTED_TOOLCHAIN.platformTools}`,
134
+ ];
135
+ // One `clang --version` per clang a process uses: up-to-date checks and manifests ask for it on every build.
136
+ const clangVersions = new Map();
137
+ /** The clang version string (the first line of `clang --version`), for build manifests. */
109
138
  export function toolchainVersion(tc = findToolchain()) {
110
- return execFileSync(tc.clang, ["--version"], { encoding: "utf8" }).split("\n")[0].trim();
139
+ let v = clangVersions.get(tc.clang);
140
+ if (v === undefined) {
141
+ v = execFileSync(tc.clang, ["--version"], { encoding: "utf8" }).split("\n")[0].trim();
142
+ clangVersions.set(tc.clang, v);
143
+ }
144
+ return v;
111
145
  }
112
- /** clang's frame-size errors, in the program's terms: which instruction or helper, how much, what to do. */
113
- function stackError(message) {
114
- const over = [...message.matchAll(/stack frame size \((\d+)\) exceeds limit \((\d+)\) in '(\w+)'/g)];
115
- if (!over.length)
146
+ /**
147
+ * The platform-tools version of an SDK, or undefined when it cannot be told for sure. cargo-build-sbf records the
148
+ * installed version as an empty `dependencies/platform-tools-<version>.md` next to `dependencies/platform-tools`,
149
+ * which links into `~/.cache/solana/<version>/platform-tools`; both have to agree when both are there.
150
+ */
151
+ export function platformToolsVersion(tc = findToolchain()) {
152
+ const deps = path.join(tc.sdk, "dependencies");
153
+ let markers;
154
+ try {
155
+ markers = readdirSync(deps).flatMap((f) => /^platform-tools-(v\d+\.\d+(?:\.\d+)?)\.md$/.exec(f)?.[1] ?? []);
156
+ }
157
+ catch {
116
158
  return undefined;
159
+ }
160
+ let linked;
161
+ try {
162
+ linked = /[/\\](v\d+\.\d+(?:\.\d+)?)[/\\]platform-tools$/.exec(realpathSync(path.join(deps, "platform-tools")))?.[1];
163
+ }
164
+ catch {
165
+ /* no platform-tools directory */
166
+ }
167
+ if (linked)
168
+ return markers.length === 0 || markers.includes(linked) ? linked : undefined;
169
+ return markers.length === 1 ? markers[0] : undefined;
170
+ }
171
+ /** A clang version line made short enough for a message: `clang 20.1.7-rust-dev (anza-xyz/llvm-project 78496716)`. */
172
+ export function shortClang(version) {
173
+ return version
174
+ .replace(/^clang version /, "clang ")
175
+ .replace(/\(https:\/\/github\.com\/([^\s)]+?)(?:\.git)? ([0-9a-f]{8})[0-9a-f]*\)/, "($1 $2)")
176
+ .trim();
177
+ }
178
+ /** The active toolchain's versions, and whether it is the tested one (the clang is what compiles, so it decides). */
179
+ export function toolchainInfo(tc = findToolchain()) {
180
+ const clang = toolchainVersion(tc);
181
+ return { clang, platformTools: platformToolsVersion(tc), tested: clang === TESTED_TOOLCHAIN.clang };
182
+ }
183
+ /** What to say about a toolchain that is not the tested one; undefined for the tested one. */
184
+ export function untestedToolchainMessage(info) {
185
+ if (info.tested)
186
+ return undefined;
187
+ const t = TESTED_TOOLCHAIN;
188
+ return (`this build uses ${shortClang(info.clang)}${info.platformTools ? ` (platform-tools ${info.platformTools})` : ""}; ` +
189
+ `TypeSOL is tested with ${shortClang(t.clang)} (platform-tools ${t.platformTools}, Agave ${t.agave}). ` +
190
+ `Binaries from an untested toolchain are not covered by the project's tests. ` +
191
+ `Install the tested one: ${INSTALL_TESTED_TOOLCHAIN[1]}`);
192
+ }
193
+ let strictFlag = false;
194
+ let warned = false;
195
+ /** `--toolchain-strict`: refuse an untested toolchain for the rest of the process, as TYPESOL_TOOLCHAIN=strict does. */
196
+ export function setToolchainStrict(on = true) {
197
+ strictFlag = on;
198
+ }
199
+ /** Whether an untested toolchain is an error: `--toolchain-strict` or TYPESOL_TOOLCHAIN=strict ("warn", the default). */
200
+ export function toolchainStrict() {
201
+ const env = process.env.TYPESOL_TOOLCHAIN;
202
+ if (env && env !== "strict" && env !== "warn")
203
+ throw new Error(`TYPESOL_TOOLCHAIN=${env}: expected "strict" or "warn"`);
204
+ return strictFlag || env === "strict";
205
+ }
206
+ /**
207
+ * Before a build: an untested toolchain gets one warning per process on stderr (a workspace or a test run builds many
208
+ * programs), or an error in strict mode. `info` is the active toolchain's, unless given.
209
+ */
210
+ export function checkToolchain(info = toolchainInfo(), warn = (m) => console.error(`warning: ${m}`)) {
211
+ const message = untestedToolchainMessage(info);
212
+ if (!message)
213
+ return info;
214
+ if (toolchainStrict())
215
+ throw new Error(`${message.replace(/^this build uses/, "refusing to build with")} (an untested toolchain is an error with --toolchain-strict or TYPESOL_TOOLCHAIN=strict)`);
216
+ if (!warned) {
217
+ warned = true;
218
+ warn(message);
219
+ }
220
+ return info;
221
+ }
222
+ const STACK_OVER = /stack frame size \((\d+)\) exceeds limit \((\d+)\) in '(\w+)'/;
223
+ /** clang's `-Rpass-analysis=stack-frame-layout` remarks: each function's variable slots. */
224
+ export function frameLayouts(remarks) {
225
+ const out = new Map();
226
+ for (const block of remarks.split(/^Function: /m).slice(1)) {
227
+ const lines = block.split("\n");
228
+ const fn = lines[0].trim().split(/\s/)[0];
229
+ const slots = [];
230
+ let slot;
231
+ for (const l of lines.slice(1)) {
232
+ const off = /^Offset: \[SP-?\d+\], Type: (\w+), Align: \d+, Size: (\d+)/.exec(l);
233
+ if (off) {
234
+ slot = off[1] === "Variable" ? { size: Number(off[2]), vars: [] } : undefined;
235
+ if (slot)
236
+ slots.push(slot);
237
+ continue;
238
+ }
239
+ const v = /^ {4}(\w+) @ .*:(\d+)(\s|$)/.exec(l);
240
+ if (v && slot)
241
+ slot.vars.push({ name: v[1], line: Number(v[2]) });
242
+ else
243
+ slot = undefined;
244
+ }
245
+ out.set(fn, slots);
246
+ }
247
+ return out;
248
+ }
249
+ /**
250
+ * clang's frame-size errors in the program's terms: which instruction or helper, how much, the locals that take the
251
+ * room (from `layouts`, clang's frame layout of the generated C `c`) and what to do.
252
+ */
253
+ export function stackError(message, layouts = new Map(), c = "") {
254
+ const over = [...message.matchAll(new RegExp(STACK_OVER.source, "g"))];
117
255
  // clang inlines helpers into their callers, so an instruction's frame includes theirs.
118
256
  const what = (fn) => fn.startsWith("ix_") ? `instruction ${fn.slice(3)} (with the helpers inlined into it)` : fn.startsWith("fn_") ? `helper ${fn.slice(3)}()` : fn;
119
257
  // Anything else clang reported in the same run stays in the message.
@@ -121,13 +259,109 @@ function stackError(message) {
121
259
  .split("\n")
122
260
  .filter((l) => / error: /.test(l) && !/-Wframe-larger-than/.test(l))
123
261
  .join("\n");
124
- return new Error(over.map((m) => `${what(m[3])} needs ${m[1]} bytes of stack; SBPF v0 gives each function ${m[2]}`).join("\n") +
125
- "\nKeep large structs and arrays in account data: bind them with const (a reference) instead of a typed local copy, or split the work into helpers." +
262
+ const cLines = c.split("\n");
263
+ // The C function a line of the generated C belongs to.
264
+ const fnAt = (line) => {
265
+ for (let i = line - 1; i >= 0; i--) {
266
+ const m = /^(?:__attribute__\(\(noinline\)\) )?static uint64_t ((?:fn|ix)_\w+)\(.*\) \{$/.exec(cLines[i] ?? "");
267
+ if (m)
268
+ return m[1];
269
+ }
270
+ return undefined;
271
+ };
272
+ // The source location nearest a line: the generated C carries one in its runtime messages ("(file.ts:12)").
273
+ const near = (line) => {
274
+ for (let d = 0; d < 40; d++)
275
+ for (const i of [line - 1 + d, line - 1 - d]) {
276
+ const m = /\(([\w.-]+\.ts):(\d+)\)/.exec(cLines[i] ?? "");
277
+ if (m)
278
+ return `${m[1]}:${m[2]}`;
279
+ }
280
+ return undefined;
281
+ };
282
+ // The C functions' bodies, and the struct and list locals of the helpers `fn` calls that clang may inline into it.
283
+ const bodies = new Map();
284
+ let current;
285
+ for (const l of cLines) {
286
+ const m = /^(__attribute__\(\(noinline\)\) )?static uint64_t ((?:fn|ix)_\w+)\(.*\) \{$/.exec(l);
287
+ if (m)
288
+ bodies.set(m[2], (current = []));
289
+ else if (l === "}")
290
+ current = undefined;
291
+ else
292
+ current?.push(l);
293
+ }
294
+ const noinline = new Set(cLines.flatMap((l) => /^__attribute__\(\(noinline\)\) static uint64_t ((?:fn|ix)_\w+)\(/.exec(l)?.[1] ?? []));
295
+ const inlinedLocals = (fn) => {
296
+ const out = [];
297
+ const seen = new Set();
298
+ const visit = (f) => {
299
+ for (const l of bodies.get(f) ?? [])
300
+ for (const call of l.matchAll(/\b(fn_\w+)\(/g)) {
301
+ const callee = call[1];
302
+ if (seen.has(callee) || noinline.has(callee))
303
+ continue;
304
+ seen.add(callee);
305
+ for (const d of bodies.get(callee) ?? []) {
306
+ const local = /^\s+TS[SFE]_\w+ l_(\w+?)_\d+(__v)?;$/.exec(d);
307
+ if (local)
308
+ out.push(`\`${local[1]}\` (${callee.slice(3)}())`);
309
+ }
310
+ visit(callee);
311
+ }
312
+ };
313
+ visit(fn);
314
+ return out;
315
+ };
316
+ const describe = (name) => {
317
+ const local = /^l_(\w+?)_\d+(__v|__h)?$/.exec(name);
318
+ if (local)
319
+ return `\`${local[1]}\``;
320
+ if (/^p_\w+$/.test(name))
321
+ return `parameter \`${name.slice(2)}\``;
322
+ const temps = [
323
+ [/^fv\d+$/, "a list literal's temporary"],
324
+ [/^st\d+$/, "a struct literal's temporary"],
325
+ [/^de\d+$/, "a data enum literal's temporary"],
326
+ [/^evv\d+$/, "an event's FixedVec"],
327
+ [/^bv\d+$/, "a pushBorsh value"],
328
+ [/^t\d+$/, "a helper's result"],
329
+ [/^s\d+$/, "a log line's text"],
330
+ ];
331
+ return temps.find(([re]) => re.test(name))?.[1] ?? `a temporary (${name})`;
332
+ };
333
+ const locals = (fn) => {
334
+ const slots = (layouts.get(fn) ?? []).filter((s) => s.size >= 64).sort((a, b) => b.size - a.size);
335
+ if (!slots.length)
336
+ return "";
337
+ const shown = slots.slice(0, 5).map((s) => {
338
+ const names = s.vars.map((v) => {
339
+ const owner = fnAt(v.line);
340
+ const at = near(v.line);
341
+ const where = [owner && owner !== fn ? `in ${what(owner).replace(" (with the helpers inlined into it)", "")}` : "", at ? `near ${at}` : ""]
342
+ .filter(Boolean)
343
+ .join(", ");
344
+ return `${describe(v.name)}${where ? ` (${where})` : ""}`;
345
+ });
346
+ // Variables whose lifetimes do not overlap share a slot. clang names no variable of an inlined helper.
347
+ return `${s.size} bytes: ${names.length ? [...new Set(names)].join(" / ") : "unnamed"}`;
348
+ });
349
+ const unnamed = slots.slice(0, 5).some((s) => !s.vars.length);
350
+ const inlined = unnamed ? inlinedLocals(fn) : [];
351
+ return (`\n biggest locals: ${shown.join("; ")}` +
352
+ (unnamed
353
+ ? inlined.length
354
+ ? `\n (unnamed: locals of the helpers inlined into it, among ${inlined.join(", ")}, or copies clang made)`
355
+ : "\n (unnamed: copies clang made)"
356
+ : ""));
357
+ };
358
+ return new Error(over.map((m) => `${what(m[3])} needs ${m[1]} bytes of stack; SBPF v0 gives each function ${m[2]}${locals(m[3])}`).join("\n") +
359
+ "\nKeep large structs and arrays in account data (bind them with const: a reference, not a copy), give a large local list or struct its own room with /** @heap */ (in an instruction), or move work that needs large locals of its own into a /** @noinline */ helper, which gets its own 4 KiB frame." +
126
360
  (rest ? `\n${rest}` : ""));
127
361
  }
128
362
  function run(cmd, args) {
129
363
  try {
130
- execFileSync(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
364
+ execFileSync(cmd, args, { stdio: ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 });
131
365
  }
132
366
  catch (e) {
133
367
  const err = e;
@@ -77,7 +77,8 @@ export interface StakeActivationOptions {
77
77
  }
78
78
  /**
79
79
  * The effective, activating and deactivating stake of a delegation at `targetEpoch`, given the cluster's stake history:
80
- * an exact port of `Delegation::stake_activating_and_deactivating_v2` (solana-stake-interface 4.3.0), BigInt math with
80
+ * an exact port of `Delegation::stake_activating_and_deactivating_v2` (solana-stake-interface 4.3.0,
81
+ * https://github.com/solana-program/stake, Copyright Anza Maintainers; licence recorded in NOTICE), BigInt math with
81
82
  * its u128 saturation. `newRateActivationEpoch` is the epoch from which warmup and cooldown are 9% per epoch rather
82
83
  * than 25%: 0 (the default) as the Stake program has it on every cluster; `null` for 25% throughout (Rust's None).
83
84
  */
@@ -130,7 +130,8 @@ function allowanceFloat(epoch, account, clusterPortion, clusterEffective, rateEp
130
130
  }
131
131
  /**
132
132
  * The effective, activating and deactivating stake of a delegation at `targetEpoch`, given the cluster's stake history:
133
- * an exact port of `Delegation::stake_activating_and_deactivating_v2` (solana-stake-interface 4.3.0), BigInt math with
133
+ * an exact port of `Delegation::stake_activating_and_deactivating_v2` (solana-stake-interface 4.3.0,
134
+ * https://github.com/solana-program/stake, Copyright Anza Maintainers; licence recorded in NOTICE), BigInt math with
134
135
  * its u128 saturation. `newRateActivationEpoch` is the epoch from which warmup and cooldown are 9% per epoch rather
135
136
  * than 25%: 0 (the default) as the Stake program has it on every cluster; `null` for 25% throughout (Rust's None).
136
137
  */
package/dist/testing.js CHANGED
@@ -25,7 +25,7 @@ import { fileURLToPath } from "node:url";
25
25
  import { TYPESOL_ERRORS } from "./tools/clientgen.js";
26
26
  import { loadClonedAccounts } from "./tools/clone.js";
27
27
  import { svmConnection } from "./tools/svmrpc.js";
28
- import { buildWorkspace, findWorkspace } from "./workspace.js";
28
+ import { buildForTest, findWorkspace } from "./workspace.js";
29
29
  export { svmConnection };
30
30
  export * from "./testing-stake.js";
31
31
  /** Load what `typesol clone` wrote (a directory of `<address>.json` accounts and `<address>.so` programs) into a LiteSVM. */
@@ -64,13 +64,15 @@ export async function testProgram(program, from) {
64
64
  throw new Error(`no typesol.json at or above ${start}`);
65
65
  if (!ws.programs[program])
66
66
  throw new Error(`typesol.json has no program "${program}" (it has ${Object.keys(ws.programs).join(", ")})`);
67
- const [built] = buildWorkspace(ws, [program]);
67
+ // Every test file calls this, often in parallel workers: an up-to-date build is reused, and concurrent builds of the
68
+ // same program wait for each other instead of writing over each other's files.
69
+ const built = buildForTest(ws, program);
68
70
  const svm = new LiteSVM();
69
71
  const programId = built.address;
70
- svm.addProgramFromFile(programId, built.result.soPath);
72
+ svm.addProgramFromFile(programId, built.soPath);
71
73
  // Accounts and programs `typesol clone` copied from a cluster (tests/accounts), in place before the first test.
72
74
  loadClonedAccounts(svm, ws.accounts);
73
- return programHarness(svm, programId, built.result.idl);
75
+ return programHarness(svm, programId, built.idl);
74
76
  }
75
77
  /** The same helpers for a program already loaded into `svm` at `programId` with this IDL. */
76
78
  export function programHarness(svm, programId, idl) {
@@ -95,6 +95,21 @@ export declare class ClientIdlError extends Error {
95
95
  * the constraints raise their Anchor codes), then TypeSOL's own runtime errors (runtime/typesol_rt.h).
96
96
  */
97
97
  export declare const TYPESOL_ERRORS: Record<number, string>;
98
+ /** Text safe to print on a terminal (notes, errors): C0 and C1 control characters and bidi overrides escaped. */
99
+ export declare const printable: (s: string) => string;
100
+ /** Text that can sit inside a block or line comment: printable ASCII (no line breaks), no comment terminator. */
101
+ export declare const commentText: (s: string) => string;
102
+ /** Whether `idl` is in the format Anchor wrote before 0.30: `isMut` / `isSigner` accounts, or a name and version at the top and no discriminators. */
103
+ export declare function isLegacyAnchorIdl(idl: unknown): boolean;
104
+ /**
105
+ * Throws ClientIdlError unless `idl` is an Anchor 0.30+ / 1.x or TypeSOL IDL whose values are safe to paste into generated
106
+ * source: identifiers that are identifiers, base58 addresses, byte lists. `typesol client`, `typesol cpi` and `typesol port`
107
+ * all check an IDL this way first. `instructions: "required"` also refuses an IDL without any (nothing to generate).
108
+ */
109
+ export declare function checkIdl(idl: unknown, opts?: {
110
+ address?: string;
111
+ instructions?: "required";
112
+ }): asserts idl is ClientIdl;
98
113
  export declare function generateClient(idl: ClientIdl, opts?: {
99
114
  address?: string;
100
115
  }): ClientGenResult;