@typesol/cli 0.41.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +319 -0
  2. package/README.md +11 -7
  3. package/dist/compiler/analyze.js +484 -13
  4. package/dist/compiler/diagnostics.d.ts +1 -0
  5. package/dist/compiler/diagnostics.js +13 -0
  6. package/dist/compiler/emit/alias.d.ts +44 -0
  7. package/dist/compiler/emit/alias.js +135 -4
  8. package/dist/compiler/emit/base.d.ts +65 -7
  9. package/dist/compiler/emit/base.js +91 -7
  10. package/dist/compiler/emit/borsh.d.ts +7 -0
  11. package/dist/compiler/emit/borsh.js +86 -1
  12. package/dist/compiler/emit/calls.d.ts +169 -2
  13. package/dist/compiler/emit/calls.js +1170 -81
  14. package/dist/compiler/emit/cpi-core.d.ts +28 -5
  15. package/dist/compiler/emit/cpi-core.js +238 -12
  16. package/dist/compiler/emit/cpi.js +16 -16
  17. package/dist/compiler/emit/create.d.ts +3 -3
  18. package/dist/compiler/emit/create.js +33 -25
  19. package/dist/compiler/emit/expressions.js +89 -9
  20. package/dist/compiler/emit/function.js +2 -2
  21. package/dist/compiler/emit/outline.d.ts +24 -0
  22. package/dist/compiler/emit/outline.js +100 -0
  23. package/dist/compiler/emit/program.js +37 -3
  24. package/dist/compiler/emit/rbtree.d.ts +7 -0
  25. package/dist/compiler/emit/rbtree.js +142 -0
  26. package/dist/compiler/emit/shared.d.ts +43 -1
  27. package/dist/compiler/emit/shared.js +18 -2
  28. package/dist/compiler/emit/statements.d.ts +58 -1
  29. package/dist/compiler/emit/statements.js +549 -22
  30. package/dist/compiler/emit/storage.d.ts +48 -1
  31. package/dist/compiler/emit/storage.js +220 -63
  32. package/dist/compiler/emit/token.d.ts +11 -8
  33. package/dist/compiler/emit/token.js +233 -104
  34. package/dist/compiler/emit/views.d.ts +60 -0
  35. package/dist/compiler/emit/views.js +523 -0
  36. package/dist/compiler/hints.js +6 -0
  37. package/dist/compiler/idl.js +2 -1
  38. package/dist/compiler/model.d.ts +84 -4
  39. package/dist/compiler/model.js +19 -0
  40. package/dist/compiler/toolchain.d.ts +15 -0
  41. package/dist/compiler/toolchain.js +146 -11
  42. package/dist/testing-stake.d.ts +216 -0
  43. package/dist/testing-stake.js +526 -0
  44. package/dist/testing.d.ts +1 -0
  45. package/dist/testing.js +1 -0
  46. package/docs/architecture.md +9 -2
  47. package/docs/case-study-phoenix.md +226 -0
  48. package/docs/case-study-spl-stake-pool.md +122 -0
  49. package/docs/errors.md +1 -1
  50. package/docs/language.md +244 -20
  51. package/docs/migrate-from-anchor.md +1 -0
  52. package/docs/runtime.md +1 -1
  53. package/docs/security-model.md +4 -0
  54. package/docs/stability.md +33 -1
  55. package/docs/test-your-program.md +47 -0
  56. package/docs/testing.md +19 -0
  57. package/docs/troubleshooting.md +5 -2
  58. package/lib/typesol.d.ts +462 -44
  59. package/llms-full.txt +338 -26
  60. package/llms.txt +1 -1
  61. package/package.json +2 -2
  62. package/runtime/typesol_rt.h +476 -0
@@ -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);
@@ -18,6 +18,15 @@ import { EmitterBase } from "./base.js";
18
18
  * unless `Dup<…>` allows it for in-place accounts.
19
19
  */
