@typesol/cli 0.28.0 → 0.30.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 (48) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +2 -2
  3. package/dist/cli.js +13 -20
  4. package/dist/compiler/analyze.d.ts +6 -2
  5. package/dist/compiler/analyze.js +57 -15
  6. package/dist/compiler/diagnostics.d.ts +2 -0
  7. package/dist/compiler/diagnostics.js +3 -2
  8. package/dist/compiler/emit/alias.d.ts +48 -0
  9. package/dist/compiler/emit/alias.js +166 -0
  10. package/dist/compiler/emit/borsh.js +6 -3
  11. package/dist/compiler/emit/calls.js +21 -4
  12. package/dist/compiler/emit/cpi-core.d.ts +70 -0
  13. package/dist/compiler/emit/cpi-core.js +356 -0
  14. package/dist/compiler/emit/cpi.d.ts +3 -177
  15. package/dist/compiler/emit/cpi.js +13 -2721
  16. package/dist/compiler/emit/create.d.ts +39 -0
  17. package/dist/compiler/emit/create.js +548 -0
  18. package/dist/compiler/emit/function.d.ts +11 -2
  19. package/dist/compiler/emit/function.js +42 -7
  20. package/dist/compiler/emit/metaplex.d.ts +78 -0
  21. package/dist/compiler/emit/metaplex.js +1345 -0
  22. package/dist/compiler/emit/program.js +24 -4
  23. package/dist/compiler/emit/shared.d.ts +7 -1
  24. package/dist/compiler/emit/shared.js +11 -2
  25. package/dist/compiler/emit/statements.d.ts +0 -9
  26. package/dist/compiler/emit/statements.js +2 -53
  27. package/dist/compiler/emit/storage.d.ts +5 -20
  28. package/dist/compiler/emit/storage.js +40 -106
  29. package/dist/compiler/emit/token.d.ts +8 -0
  30. package/dist/compiler/emit/token.js +493 -0
  31. package/dist/compiler/index.js +1 -1
  32. package/dist/compiler/model.d.ts +10 -2
  33. package/dist/compiler/model.js +7 -1
  34. package/dist/tools/portgen.js +3 -0
  35. package/dist/workspace.d.ts +1 -1
  36. package/dist/workspace.js +3 -1
  37. package/docs/architecture.md +30 -2
  38. package/docs/audit.md +3 -2
  39. package/docs/case-study-multisig.md +31 -29
  40. package/docs/cli.md +7 -4
  41. package/docs/errors.md +3 -2
  42. package/docs/language.md +4 -3
  43. package/docs/migrate-from-anchor.md +3 -3
  44. package/docs/security-model.md +1 -1
  45. package/lib/typesol.d.ts +17 -6
  46. package/package.json +1 -1
  47. package/runtime/typesol_rt.h +85 -1
  48. package/ts-plugin/index.js +75 -39
package/CHANGELOG.md CHANGED
@@ -6,6 +6,41 @@ codes, and says so here.
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 0.30.0 — 2026-10-30
10
+
11
+ Editor errors that follow you through a program, faster. The compiler's output is the same as 0.29.0 for every
12
+ program.
13
+
14
+ - Changed: `typesol/ts-plugin` shows the compiler's refusals in every file of a program (a helper or state file the
15
+ entry imports, not only the entry), for the unsaved text of every open file, underlining the whole construct.
16
+ - Changed: the plugin runs the compiler inside the editor's TypeScript server once it has loaded (a check takes
17
+ milliseconds instead of starting a process), and `typesol init` writes `.vscode/settings.json` so VS Code offers the
18
+ workspace's TypeScript, which loads the plugin.
19
+ - New: `typesol check --files` reads `{ "files": { "<path>": "<text>" } }` from stdin (unsaved buffers of any file);
20
+ `--json` diagnostics carry a `length`. The compiler's `generate(entry, { files })` takes the same overrides.
21
+
22
+ ## 0.29.0 — 2026-10-30
23
+
24
+ The remaining Anchor gaps: declarative constraints in Anchor's order, Anchor's unbounded `Vec` in Borsh accounts, and
25
+ more than 32 accounts per instruction. Programs that use none of them compile to the same binaries as in 0.28.0.
26
+
27
+ - New: `export const MAX_ACCOUNTS = 128n` (33–255) lets a program's instructions take more than 32 accounts, as Anchor
28
+ programs can. Above 32 the CPI scratch lists live on the heap, grown as needed.
29
+
30
+ - New: `constraint(account, condition, error?)`, Anchor's `constraint = condition @ error`: statements at the start of
31
+ an instruction that run with that account's checks (after its `has_one`), so a transaction breaking several checks
32
+ gets Anchor's code. The default error is ConstraintRaw (2003).
33
+ - New: `Vec<T>` in a `@layout borsh` struct is Anchor's Vec: any field position, held on the heap while the instruction
34
+ runs (growing as Rust's does), bounded only by the account when it is written back (3004). Such a struct can be an
35
+ account or a whole argument (not return data or an event); `Init` of one takes its space. `typesol port` now writes
36
+ `Vec<T>` for Anchor's Vec fields instead of a `FixedVec` to size by hand.
37
+ - Changed: `push(value, payer)`'s payer is optional in the types (the compiler still requires it for a Vec that grows
38
+ the account), so a `Vec` assigns to a `FixedVec` without the earlier type workaround.
39
+ - Changed: examples/multisig.ts uses both; it now matches the mainnet program on 52 transactions, including one that
40
+ breaks two checks at once and an account holding 40 owners.
41
+ - Internal: `cpi.ts` split into `cpi-core`, `create`, `token`, `metaplex` and `cpi`; aliasing rules in `alias.ts`;
42
+ `scripts/codegen-snapshot.ts`; the IR decision in docs/architecture.md.
43
+
9
44
  ## 0.28.0 — 2026-10-29