20
20
  export declare abstract class AliasEmitter extends EmitterBase {
21
+ /**
22
+ * The trees a `for … of` is walking, by C name, with the account each views: no tree view that may be the same tree
23
+ * (the same local, or another view of an account that may be the walked one's) may change its structure in the
24
+ * loop (Rust's borrow).
25
+ */
26
+ protected iteratingTrees: Map<string, {
27
+ name: string;
28
+ acct: string;
29
+ }>;
21
30
  protected abstract peekKind(node: ts.Expression): FieldType["kind"] | undefined;
22
31
  /**
23
32
  * Storage paths an expression names, syntactically: `acct.a.b` -> ["acct.a.b"], `v.get(i)` -> ["v[]"],
@@ -36,6 +45,41 @@ export declare abstract class AliasEmitter extends EmitterBase {
36
45
  * `at` is in another function (a closure or helper it calls), any read of it in its own function counts.
37
46
  */
38
47
  protected usedAfter(decl: ts.VariableDeclaration | ts.ParameterDeclaration, at: ts.Node): boolean;
48
+ /**
49
+ * A helper given a place to change (`Inout<T>`) may replace what is stored inside it (`rec.inner = { … }`,
50
+ * `rec.items.pop()`), so a reference into it that is read after the call would read the new value where JS keeps the
51
+ * old object. References to the place itself (or to what holds it) see the same object as JS does, so only those
52
+ * strictly inside it are refused.
53
+ */
54
+ protected assertNothingInside(place: string[], at: ts.Node, helper: string, arg: string): void;
55
+ /**
56
+ * The account a native view's first argument names, as `viewAcct` records it: a declared parameter's name, or "?"
57
+ * when it is not one (a remaining account, a choice between accounts).
58
+ */
59
+ protected viewAccountKey(node: ts.Expression): string;
60
+ /**
61
+ * Whether two accounts `viewAccountKey` named may be one account at run time: the same name, one not a declared
62
+ * parameter, or two parameters the runtime does not keep apart (a helper's, any two under NATIVE_ACCOUNT_WRITES, a
63
+ * read-only or Dup one; function.ts refuses two writable parameters naming one account otherwise).
64
+ */
65
+ protected mayBeSameAccount(a: string, b: string): boolean;
66
+ /**
67
+ * `closeRaw(acct, …)` / `resizeAccount(acct, n)` (or a helper that may do either, `target` "?"): a view checks its
68
+ * bounds once, when it is made, so a view of the account made before (and anything read through it) would reach past
69
+ * the account's new end afterwards. Refused when it is used later; the fix is to take the view again.
70
+ */
71
+ protected assertNoViewAfter(target: string, at: ts.Node, what: string): void;
72
+ /** A storage path as the source names it: `@<C local>.x` becomes `<its name>.x` (`@p_rec.items[]` → `rec.items[]`). */
73
+ protected showPath(path: string): string;
74
+ /** Whether two places share storage: the same path, or one inside the other. */
75
+ protected placesOverlap(a: string[], b: string[]): boolean;
76
+ /**
77
+ * Whether a place is reached through an element of a list whose elements can move: a growable Vec of an account (a
78
+ * push or pop of it, or of a Vec stored before it, moves them), a heap Vec (`@layout borsh`) or a BigVec (`retain`
79
+ * shifts them). FixedVec and FixedArray elements stay where they are.
80
+ */
81
+ protected throughMovableList(node: ts.Expression): boolean;
82
+ protected abstract peekType(node: ts.Expression): FieldType | undefined;
39
83
  /** Whether a place goes through a Vec element (`v.get(i).x`, `v.get(i)`). */
40
84
  protected writesThroughVec(node: ts.Expression): boolean;
41
85
  protected helperTakesMutAccounts(node: ts.CallExpression): boolean;
@@ -1,6 +1,8 @@
1
1
  import ts from "typescript";
2
2
  import { isWritable } from "../model.js";
3
3
  import { EmitterBase } from "./base.js";
4
+ /** A tree's methods other than get that return a node of it. */
5
+ const TREE_NODE_METHODS = new Set(["min", "max", "nodeAt", "remove", "removeAt"]);
4
6
  /**
5
7
  * Aliasing, in one place. A struct read from account data is a reference into that data, not a copy, so code that
6
8
  * replaces or moves the data under a reference still in use would let it read a value JS would not show. The rules:
@@ -18,17 +20,23 @@ import { EmitterBase } from "./base.js";
18
20
  * unless `Dup<…>` allows it for in-place accounts.
19
21
  */
20
22
  export class AliasEmitter extends EmitterBase {
23
+ /**
24
+ * The trees a `for … of` is walking, by C name, with the account each views: no tree view that may be the same tree
25
+ * (the same local, or another view of an account that may be the walked one's) may change its structure in the
26
+ * loop (Rust's borrow).
27
+ */
28
+ iteratingTrees = new Map();
21
29
  /**
22
30
  * Storage paths an expression names, syntactically: `acct.a.b` -> ["acct.a.b"], `v.get(i)` -> ["v[]"],
23
31
  * a reference local -> the paths it aliases, a ternary -> both sides. Undefined when unknown.
24
32
  */
25
33
  pathsOf(node) {
26
- if (ts.isParenthesizedExpression(node))
34
+ if (ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node))
27
35
  return this.pathsOf(node.expression);
28
36
  if (ts.isIdentifier(node)) {
29
37
  const l = this.lookup(node.text);
30
38
  if (l)
31
- return l.paths ?? (l.type.kind === "array" ? [`@${l.c}`] : undefined);
39
+ return l.paths ?? (l.type.kind === "array" || l.type.kind === "vec" || l.type.kind === "rbTree" ? [`@${l.c}`] : undefined);
32
40
  return this.accounts.has(node.text) ? [node.text] : undefined;
33
41
  }
34
42
  if (ts.isPropertyAccessExpression(node)) {
@@ -39,6 +47,16 @@ export class AliasEmitter extends EmitterBase {
39
47
  }
40
48
  if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "get")
41
49
  return this.pathsOf(node.expression.expression)?.map((p) => `${p}[]`);
50
+ // A tree's methods that hand out a node (`t.min()`, `t.nodeAt(i)`, `t.remove(k)`): a reference into its nodes.
51
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && TREE_NODE_METHODS.has(node.expression.name.text)) {
52
+ const base = node.expression.expression;
53
+ const l = ts.isIdentifier(base) ? this.lookup(base.text) : undefined;
54
+ if (l?.type.kind === "rbTree")
55
+ return [`@${l.c}[]`];
56
+ }
57
+ // `big.slice(a, b)` is a view of the list's own elements: the same storage.
58
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "slice")
59
+ return this.pathsOf(node.expression.expression);
42
60
  if (ts.isConditionalExpression(node)) {
43
61
  const a = this.pathsOf(node.whenTrue);
44
62
  const b = this.pathsOf(node.whenFalse);
@@ -62,8 +80,8 @@ export class AliasEmitter extends EmitterBase {
62
80
  if (!hit || !this.usedAfter(l.decl, at))
63
81
  continue;
64
82
  this.fail(at, helper
65
- ? `"${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`
66
- : `"${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`);
83
+ ? `"${name}" still refers to data in ${this.showPath(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`
84
+ : `"${name}" still refers to ${this.showPath(hit)}; replacing it here would change what "${name}" reads (in JS it keeps the old value). Copy the fields you need into locals first`);
67
85
  }
68
86
  }
69
87
  /**
@@ -116,6 +134,119 @@ export class AliasEmitter extends EmitterBase {
116
134
  visit(scope);
117
135
  return found;
118
136
  }
137
+ /**
138
+ * A helper given a place to change (`Inout<T>`) may replace what is stored inside it (`rec.inner = { … }`,
139
+ * `rec.items.pop()`), so a reference into it that is read after the call would read the new value where JS keeps the
140
+ * old object. References to the place itself (or to what holds it) see the same object as JS does, so only those
141
+ * strictly inside it are refused.
142
+ */
143
+ assertNothingInside(place, at, helper, arg) {
144
+ for (const scope of this.scopes)
145
+ for (const [name, l] of scope) {
146
+ if (!l.paths || !l.decl)
147
+ continue;
148
+ const hit = place.find((r) => l.paths.some((p) => p.startsWith(`${r}.`) || p.startsWith(`${r}[]`)));
149
+ if (!hit || !this.usedAfter(l.decl, at))
150
+ continue;
151
+ this.fail(at, `"${name}" refers to data inside ${arg}, which ${helper}() may change in place (Inout); if it replaced that data, "${name}" would read the new value where JS keeps the old one. Copy the fields you need into locals before the call, or read them through ${arg} after it`);
152
+ }
153
+ }
154
+ /**
155
+ * The account a native view's first argument names, as `viewAcct` records it: a declared parameter's name, or "?"
156
+ * when it is not one (a remaining account, a choice between accounts).
157
+ */
158
+ viewAccountKey(node) {
159
+ while (ts.isParenthesizedExpression(node))
160
+ node = node.expression;
161
+ return ts.isIdentifier(node) && !this.lookup(node.text) && this.accounts.has(node.text) ? node.text : "?";
162
+ }
163
+ /**
164
+ * Whether two accounts `viewAccountKey` named may be one account at run time: the same name, one not a declared
165
+ * parameter, or two parameters the runtime does not keep apart (a helper's, any two under NATIVE_ACCOUNT_WRITES, a
166
+ * read-only or Dup one; function.ts refuses two writable parameters naming one account otherwise).
167
+ */
168
+ mayBeSameAccount(a, b) {
169
+ if (a === b || a === "?" || b === "?" || this.nativeAccountWrites())
170
+ return true;
171
+ const [x, y] = [this.accounts.get(a), this.accounts.get(b)];
172
+ if (!x || !y || x.index === -1 || y.index === -1)
173
+ return true;
174
+ return !(isWritable(x.kind) && isWritable(y.kind) && !x.constraints.dup && !y.constraints.dup);
175
+ }
176
+ /**
177
+ * `closeRaw(acct, …)` / `resizeAccount(acct, n)` (or a helper that may do either, `target` "?"): a view checks its
178
+ * bounds once, when it is made, so a view of the account made before (and anything read through it) would reach past
179
+ * the account's new end afterwards. Refused when it is used later; the fix is to take the view again.
180
+ */
181
+ assertNoViewAfter(target, at, what) {
182
+ const dead = new Set();
183
+ for (const scope of this.scopes)
184
+ for (const l of scope.values())
185
+ if (l.viewAcct !== undefined && this.mayBeSameAccount(l.viewAcct, target))
186
+ dead.add(l.c);
187
+ if (!dead.size)
188
+ return;
189
+ for (const scope of this.scopes)
190
+ for (const [name, l] of scope) {
191
+ if (!l.decl)
192
+ continue;
193
+ const hit = dead.has(l.c) || !!l.paths?.some((p) => p.startsWith("@") && dead.has(p.slice(1).split(/[.[]/)[0]));
194
+ if (!hit || !this.usedAfter(l.decl, at))
195
+ continue;
196
+ this.fail(at, `"${name}" reads account data through a view made before ${what}, which changes the account's length: a view checks its bounds when it is made, so "${name}" could reach past the new end. Take the view again after ${what} and read through the new one`);
197
+ }
198
+ }
199
+ /** A storage path as the source names it: `@<C local>.x` becomes `<its name>.x` (`@p_rec.items[]` → `rec.items[]`). */
200
+ showPath(path) {
201
+ if (!path.startsWith("@"))
202
+ return path;
203
+ // A @heap local is named through its pointer: `@(*l_x)`.
204
+ const c = /^@(\(\*\w+\)|\w+)/.exec(path)?.[1];
205
+ for (const s of [...this.scopes].reverse().concat(this.args))
206
+ for (const [name, l] of s)
207
+ if (c && (l.c === c || l.c === `(*${c})`))
208
+ return name + path.slice(c.length + 1);
209
+ return path;
210
+ }
211
+ /** Whether two places share storage: the same path, or one inside the other. */
212
+ placesOverlap(a, b) {
213
+ const inside = (x, y) => x === y || x.startsWith(`${y}.`) || x.startsWith(`${y}[]`);
214
+ return a.some((x) => b.some((y) => inside(x, y) || inside(y, x)));
215
+ }
216
+ /**
217
+ * Whether a place is reached through an element of a list whose elements can move: a growable Vec of an account (a
218
+ * push or pop of it, or of a Vec stored before it, moves them), a heap Vec (`@layout borsh`) or a BigVec (`retain`
219
+ * shifts them). FixedVec and FixedArray elements stay where they are.
220
+ */
221
+ throughMovableList(node) {
222
+ for (let n = node;;) {
223
+ if (ts.isParenthesizedExpression(n))
224
+ n = n.expression;
225
+ else if (ts.isConditionalExpression(n))
226
+ return this.throughMovableList(n.whenTrue) || this.throughMovableList(n.whenFalse);
227
+ else if (ts.isPropertyAccessExpression(n))
228
+ n = n.expression;
229
+ else if (ts.isNonNullExpression(n))
230
+ n = n.expression;
231
+ else if (ts.isCallExpression(n) &&
232
+ ts.isPropertyAccessExpression(n.expression) &&
233
+ (n.expression.name.text === "get" || n.expression.name.text === "slice")) {
234
+ const base = n.expression.expression;
235
+ // A list reached through another call (`a.get(i).get(j)`, `big.slice(s, e).get(i)`) is judged by the list under
236
+ // it, walked next; it is not probed itself (a probed slice would keep a view whose lines were dropped).
237
+ if (!ts.isCallExpression(base)) {
238
+ const t = this.peekType(base);
239
+ if (t?.kind === "vec" && t.cap === undefined)
240
+ return true;
241
+ }
242
+ n = base;
243
+ }
244
+ else if (ts.isIdentifier(n))
245
+ return !!this.lookup(n.text)?.movable;
246
+ else
247
+ return false;
248
+ }
249
+ }
119
250
  /** Whether a place goes through a Vec element (`v.get(i).x`, `v.get(i)`). */
120
251
  writesThroughVec(node) {
121
252
  for (let n = node;;) {
@@ -2,7 +2,7 @@ import ts from "typescript";
2
2
  import { type Analysis, type TypeArg, type TypeScope } from "../analyze.js";
3
3
  import type { Reporter } from "../diagnostics.js";
4
4
  import { type AccountParam, type GenericHelper, type Helper, type IdlSeed, type Instruction, type ProgramModel, type ValueType } from "../model.js";
5
- import { type Value, type Ref, type Local, type Closure, type FunctionChoice, type EmitOptions } from "./shared.js";
5
+ import { type Value, type Ref, type Local, type Closure, type FunctionChoice, type EmitOptions, type CpiProgram } from "./shared.js";
6
6
  /**
7
7
  * State of one function being lowered, and the primitives every layer uses: emitting lines, temporaries,
8
8
  * scopes, evaluation-order snapshots and account lookups.
@@ -17,6 +17,17 @@ export declare abstract class EmitterBase {
17
17
  protected lines: string[];
18
18
  /** Declarations placed at the top of the function (buffers reused by every pass through a loop). */
19
19
  protected hoisted: string[];
20
+ /**
21
+ * The hoisted declarations of heap buffers taken on first use (`T *name = NULL;`), by line: a loop moved into a
22
+ * function of its own leaves them in its caller and is given a pointer to each (see outlinedLoop), so the buffer is
23
+ * still taken once per function, not once per call of the loop's.
24
+ */
25
+ protected readonly lazyHoists: Map<string, {
26
+ name: string;
27
+ decl: (name: string) => string;
28
+ }>;
29
+ /** Loops moved into C functions of their own (see outlinedLoop), placed before this function. */
30
+ protected outlinedLoops: string[];
20
31
  protected indent: number;
21
32
  protected temp: number;
22
33
  /** Init accounts whose create() has run (top-level, in order). */
@@ -61,6 +72,11 @@ export declare abstract class EmitterBase {
61
72
  private readonly calleeCache;
62
73
  /** `file.ts:line` of the statement being lowered. */
63
74
  protected where: string | undefined;
75
+ /**
76
+ * Inside `panicsAt(location, expression)`: the Rust location ("file:line:col") its checked arithmetic panics at,
77
+ * with Rust's messages ("attempt to add with overflow"), instead of failing with 5100 / 5101.
78
+ */
79
+ protected panicAt: string | undefined;
64
80
  protected readonly profile: boolean;
65
81
  constructor(analysis: Analysis, target: Instruction | Helper, opts?: EmitOptions);
66
82
  /** The helper a call runs: a function, a const arrow function (top-level or local), or a generic one's instance. */
@@ -81,6 +97,8 @@ export declare abstract class EmitterBase {
81
97
  /** `file.ts:line` of a node, for messages. */
82
98
  protected location(node: ts.Node): string;
83
99
  protected tmp(prefix?: string): string;
100
+ /** Declare a heap buffer pointer at the top of the function, NULL until first use (`decl(name)` declares it). */
101
+ protected hoistLazy(name: string, decl: (name: string) => string): void;
84
102
  /**
85
103
  * JS evaluates operands left to right, but a lowered Value is a C expression read where it is used.
86
104
  * When lowering a later operand emitted statements (from line `mark` on, e.g. a pop() or a helper call),
@@ -100,6 +118,25 @@ export declare abstract class EmitterBase {
100
118
  protected probe<T>(fn: () => T): T | undefined;
101
119
  protected fail(node: ts.Node, message: string): never;
102
120
  protected exportName(node: ts.Expression): string | undefined;
121
+ /**
122
+ * `const NATIVE_ACCOUNT_WRITES = true`: loadRawMut, storeBorsh and BigVec writes follow a native program, which
123
+ * writes data in place and leaves writability to the runtime (ReadonlyDataModified when a read-only account's data
124
+ * changed) and lets one account be viewed twice. Without it they check writability (3006) and claim the account
125
+ * once (2040) up front.
126
+ */
127
+ protected nativeAccountWrites(): boolean;
128
+ /**
129
+ * `const PANIC_STYLE = "solana-1.14"`: a Rust panic logs what solana_program 1.14's panic handler logs (rustc before
130
+ * 1.73 formats it as `panicked at '<message>', <file>:<line>:<col>`) and then aborts, so the runtime reports "SBF
131
+ * program panicked"; by default it logs the message and calls sol_panic_ with the location.
132
+ */
133
+ protected panicStyle(): "solana-1.14" | undefined;
134
+ /** The C statements of a Rust panic with `message` (undefined: nothing logged) at `location` ("file:line:col"). */
135
+ protected panicC(message: string | undefined, location: string): string[];
136
+ /** `file.ts:line:column` of a node (1-based, as Rust reports a location). */
137
+ protected locationWithColumn(node: ts.Node): string;
138
+ /** Whether `node` is an EpochRewards value: `epochRewards()` or a local holding one. */
139
+ protected isEpochRewards(node: ts.Expression): boolean;
103
140
  /**
104
141
  * `acct!.field` on an optional account: the same access without `!` (using the account checks that it was passed,
105
142
  * failing with 5115 otherwise). Returns undefined for anything else.
@@ -123,6 +160,15 @@ export declare abstract class EmitterBase {
123
160
  protected abstract isRemaining(node: ts.Expression): boolean;
124
161
  protected abstract remainingBase(node: ts.Expression): string;
125
162
  protected abstract handle(node: ts.Expression): string | undefined;
163
+ protected abstract looksLikeAccountHandle(node: ts.Expression): boolean;
164
+ protected abstract isVecArgView(node: ts.Expression): boolean;
165
+ protected abstract vecArgView(node: ts.Expression): {
166
+ c: string;
167
+ type: ValueType & {
168
+ kind: "vecArg";
169
+ };
170
+ } | undefined;
171
+ protected abstract accountChoice(node: ts.ConditionalExpression): Value;
126
172
  protected abstract instructionsParam(node: ts.Expression): AccountParam | undefined;
127
173
  protected abstract isTxIx(node: ts.Expression): boolean;
128
174
  protected abstract seeds(node: ts.Expression, extra: number): {
@@ -135,13 +181,13 @@ export declare abstract class EmitterBase {
135
181
  protected abstract createAta(node: ts.CallExpression, target: AccountParam, topLevel: boolean): Value | undefined;
136
182
  protected abstract createToken(node: ts.CallExpression, target: AccountParam, topLevel: boolean): Value;
137
183
  protected abstract systemTransfer(node: ts.CallExpression): undefined;
138
- protected abstract createAccount(node: ts.CallExpression, system: AccountParam): undefined;
184
+ protected abstract createAccount(node: ts.CallExpression, system: CpiProgram): undefined;
139
185
  protected abstract createPda(node: ts.CallExpression): Value;
140
- protected abstract allocateOrAssign(node: ts.CallExpression, system: AccountParam, method: "allocate" | "assign"): undefined;
141
- protected abstract tokenOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
142
- protected abstract ataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
143
- protected abstract memoOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
144
- protected abstract stakeOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
186
+ protected abstract allocateOrAssign(node: ts.CallExpression, system: CpiProgram, method: "allocate" | "assign"): undefined;
187
+ protected abstract tokenOp(node: ts.CallExpression, program: CpiProgram, method: string): undefined;
188
+ protected abstract ataOp(node: ts.CallExpression, program: CpiProgram, method: string): undefined;
189
+ protected abstract memoOp(node: ts.CallExpression, program: CpiProgram, method: string): undefined;
190
+ protected abstract stakeOp(node: ts.CallExpression, program: CpiProgram, method: string): Value | undefined;
145
191
  protected abstract metadataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
146
192
  protected abstract coreOp(node: ts.CallExpression, core: AccountParam, method: string): undefined;
147
193
  protected abstract bubblegumOp(node: ts.CallExpression, bg: AccountParam, method: string): undefined;
@@ -155,7 +201,18 @@ export declare abstract class EmitterBase {
155
201
  protected abstract expandClosure(c: Closure, args: readonly ts.Expression[], node: ts.Node): Value | undefined;
156
202
  protected abstract callChoice(choice: FunctionChoice, args: readonly ts.Expression[], node: ts.Node): Value | undefined;
157
203
  protected abstract listMethod(node: ts.CallExpression, method: string): Value | undefined;
204
+ protected abstract expressionStatement(e: ts.Expression, topLevel: boolean): void;
205
+ protected abstract byteListMethod(node: ts.CallExpression, method: string, v: Ref): Value | undefined;
206
+ protected abstract programErrorFail(name: string, node: ts.Node): string;
158
207
  protected abstract isPipeline(e: ts.Expression): e is ts.CallExpression;
208
+ /** views.ts: a RedBlackTree method call, or undefined when `node` is not one. */
209
+ protected abstract treeCall(node: ts.CallExpression): {
210
+ value: Value | undefined;
211
+ } | undefined;
212
+ /** views.ts: the place a RawArray, a tree node's `.key` / `.value` or a narrowed tree result names. */
213
+ protected abstract viewRef(node: ts.Expression): Ref | undefined;
214
+ /** views.ts: `.length` / `.capacity` of a tree, `.index` of a tree node. */
215
+ protected abstract viewProperty(node: ts.PropertyAccessExpression): Value | undefined;
159
216
  protected abstract closureOf(arg: ts.Expression): Closure;
160
217
  /** The arguments and accounts code written here can name (what a closure written here keeps). */
161
218
  protected envNow(): Closure["env"];
@@ -168,5 +225,6 @@ export declare abstract class EmitterBase {
168
225
  next?: string;
169
226
  alwaysNext?: boolean;
170
227
  atNext?: () => void;
228
+ body?: ts.Node;
171
229
  }, body: (element: ts.Expression, index: ts.Expression) => void): void;
172
230
  }
@@ -1,7 +1,7 @@
1
1
  import ts from "typescript";
2
2
  import { calleeName, resolveScalarType, structNameOf } from "../analyze.js";
3
3
  import { isScalar, } from "../model.js";
4
- import { isStable, cString, valueC } from "./shared.js";
4
+ import { isStable, cString, valueC, fixedVecC, } from "./shared.js";
5
5
  /**
6
6
  * State of one function being lowered, and the primitives every layer uses: emitting lines, temporaries,
7
7
  * scopes, evaluation-order snapshots and account lookups.
@@ -16,6 +16,14 @@ export class EmitterBase {
16
16
  lines = [];
17
17
  /** Declarations placed at the top of the function (buffers reused by every pass through a loop). */
18
18
  hoisted = [];
19
+ /**
20
+ * The hoisted declarations of heap buffers taken on first use (`T *name = NULL;`), by line: a loop moved into a
21
+ * function of its own leaves them in its caller and is given a pointer to each (see outlinedLoop), so the buffer is
22
+ * still taken once per function, not once per call of the loop's.
23
+ */
24
+ lazyHoists = new Map();
25
+ /** Loops moved into C functions of their own (see outlinedLoop), placed before this function. */
26
+ outlinedLoops = [];
19
27
  indent = 1;
20
28
  temp = 0;
21
29
  /** Init accounts whose create() has run (top-level, in order). */
@@ -46,6 +54,11 @@ export class EmitterBase {
46
54
  calleeCache = new Map();
47
55
  /** `file.ts:line` of the statement being lowered. */
48
56
  where;
57
+ /**
58
+ * Inside `panicsAt(location, expression)`: the Rust location ("file:line:col") its checked arithmetic panics at,
59
+ * with Rust's messages ("attempt to add with overflow"), instead of failing with 5100 / 5101.
60
+ */
61
+ panicAt;
49
62
  profile;
50
63
  constructor(analysis, target, opts = {}) {
51
64
  this.profile = !!opts.profile;
@@ -73,24 +86,44 @@ export class EmitterBase {
73
86
  ((a.kind.kind === "token" || a.kind.kind === "mint") && a.kind.init))
74
87
  this.pendingInit.add(a.name);
75
88
  }
89
+ // A struct, FixedArray or data enum argument is decoded into memory of its own (`owned`: never account data, so a
90
+ // helper taking accounts reads it in place instead of a copy).
76
91
  for (const a of target.args)
77
92
  this.args.set(a.name, a.type.kind === "dataEnumArg"
78
- ? { c: `arg_${a.name}`, type: { kind: "enumRef", name: a.type.name, writable: false }, mutable: false }
93
+ ? { c: `arg_${a.name}`, type: { kind: "enumRef", name: a.type.name, writable: false }, mutable: false, owned: true }
79
94
  : a.type.kind === "arrayArg"
80
- ? { c: `(*arg_${a.name})`, type: a.type.array, mutable: false, readonly: true }
81
- : { c: `arg_${a.name}`, type: a.type, mutable: false });
95
+ ? { c: `(*arg_${a.name})`, type: a.type.array, mutable: false, readonly: true, owned: true }
96
+ : { c: `arg_${a.name}`, type: a.type, mutable: false, ...(a.type.kind === "structRef" ? { owned: true } : {}) });
82
97
  }
83
98
  else {
84
99
  this.helper = target;
100
+ // A helper that takes accounts gets its struct, FixedArray and data enum arguments as a copy or as a pointer to
101
+ // memory its caller owns, never account data (see snapshotPlace): `owned`, so it passes them on in place.
102
+ const owned = target.params.some((p) => p.account || p.type.kind === "account" || p.type.kind === "remaining") ? { owned: true } : {};
85
103
  for (const p of target.params) {
86
104
  if (p.account)
87
105
  this.accounts.set(p.name, { name: p.name, index: -1, kind: p.account, node: p.node, constraints: { hasOne: [] } });
106
+ else if (p.inout) {
107
+ // Inout<T>: the caller's place, read and written through its pointer. Its paths let the aliasing rules see
108
+ // references into it (`const e = rec.items.get(i)` before `rec.items.pop()`).
109
+ const paths = [`@p_${p.name}`];
110
+ if (p.inout.kind === "struct")
111
+ this.args.set(p.name, { c: `p_${p.name}`, type: { kind: "structRef", struct: p.inout.name, writable: true }, mutable: false, paths, decl: p.node });
112
+ else {
113
+ if (p.inout.kind === "vec")
114
+ this.model.localVecs.set(fixedVecC(p.inout), p.inout);
115
+ const elem = p.inout.elem;
116
+ if (elem.kind === "fstring")
117
+ this.model.fstrings.add(elem.cap);
118
+ this.args.set(p.name, { c: `(*p_${p.name})`, type: p.inout, mutable: false, paths, decl: p.node });
119
+ }
120
+ }
88
121
  else if (p.type.kind === "arrayArg")
89
- this.args.set(p.name, { c: `(*p_${p.name})`, type: p.type.array, mutable: false, readonly: true });
122
+ this.args.set(p.name, { c: `(*p_${p.name})`, type: p.type.array, mutable: false, readonly: true, ...owned });
90
123
  else if (p.type.kind === "dataEnumArg")
91
- this.args.set(p.name, { c: `p_${p.name}`, type: { kind: "enumRef", name: p.type.name, writable: false }, mutable: false });
124
+ this.args.set(p.name, { c: `p_${p.name}`, type: { kind: "enumRef", name: p.type.name, writable: false }, mutable: false, ...owned });
92
125
  else
93
- this.args.set(p.name, { c: `p_${p.name}`, type: p.type, mutable: false });
126
+ this.args.set(p.name, { c: `p_${p.name}`, type: p.type, mutable: false, ...(p.type.kind === "structRef" ? owned : {}) });
94
127
  }
95
128
  }
96
129
  }
@@ -218,6 +251,12 @@ export class EmitterBase {
218
251
  tmp(prefix = "t") {
219
252
  return `${prefix}${this.temp++}`;
220
253
  }
254
+ /** Declare a heap buffer pointer at the top of the function, NULL until first use (`decl(name)` declares it). */
255
+ hoistLazy(name, decl) {
256
+ const line = ` ${decl(name)} = NULL;`;
257
+ this.lazyHoists.set(line, { name, decl });
258
+ this.hoisted.push(line);
259
+ }
221
260
  /**
222
261
  * JS evaluates operands left to right, but a lowered Value is a C expression read where it is used.
223
262
  * When lowering a later operand emitted statements (from line `mark` on, e.g. a pop() or a helper call),
@@ -301,6 +340,7 @@ export class EmitterBase {
301
340
  const saved = {
302
341
  lines: this.lines.length,
303
342
  hoisted: this.hoisted.length, // a probed helper call may hoist declarations
343
+ outlined: this.outlinedLoops.length,
304
344
  temp: this.temp,
305
345
  diagnostics: this.reporter.diagnostics.length,
306
346
  scopes: this.scopes.length,
@@ -318,6 +358,7 @@ export class EmitterBase {
318
358
  finally {
319
359
  this.lines.length = saved.lines;
320
360
  this.hoisted.length = saved.hoisted;
361
+ this.outlinedLoops.length = saved.outlined;
321
362
  this.temp = saved.temp;
322
363
  this.reporter.diagnostics.length = saved.diagnostics;
323
364
  this.scopes.length = saved.scopes;
@@ -343,6 +384,49 @@ export class EmitterBase {
343
384
  exportName(node) {
344
385
  return ts.isIdentifier(node) ? this.imports.get(node.text) : undefined;
345
386
  }
387
+ /**
388
+ * `const NATIVE_ACCOUNT_WRITES = true`: loadRawMut, storeBorsh and BigVec writes follow a native program, which
389
+ * writes data in place and leaves writability to the runtime (ReadonlyDataModified when a read-only account's data
390
+ * changed) and lets one account be viewed twice. Without it they check writability (3006) and claim the account
391
+ * once (2040) up front.
392
+ */
393
+ nativeAccountWrites() {
394
+ return this.model.constants.get("NATIVE_ACCOUNT_WRITES")?.value === true;
395
+ }
396
+ /**
397
+ * `const PANIC_STYLE = "solana-1.14"`: a Rust panic logs what solana_program 1.14's panic handler logs (rustc before
398
+ * 1.73 formats it as `panicked at '<message>', <file>:<line>:<col>`) and then aborts, so the runtime reports "SBF
399
+ * program panicked"; by default it logs the message and calls sol_panic_ with the location.
400
+ */
401
+ panicStyle() {
402
+ return this.model.constants.get("PANIC_STYLE")?.value === "solana-1.14" ? "solana-1.14" : undefined;
403
+ }
404
+ /** The C statements of a Rust panic with `message` (undefined: nothing logged) at `location` ("file:line:col"). */
405
+ panicC(message, location) {
406
+ if (this.panicStyle())
407
+ return [`sol_log(${cString(`panicked at '${message}', ${location}`)});`, `abort();`, `__builtin_unreachable();`];
408
+ const m = /^(.*?):(\d+)(?::(\d+))?$/.exec(location);
409
+ const [file, line, col] = m ? [m[1], m[2], m[3] ?? "0"] : [location, "0", "0"];
410
+ return [
411
+ ...(message !== undefined ? [`sol_log(${cString(message)});`] : []),
412
+ `sol_panic_(${cString(file)}, ${Buffer.byteLength(file)}, ${line}, ${col});`,
413
+ `__builtin_unreachable();`,
414
+ ];
415
+ }
416
+ /** `file.ts:line:column` of a node (1-based, as Rust reports a location). */
417
+ locationWithColumn(node) {
418
+ const sf = node.getSourceFile();
419
+ const lc = sf.getLineAndCharacterOfPosition(node.getStart(sf));
420
+ return `${sf.fileName.split("/").pop()}:${lc.line + 1}:${lc.character + 1}`;
421
+ }
422
+ /** Whether `node` is an EpochRewards value: `epochRewards()` or a local holding one. */
423
+ isEpochRewards(node) {
424
+ if (ts.isParenthesizedExpression(node))
425
+ return this.isEpochRewards(node.expression);
426
+ if (ts.isIdentifier(node))
427
+ return this.lookup(node.text)?.type.kind === "epochRewards";
428
+ return ts.isCallExpression(node) && this.exportName(node.expression) === "epochRewards";
429
+ }
346
430
  /**
347
431
  * `acct!.field` on an optional account: the same access without `!` (using the account checks that it was passed,
348
432
  * failing with 5115 otherwise). Returns undefined for anything else.
@@ -11,3 +11,10 @@ export declare function borshIdentical(t: FieldType, model: Pick<ProgramModel, "
11
11
  export declare function borshMinSize(s: StructDef, model: Pick<ProgramModel, "structs">): number;
12
12
  /** C for `ts_unpack_<S>` and `ts_pack_<S>` of every `@layout borsh` struct. */
13
13
  export declare function emitBorshCodecs(model: ProgramModel): string[];
14
+ /**
15
+ * C for `ts_bdec_<S>` / `ts_benc_<S>` of the structs `loadBorsh` / `storeBorsh` use (model.borshNative): the same
16
+ * straight-line codec, failing with a bare nonzero return (no log) so that the call site fails with BorshIoError.
17
+ */
18
+ export declare function emitNativeBorshCodecs(model: ProgramModel): string[];
19
+ /** Why `loadBorsh<S>` / `storeBorsh` cannot take struct `s`, or undefined when they can. */
20
+ export declare function borshNativeStructUnsupported(s: StructDef, model: Pick<ProgramModel, "structs" | "dataEnums">): string | undefined;