10
45
 
11
46
  A port of coral-xyz/multisig, checked against the program deployed on mainnet, and the features it needed. The
package/README.md CHANGED
@@ -176,7 +176,7 @@ program's address.
176
176
  Coming from Anchor: [docs/migrate-from-anchor.md](docs/migrate-from-anchor.md) maps every construct, `typesol port`
177
177
  starts from your program's IDL, and [docs/case-study-escrow.md](docs/case-study-escrow.md) follows one complete Anchor
178
178
  program through the port; [docs/case-study-multisig.md](docs/case-study-multisig.md) ports coral-xyz/multisig and
179
- checks it against the binary deployed on mainnet (same outcomes and account bytes; 73–84% fewer compute units). Tests use `typesol/testing` (accounts by name, plain values; [docs/test-your-program.md](docs/test-your-program.md)). To go to
179
+ checks it against the binary deployed on mainnet (same outcomes and account bytes; 66–84% fewer compute units). Tests use `typesol/testing` (accounts by name, plain values; [docs/test-your-program.md](docs/test-your-program.md)). To go to
180
180
  mainnet (wallet, cost, deploy, IDL, verification), follow [docs/mainnet.md](docs/mainnet.md).
181
181
 
182
182
  ## How it works
@@ -225,7 +225,7 @@ The full reference, with every type, check and built-in, is in [docs/language.md
225
225
  | `typesol cpi <idl.json>` | generate typed CPI helpers for another program |
226
226
  | `typesol client <idl.json>` | generate a typed TypeScript client from an Anchor IDL (`typesol build` writes one per program) |
227
227
  | `typesol port` | a TypeSOL skeleton of an Anchor program from its IDL, keeping discriminators and error codes |
228
- | `typesol/ts-plugin` | the compiler's errors in the editor as you type ([docs/cli.md](docs/cli.md#editor)) |
228
+ | `typesol/ts-plugin` | the compiler's errors in the editor as you type, in every file of a program ([docs/cli.md](docs/cli.md#editor)) |
229
229
  | `typesol verify` | rebuild from source and compare with the program and IDL on chain (or a dumped `.so`) |
230
230
  | `typesol profile` | compute units per TypeScript line, from a `--profile` build's logs |
231
231
  | `typesol emit-c` | print the generated C |
package/dist/cli.js CHANGED
@@ -5,7 +5,6 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { parseArgs } from "node:util";
8
- import ts from "typescript";
9
8
  import { build, CompileError, COMPILER_VERSION, generate, SBPF_VERSIONS, verifyBinary } from "./compiler/index.js";
10
9
  import { generateCpi } from "./tools/cpigen.js";
11
10
  import { generatePort } from "./tools/portgen.js";
@@ -44,7 +43,7 @@ const COMMANDS = {
44
43
  init: {
45
44
  usage: "typesol init [<dir>] [--name <program>] [--template counter|vault|escrow]",
46
45
  help: [
47
- "Create a project: typesol.json, programs/<name>.ts, tests/<name>.test.ts (LiteSVM), package.json, tsconfig.json, .gitignore.",
46
+ "Create a project: typesol.json, programs/<name>.ts, tests/<name>.test.ts (LiteSVM), package.json, tsconfig.json, .gitignore, .vscode/settings.json (editor errors).",
48
47
  "Refuses to overwrite files. <name> must be snake_case (default: derived from <dir>).",
49
48
  "--template counter a PDA counter per user (default)",
50
49
  "--template vault a SOL vault at a PDA: deposit, withdraw above rent, close",
@@ -132,20 +131,27 @@ const COMMANDS = {
132
131
  },
133
132
  },
134
133
  check: {
135
- usage: "typesol check <program.ts> [--json] [--stdin]",
134
+ usage: "typesol check <program.ts> [--json] [--stdin | --files]",
136
135
  help: [
137
136
  "Typecheck and validate the TypeSOL subset without building.",
138
137
  "--json print { ok, diagnostics: [{ file, line, column, message }] } (exit 1 when there are diagnostics)",
139
138
  "--stdin read <program.ts>'s text from stdin instead of the file (an editor's unsaved buffer); its imports are read from disk",
139
+ '--files read { "files": { "<absolute path>": "<text>", … } } from stdin: those files\' texts instead of the disk (unsaved buffers)',
140
140
  ].join("\n "),
141
- options: { json: { type: "boolean" }, stdin: { type: "boolean" } },
141
+ options: { json: { type: "boolean" }, stdin: { type: "boolean" }, files: { type: "boolean" } },
142
142
  run(v, args) {
143
143
  const file = path.resolve(one(args, "<program.ts>"));
144
- const restore = v.stdin ? overrideFile(file, readFileSync(0, "utf8")) : undefined;
144
+ let files;
145
+ if (v.stdin)
146
+ files = new Map([[file, readFileSync(0, "utf8")]]);
147
+ else if (v.files) {
148
+ const given = JSON.parse(readFileSync(0, "utf8")).files ?? {};
149
+ files = new Map(Object.entries(given).map(([p, t]) => [path.resolve(p), t]));
150
+ }
145
151
  try {
146
- if (!v.stdin)
152
+ if (!files?.has(file))
147
153
  mustExist(file);
148
- const { model } = generate(file);
154
+ const { model } = generate(file, { files });
149
155
  if (v.json)
150
156
  log(JSON.stringify({ ok: true, diagnostics: [] }));
151
157
  else
@@ -158,9 +164,6 @@ const COMMANDS = {
158
164
  log(JSON.stringify({ ok: false, diagnostics: e.diagnostics }));
159
165
  return 1;
160
166
  }
161
- finally {
162
- restore?.();
163
- }
164
167
  },
165
168
  },
166
169
  "emit-c": {
@@ -517,16 +520,6 @@ function readJson(file) {
517
520
  }
518
521
  }
519
522
  /** Make the compiler read `text` for `file` (instead of the disk) until the returned function is called. */
520
- function overrideFile(file, text) {
521
- const sys = ts.sys;
522
- const { readFile, fileExists } = sys;
523
- sys.readFile = (p, enc) => (path.resolve(p) === file ? text : readFile.call(sys, p, enc));
524
- sys.fileExists = (p) => path.resolve(p) === file || fileExists.call(sys, p);
525
- return () => {
526
- sys.readFile = readFile;
527
- sys.fileExists = fileExists;
528
- };
529
- }
530
523
  /** json_rpc_url / keypair_path from a Solana CLI config (the given file, or the CLI's default one). */
531
524
  function solanaConfig(file) {
532
525
  const cfg = readSolanaConfig(file);
@@ -1,6 +1,6 @@
1
1
  import ts from "typescript";
2
2
  import { Reporter } from "./diagnostics.js";
3
- import { type DataEnumDef, type EnumDef, type GenericHelper, type Helper, type ProgramModel, type ScalarType, type StructDef, type ValueType, isScalar } from "./model.js";
3
+ import { type DataEnumDef, type EnumDef, type GenericHelper, type Helper, type ProgramModel, type ScalarType, type StructDef, type StructField, type ValueType, isScalar } from "./model.js";
4
4
  export declare const LIB_PATH: string;
5
5
  /** A struct used as account data: none of its fields may shadow an account member. */
6
6
  export declare function checkAccountMembers(s: StructDef, at: ts.Node, reporter: Reporter): void;
@@ -47,9 +47,11 @@ export interface TypeScope {
47
47
  }
48
48
  export declare function snakeCase(name: string): string;
49
49
  export declare function discriminator(preimage: string): number[];
50
+ /** Source text by absolute path: an editor's unsaved buffers, read instead of the files on disk. */
51
+ export type SourceOverrides = ReadonlyMap<string, string>;
50
52
  /** Resolve a relative import to a `.ts` file next to `from`, or undefined. */
51
53
  export declare function resolveRelative(from: string, spec: string): string | undefined;
52
- export declare function analyze(entry: string): Analysis;
54
+ export declare function analyze(entry: string, files?: SourceOverrides): Analysis;
53
55
  /**
54
56
  * Instruction-argument types beyond scalars: a fixed-size struct (`p: Point`), `FixedArray<T, N>`, or
55
57
  * `Vec<Struct>`. They are Borsh-identical to TypeSOL's fixed layouts, so they are copied as is and validated.
@@ -64,6 +66,8 @@ export declare function resolveOptionType(node: ts.TypeNode, scope: TypeScope):
64
66
  }) | undefined;
65
67
  /** Values a local, argument or helper parameter can hold. */
66
68
  export declare function resolveValueType(node: ts.TypeNode, scope: TypeScope, allowVec?: boolean): ValueType | undefined;
69
+ /** The first heap Vec<T> field of a struct (a Vec in a `@layout borsh` struct), if it has one. */
70
+ export declare function heapVecOf(s: StructDef): StructField | undefined;
67
71
  /** The helper (or generic) a call's callee names: a local function by its declaration, others by name. */
68
72
  export declare function calleeName(callee: ts.Identifier, decls: Map<ts.Node, string>, checker: ts.TypeChecker): string | undefined;
69
73
  export { isScalar };
@@ -145,7 +145,12 @@ export function discriminator(preimage) {
145
145
  return [...createHash("sha256").update(preimage).digest().subarray(0, 8)];
146
146
  }
147
147
  /** Run the TypeScript checker over the entry file with `typesol` mapped to our declarations. */
148
- function typecheck(entry) {
148
+ /**
149
+ * Library declarations (TypeScript's lib files, typesol.d.ts) parsed once per process: an editor checks the same
150
+ * program on every keystroke, and these never change.
151
+ */
152
+ const libSourceFiles = new Map();
153
+ function typecheck(entry, files) {
149
154
  const options = {
150
155
  strict: true,
151
156
  noEmit: true,
@@ -157,7 +162,30 @@ function typecheck(entry) {
157
162
  paths: { typesol: [LIB_PATH] },
158
163
  skipLibCheck: true,
159
164
  };
160
- const program = ts.createProgram([entry], options);
165
+ const host = ts.createCompilerHost(options);
166
+ const getSourceFile = host.getSourceFile.bind(host);
167
+ host.getSourceFile = (fileName, language, onError, shouldCreate) => {
168
+ const text = files?.get(path.resolve(fileName));
169
+ if (text !== undefined)
170
+ return ts.createSourceFile(fileName, text, language, true);
171
+ const lib = fileName.endsWith(".d.ts") && (path.resolve(fileName) === LIB_PATH || fileName.includes(`${path.sep}typescript${path.sep}lib${path.sep}`));
172
+ if (!lib)
173
+ return getSourceFile(fileName, language, onError, shouldCreate);
174
+ let sf = libSourceFiles.get(fileName);
175
+ if (!sf) {
176
+ sf = getSourceFile(fileName, language, onError, shouldCreate);
177
+ if (sf)
178
+ libSourceFiles.set(fileName, sf);
179
+ }
180
+ return sf;
181
+ };
182
+ if (files) {
183
+ const readFile = host.readFile.bind(host);
184
+ const fileExists = host.fileExists.bind(host);
185
+ host.readFile = (f) => files.get(path.resolve(f)) ?? readFile(f);
186
+ host.fileExists = (f) => files.has(path.resolve(f)) || fileExists(f);
187
+ }
188
+ const program = ts.createProgram([entry], options, host);
161
189
  const sourceFile = program.getSourceFile(entry);
162
190
  if (!sourceFile)
163
191
  throw new CompileError([{ file: entry, line: 1, column: 1, message: "cannot read source file" }]);
@@ -170,7 +198,7 @@ function typecheck(entry) {
170
198
  if (!d.file || d.start === undefined)
171
199
  return { file: entry, line: 1, column: 1, message };
172
200
  const { line, character } = d.file.getLineAndCharacterOfPosition(d.start);
173
- return { file: d.file.fileName, line: line + 1, column: character + 1, message };
201
+ return { file: d.file.fileName, line: line + 1, column: character + 1, message, length: d.length };
174
202
  });
175
203
  throw new CompileError(diagnostics);
176
204
  }
@@ -190,14 +218,14 @@ export function resolveRelative(from, spec) {
190
218
  * Reject foreign imports before typechecking so the user sees why, not "cannot find module".
191
219
  * Follows relative imports so every file of the program is checked.
192
220
  */
193
- function checkImports(entry) {
221
+ function checkImports(entry, files) {
194
222
  const reporter = new Reporter();
195
223
  const seen = new Set();
196
224
  const visit = (file) => {
197
225
  if (seen.has(file))
198
226
  return;
199
227
  seen.add(file);
200
- const text = ts.sys.readFile(file);
228
+ const text = files?.get(file) ?? ts.sys.readFile(file);
201
229
  if (text === undefined)
202
230
  throw new CompileError([{ file, line: 1, column: 1, message: "cannot read source file" }]);
203
231
  const sf = ts.createSourceFile(file, text, ts.ScriptTarget.ES2022, true);
@@ -241,10 +269,10 @@ function programFiles(program, entry) {
241
269
  visit(entry);
242
270
  return order;
243
271
  }
244
- export function analyze(entry) {
272
+ export function analyze(entry, files) {
245
273
  const entryPath = path.resolve(entry);
246
- checkImports(entryPath);
247
- const { program, sourceFile } = typecheck(entryPath);
274
+ checkImports(entryPath, files);
275
+ const { program, sourceFile } = typecheck(entryPath, files);
248
276
  const reporter = new Reporter();
249
277
  const errorEnums = new Map();
250
278
  const enums = new Map();
@@ -621,10 +649,13 @@ export function analyze(entry) {
621
649
  collectStructs(a.type, structs, dataEnums, seen);
622
650
  // A @layout borsh struct is decoded as a whole argument; inside lists or enums it would need a fixed size.
623
651
  const whole = a.type.kind === "structRef" ? a.type.struct : undefined;
624
- for (const s of seen)
652
+ for (const s of seen) {
625
653
  if (structs.get(s).layout === "borsh" && s !== whole)
626
654
  reporter.error(fn.node.name ?? fn.node, `argument ${a.name}: ${s} is @layout borsh; pass it as a whole argument, not inside a list or enum`);
655
+ }
627
656
  }
657
+ if (ix.returns?.kind === "struct" && heapVecOf(structs.get(ix.returns.name)))
658
+ reporter.error(fn.node.name ?? fn.node, `${ix.returns.name} holds a Vec<T>; return data takes a struct with FixedVec<T, N> instead`);
628
659
  // A returned struct goes out in its fixed layout, like an argument comes in: it cannot also be a Borsh event.
629
660
  if (ix.returns?.kind === "struct")
630
661
  collectStructs(ix.returns, structs, dataEnums, argStructs);
@@ -984,11 +1015,12 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
984
1015
  if (layoutTag && layoutText !== "borsh" && layoutText !== "fixed")
985
1016
  reporter.fail(layoutTag, "@layout is borsh (Anchor's account bytes) or fixed (the default)");
986
1017
  const growable = (f) => f.type.kind === "vec" && f.type.cap === undefined;
987
- // Anchor's bytes keep the declared order, so there a growable Vec has to be last (the fields after it would move).
1018
+ // In a @layout borsh struct a Vec<T> is Anchor's: held on the heap while an instruction runs, any field, bounded
1019
+ // only by the account when it is written back.
988
1020
  if (layoutText === "borsh")
989
- for (const f of fields.slice(0, -1))
1021
+ for (const f of fields)
990
1022
  if (growable(f))
991
- reporter.fail(f.node ?? decl, "in a @layout borsh struct a Vec<T> field must be the last field (Anchor's bytes keep the declared order); use FixedVec<T, N> for a list of at most N elsewhere");
1023
+ f.type = { ...f.type, heap: true };
992
1024
  // The fixed layout stores the growable Vecs after the fixed-size fields, in the order declared, so every other
993
1025
  // field keeps a fixed offset; the IDL lists the fields in this stored order.
994
1026
  const stored = layoutText === "borsh" ? fields : [...fields.filter((f) => !growable(f)), ...fields.filter(growable)];
@@ -1098,6 +1130,8 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1098
1130
  return 1 + e.payload;
1099
1131
  }
1100
1132
  case "vec": {
1133
+ if (t.heap)
1134
+ return 16; // TSH_*: u32 length, u32 capacity, a pointer to the elements on the heap
1101
1135
  if (t.cap === undefined)
1102
1136
  return 4; // the u32 length; elements live past the fixed part
1103
1137
  const e = sizeOf(t.elem, at);
@@ -1149,7 +1183,7 @@ function analyzeStructs(items, aliases, dataEnums, reporter, scopeFor, fstrings,
1149
1183
  // Growable Vecs (stored last, see above): the first one's length and elements end the C struct; the others follow
1150
1184
  // it in the account, each a u32 length and its elements.
1151
1185
  for (const f of s.fields)
1152
- if (f.type.kind === "vec" && f.type.cap === undefined) {
1186
+ if (f.type.kind === "vec" && f.type.cap === undefined && !f.type.heap) {
1153
1187
  const elemSize = sizeOf(f.type.elem, s.node);
1154
1188
  if (elemSize === undefined)
1155
1189
  reporter.fail(s.node, "Vec elements must have a fixed size");
@@ -1269,6 +1303,10 @@ function references(l, decls, checker) {
1269
1303
  visit(l.node.body);
1270
1304
  return found;
1271
1305
  }
1306
+ /** The first heap Vec<T> field of a struct (a Vec in a `@layout borsh` struct), if it has one. */
1307
+ export function heapVecOf(s) {
1308
+ return s.fields.find((f) => f.type.kind === "vec" && f.type.heap);
1309
+ }
1272
1310
  /**
1273
1311
  * A `@layout borsh` struct: its own fields may be FixedString (Borsh String), FixedVec (Borsh Vec) and Option; anything
1274
1312
  * nested must already be Borsh-identical (fixed-size scalars, Pubkeys, enums, arrays and structs of them).
@@ -1289,8 +1327,12 @@ function checkBorshLayout(s, structs, dataEnums, reporter) {
1289
1327
  reporter.fail(at, `${t.name}.${v.name}.${vf.name} in a @layout borsh struct: enum variants hold fixed-size values and strings`);
1290
1328
  continue;
1291
1329
  }
1292
- if (t.kind === "vec" && t.cap === undefined)
1293
- reporter.fail(at, "a @layout borsh struct cannot end in a growable Vec<T>; use FixedVec<T, N> (Anchor's #[max_len(N)] Vec)");
1330
+ if (t.kind === "vec" && t.heap) {
1331
+ const e = t.elem;
1332
+ if (!fixed(e) || e.kind === "array")
1333
+ reporter.fail(at, `${typeName(t)} in a @layout borsh struct: its elements are integers, booleans, Pubkeys, unit enums or fixed-size structs`);
1334
+ continue;
1335
+ }
1294
1336
  if (t.kind === "vec" && (fixed(t.elem) || t.elem.kind === "fstring"))
1295
1337
  continue;
1296
1338
  if (t.kind === "option" && fixed(t.inner))
@@ -4,6 +4,8 @@ export interface Diagnostic {
4
4
  line: number;
5
5
  column: number;
6
6
  message: string;
7
+ /** Characters the problem spans from line:column (the construct refused), when known. */
8
+ length?: number;
7
9
  }
8
10
  export declare class CompileError extends Error {
9
11
  readonly diagnostics: Diagnostic[];
@@ -11,8 +11,9 @@ export function formatDiagnostic(d) {
11
11
  }
12
12
  export function diagnosticAt(node, message) {
13
13
  const sf = node.getSourceFile();
14
- const { line, character } = sf.getLineAndCharacterOfPosition(node.getStart(sf));
15
- return { file: sf.fileName, line: line + 1, column: character + 1, message };
14
+ const start = node.getStart(sf);
15
+ const { line, character } = sf.getLineAndCharacterOfPosition(start);
16
+ return { file: sf.fileName, line: line + 1, column: character + 1, message, length: Math.max(1, node.getEnd() - start) };
16
17
  }
17
18
  /** Collects diagnostics; `fail` records one and throws to unwind the current construct. */
18
19
  export class Reporter {
@@ -0,0 +1,48 @@
1
+ import ts from "typescript";
2
+ import { type FieldType } from "../model.js";
3
+ import { EmitterBase } from "./base.js";
4
+ /**
5
+ * Aliasing, in one place. A struct read from account data is a reference into that data, not a copy, so code that
6
+ * replaces or moves the data under a reference still in use would let it read a value JS would not show. The rules:
7
+ *
8
+ * - `pathsOf` names the storage an expression refers to (`acct.a.b`, `v[]` for a Vec element, a reference local's
9
+ * paths); every reference local records its paths when it is declared (statements.ts).
10
+ * - `assertNotAliased(paths, at)` refuses replacing a place while a reference into it is read later (`usedAfter`).
11
+ * Called for: assigning a struct or list (statements.ts `assign`); `set` of a struct element of an array or Vec,
12
+ * `pop` and `clear` (calls.ts); any push / pop / clear that moves the growable Vecs stored after the one it resizes
13
+ * (calls.ts `tailStart`); a helper taking a writable struct account (calls.ts); `acct.migrate(…)` (calls.ts).
14
+ * - `mayResizeVecs(node)` decides whether evaluating a value may resize a growable Vec (moving the Vecs after it); an
15
+ * assignment whose target is reached through a Vec element (`writesThroughVec`) is then refused (statements.ts).
16
+ *
17
+ * Accounts passed twice are a separate rule: function.ts refuses two writable parameters naming one account (2040)
18
+ * unless `Dup<…>` allows it for in-place accounts.
19
+ */
20
+ export declare abstract class AliasEmitter extends EmitterBase {
21
+ protected abstract peekKind(node: ts.Expression): FieldType["kind"] | undefined;
22
+ /**
23
+ * Storage paths an expression names, syntactically: `acct.a.b` -> ["acct.a.b"], `v.get(i)` -> ["v[]"],
24
+ * a reference local -> the paths it aliases, a ternary -> both sides. Undefined when unknown.
25
+ */
26
+ protected pathsOf(node: ts.Expression): string[] | undefined;
27
+ /**
28
+ * In JS, replacing an object (`acct.pos = {...}`, `v.set(i, {...})`, `v.pop()`) leaves earlier references
29
+ * to the old object unchanged. Here a reference is a pointer into account data, so it would see the new
30
+ * value. Refuse when a live reference into the replaced place is still used afterwards.
31
+ */
32
+ protected assertNotAliased(replaced: string[] | undefined, at: ts.Node, helper?: string): void;
33
+ /**
34
+ * Whether the variable declared by `decl` is read after `at` (later in its block, or anywhere in a loop around `at`).
35
+ * A parameter (of a closure or helper expanded here) is read after `at` when its function reads it after `at`; when
36
+ * `at` is in another function (a closure or helper it calls), any read of it in its own function counts.
37
+ */
38
+ protected usedAfter(decl: ts.VariableDeclaration | ts.ParameterDeclaration, at: ts.Node): boolean;
39
+ /** Whether a place goes through a Vec element (`v.get(i).x`, `v.get(i)`). */
40
+ protected writesThroughVec(node: ts.Expression): boolean;
41
+ protected helperTakesMutAccounts(node: ts.CallExpression): boolean;
42
+ /**
43
+ * Whether evaluating `node` may resize a growable Vec (and so move the Vecs after it): a push / pop / clear, a
44
+ * realloc or close, a helper taking a writable account or a function argument, or a closure (its body is not
45
+ * looked into: it may capture the account). Conservative: it only decides whether a Vec element may be the target.
46
+ */
47
+ protected mayResizeVecs(node: ts.Node): boolean;
48
+ }
@@ -0,0 +1,166 @@
1
+ import ts from "typescript";
2
+ import { isWritable } from "../model.js";
3
+ import { EmitterBase } from "./base.js";
4
+ /**
5
+ * Aliasing, in one place. A struct read from account data is a reference into that data, not a copy, so code that
6
+ * replaces or moves the data under a reference still in use would let it read a value JS would not show. The rules:
7
+ *
8
+ * - `pathsOf` names the storage an expression refers to (`acct.a.b`, `v[]` for a Vec element, a reference local's
9
+ * paths); every reference local records its paths when it is declared (statements.ts).
10
+ * - `assertNotAliased(paths, at)` refuses replacing a place while a reference into it is read later (`usedAfter`).
11
+ * Called for: assigning a struct or list (statements.ts `assign`); `set` of a struct element of an array or Vec,
12
+ * `pop` and `clear` (calls.ts); any push / pop / clear that moves the growable Vecs stored after the one it resizes
13
+ * (calls.ts `tailStart`); a helper taking a writable struct account (calls.ts); `acct.migrate(…)` (calls.ts).
14
+ * - `mayResizeVecs(node)` decides whether evaluating a value may resize a growable Vec (moving the Vecs after it); an
15
+ * assignment whose target is reached through a Vec element (`writesThroughVec`) is then refused (statements.ts).
16
+ *
17
+ * Accounts passed twice are a separate rule: function.ts refuses two writable parameters naming one account (2040)
18
+ * unless `Dup<…>` allows it for in-place accounts.
19
+ */
20
+ export class AliasEmitter extends EmitterBase {
21
+ /**
22
+ * Storage paths an expression names, syntactically: `acct.a.b` -> ["acct.a.b"], `v.get(i)` -> ["v[]"],
23
+ * a reference local -> the paths it aliases, a ternary -> both sides. Undefined when unknown.
24
+ */
25
+ pathsOf(node) {
26
+ if (ts.isParenthesizedExpression(node))
27
+ return this.pathsOf(node.expression);
28
+ if (ts.isIdentifier(node)) {
29
+ const l = this.lookup(node.text);
30
+ if (l)
31
+ return l.paths ?? (l.type.kind === "array" ? [`@${l.c}`] : undefined);
32
+ return this.accounts.has(node.text) ? [node.text] : undefined;
33
+ }
34
+ if (ts.isPropertyAccessExpression(node))
35
+ return this.pathsOf(node.expression)?.map((p) => `${p}.${node.name.text}`);
36
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "get")
37
+ return this.pathsOf(node.expression.expression)?.map((p) => `${p}[]`);
38
+ if (ts.isConditionalExpression(node)) {
39
+ const a = this.pathsOf(node.whenTrue);
40
+ const b = this.pathsOf(node.whenFalse);
41
+ return a && b ? [...a, ...b] : undefined;
42
+ }
43
+ return undefined;
44
+ }
45
+ /**
46
+ * In JS, replacing an object (`acct.pos = {...}`, `v.set(i, {...})`, `v.pop()`) leaves earlier references
47
+ * to the old object unchanged. Here a reference is a pointer into account data, so it would see the new
48
+ * value. Refuse when a live reference into the replaced place is still used afterwards.
49
+ */
50
+ assertNotAliased(replaced, at, helper) {
51
+ if (!replaced)
52
+ return;
53
+ for (const scope of this.scopes)
54
+ for (const [name, l] of scope) {
55
+ if (!l.paths || !l.decl)
56
+ continue;
57
+ const hit = replaced.find((r) => l.paths.some((p) => p === r || p.startsWith(`${r}.`) || p.startsWith(`${r}[]`)));
58
+ if (!hit || !this.usedAfter(l.decl, at))
59
+ continue;
60
+ this.fail(at, helper
61
+ ? `"${name}" still refers to data in ${hit}, and ${helper}() may replace it (then "${name}" would read the new value; in JS it keeps the old one). Copy the fields you need into locals first`
62
+ : `"${name}" still refers to ${hit}; replacing it here would change what "${name}" reads (in JS it keeps the old value). Copy the fields you need into locals first`);
63
+ }
64
+ }
65
+ /**
66
+ * Whether the variable declared by `decl` is read after `at` (later in its block, or anywhere in a loop around `at`).
67
+ * A parameter (of a closure or helper expanded here) is read after `at` when its function reads it after `at`; when
68
+ * `at` is in another function (a closure or helper it calls), any read of it in its own function counts.
69
+ */
70
+ usedAfter(decl, at) {
71
+ const symbol = this.checker.getSymbolAtLocation(decl.name);
72
+ if (!symbol)
73
+ return true;
74
+ if (ts.isParameter(decl)) {
75
+ const fn = decl.parent;
76
+ const inside = at.getSourceFile() === fn.getSourceFile() && at.pos >= fn.pos && at.end <= fn.end;
77
+ let read = false;
78
+ const visitParam = (n) => {
79
+ if (read)
80
+ return;
81
+ if (ts.isIdentifier(n) && n !== decl.name && this.checker.getSymbolAtLocation(n) === symbol) {
82
+ if (!inside || n.pos >= at.end)
83
+ read = true;
84
+ // A loop inside the function, around `at`, reads it again on its next turn.
85
+ for (let p = at.parent; inside && p && p !== fn; p = p.parent)
86
+ if ((ts.isForStatement(p) || ts.isForOfStatement(p) || ts.isWhileStatement(p) || ts.isDoStatement(p)) && n.pos >= p.pos && n.end <= p.end)
87
+ read = true;
88
+ }
89
+ ts.forEachChild(n, visitParam);
90
+ };
91
+ const body = fn.body;
92
+ if (body)
93
+ visitParam(body);
94
+ return read;
95
+ }
96
+ // Loops around `at` that do not also contain the declaration run their earlier statements again later.
97
+ let loop;
98
+ for (let n = at.parent; n && n !== decl.parent; n = n.parent)
99
+ if ((ts.isForStatement(n) || ts.isForOfStatement(n) || ts.isWhileStatement(n) || ts.isDoStatement(n)) && !(decl.pos >= n.pos && decl.end <= n.end))
100
+ loop = n;
101
+ let found = false;
102
+ const scope = decl.parent.parent.parent; // VariableDeclaration -> List -> Statement -> enclosing block
103
+ const visit = (n) => {
104
+ if (found)
105
+ return;
106
+ if (ts.isIdentifier(n) && n !== decl.name && this.checker.getSymbolAtLocation(n) === symbol) {
107
+ if (n.pos >= at.end || (loop && n.pos >= loop.pos && n.end <= loop.end))
108
+ found = true;
109
+ }
110
+ ts.forEachChild(n, visit);
111
+ };
112
+ visit(scope);
113
+ return found;
114
+ }
115
+ /** Whether a place goes through a Vec element (`v.get(i).x`, `v.get(i)`). */
116
+ writesThroughVec(node) {
117
+ for (let n = node;;) {
118
+ if (ts.isParenthesizedExpression(n))
119
+ n = n.expression;
120
+ else if (ts.isPropertyAccessExpression(n))
121
+ n = n.expression;
122
+ else if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression) && n.expression.name.text === "get") {
123
+ if (this.peekKind(n.expression.expression) === "vec")
124
+ return true;
125
+ n = n.expression.expression;
126
+ }
127
+ else
128
+ return false;
129
+ }
130
+ }
131
+ helperTakesMutAccounts(node) {
132
+ const h = this.helperOf(node);
133
+ return !!h?.params.some((p) => p.account && isWritable(p.account));
134
+ }
135
+ /**
136
+ * Whether evaluating `node` may resize a growable Vec (and so move the Vecs after it): a push / pop / clear, a
137
+ * realloc or close, a helper taking a writable account or a function argument, or a closure (its body is not
138
+ * looked into: it may capture the account). Conservative: it only decides whether a Vec element may be the target.
139
+ */
140
+ mayResizeVecs(node) {
141
+ let found = false;
142
+ const isClosure = (e) => ts.isArrowFunction(e) || ts.isFunctionExpression(e) || (ts.isIdentifier(e) && !!this.lookup(e.text)?.closure);
143
+ const visit = (n) => {
144
+ if (found)
145
+ return;
146
+ if (ts.isCallExpression(n)) {
147
+ const callee = n.expression;
148
+ if (ts.isPropertyAccessExpression(callee) && ["push", "pop", "clear"].includes(callee.name.text))
149
+ found = true;
150
+ else if (ts.isCallExpression(callee))
151
+ found = true; // a function a function returns
152
+ else if (ts.isIdentifier(callee)) {
153
+ if (this.lookup(callee.text)?.closure)
154
+ found = true;
155
+ else if (["realloc", "close"].includes(this.exportName(callee) ?? ""))
156
+ found = true;
157
+ else if (this.helperOf(n) && (this.helperTakesMutAccounts(n) || n.arguments.some(isClosure)))
158
+ found = true;
159
+ }
160
+ }
161
+ ts.forEachChild(n, visit);
162
+ };
163
+ visit(node);
164
+ return found;
165
+ }
166
+ }
@@ -106,10 +106,13 @@ export function emitBorshCodecs(model) {
106
106
  }
107
107
  case "vec": {
108
108
  const l = tmp("n");
109
+ // A heap Vec (Anchor's Vec<T>) gets room on the heap for what the bytes hold; a FixedVec has its capacity.
109
110
  const head = [
110
111
  `${pad}uint32_t ${l} = (uint32_t)ts_read_le(src + at, 4);`,
111
112
  `${pad}at += 4;`,
112
- `${pad}if (${l} > ${t.cap}) ${DESER};`,
113
+ ...(t.heap
114
+ ? [need(`(uint64_t)${l} * ${fixedBytes(t.elem, model)}`, rest, pad), `${pad}TS_TRY(ts_hvec_reserve(&${lv}, ${l}, ${fixedBytes(t.elem, model)}));`]
115
+ : [`${pad}if (${l} > ${t.cap}) ${DESER};`]),
113
116
  `${pad}${lv}.len = ${l};`,
114
117
  ];
115
118
  if (borshIdentical(t.elem, model)) {
@@ -207,7 +210,7 @@ export function emitBorshCodecs(model) {
207
210
  if (borshIdentical(t.elem, model)) {
208
211
  const n = fixedBytes(t.elem, model);
209
212
  return [
210
- `${pad}uint32_t ${l} = ${lv}.len > ${t.cap} ? ${t.cap} : ${lv}.len;`,
213
+ `${pad}uint32_t ${l} = ${t.heap ? `${lv}.len` : `${lv}.len > ${t.cap} ? ${t.cap} : ${lv}.len`};`,
211
214
  room(`4 + (uint64_t)${l} * ${n}`, rest, pad),
212
215
  `${pad}ts_write_le(dst + at, ${l}, 4);`,
213
216
  `${pad}ts_memcpy(dst + at + 4, ${lv}.items, (uint64_t)${l} * ${n});`,
@@ -216,7 +219,7 @@ export function emitBorshCodecs(model) {
216
219
  }
217
220
  const i = tmp("i");
218
221
  return [
219
- `${pad}uint32_t ${l} = ${lv}.len > ${t.cap} ? ${t.cap} : ${lv}.len;`,
222
+ `${pad}uint32_t ${l} = ${t.heap ? `${lv}.len` : `${lv}.len > ${t.cap} ? ${t.cap} : ${lv}.len`};`,
220
223
  room("4", rest, pad),
221
224
  `${pad}ts_write_le(dst + at, ${l}, 4);`,
222
225
  `${pad}at += 4;`,