@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
@@ -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[]"],
@@ -29,13 +38,48 @@ export declare abstract class AliasEmitter extends EmitterBase {
29
38
  * to the old object unchanged. Here a reference is a pointer into account data, so it would see the new
30
39
  * value. Refuse when a live reference into the replaced place is still used afterwards.
31
40
  */
32
- protected assertNotAliased(replaced: string[] | undefined, at: ts.Node, helper?: string): void;
41
+ protected assertNotAliased(replaced: string[] | undefined, at: ts.Node, helper?: string, inPlace?: boolean): void;
33
42
  /**
34
43
  * Whether the variable declared by `decl` is read after `at` (later in its block, or anywhere in a loop around `at`).
35
44
  * A parameter (of a closure or helper expanded here) is read after `at` when its function reads it after `at`; when
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);
@@ -51,19 +69,21 @@ export class AliasEmitter extends EmitterBase {
51
69
  * to the old object unchanged. Here a reference is a pointer into account data, so it would see the new
52
70
  * value. Refuse when a live reference into the replaced place is still used afterwards.
53
71
  */
54
- assertNotAliased(replaced, at, helper) {
72
+ assertNotAliased(replaced, at, helper, inPlace = false) {
55
73
  if (!replaced)
56
74
  return;
57
75
  for (const scope of this.scopes)
58
76
  for (const [name, l] of scope) {
59
77
  if (!l.paths || !l.decl)
60
78
  continue;
61
- const hit = replaced.find((r) => l.paths.some((p) => p === r || p.startsWith(`${r}.`) || p.startsWith(`${r}[]`)));
79
+ // A helper given an account changes it in place (`inPlace`): a local naming the whole account (a struct loaded
80
+ // with loadAccountMut) then reads what JS's object would. Only references into it are stale.
81
+ const hit = replaced.find((r) => l.paths.some((p) => (p === r && !inPlace) || p.startsWith(`${r}.`) || p.startsWith(`${r}[]`)));
62
82
  if (!hit || !this.usedAfter(l.decl, at))
63
83
  continue;
64
84
  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`);
85
+ ? `"${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`
86
+ : `"${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
87
  }
68
88
  }
69
89
  /**
@@ -116,6 +136,123 @@ export class AliasEmitter extends EmitterBase {
116
136
  visit(scope);
117
137
  return found;
118
138
  }
139
+ /**
140
+ * A helper given a place to change (`Inout<T>`) may replace what is stored inside it (`rec.inner = { … }`,
141
+ * `rec.items.pop()`), so a reference into it that is read after the call would read the new value where JS keeps the
142
+ * old object. References to the place itself (or to what holds it) see the same object as JS does, so only those
143
+ * strictly inside it are refused.
144
+ */
145
+ assertNothingInside(place, at, helper, arg) {
146
+ for (const scope of this.scopes)
147
+ for (const [name, l] of scope) {
148
+ if (!l.paths || !l.decl)
149
+ continue;
150
+ const hit = place.find((r) => l.paths.some((p) => p.startsWith(`${r}.`) || p.startsWith(`${r}[]`)));
151
+ if (!hit || !this.usedAfter(l.decl, at))
152
+ continue;
153
+ 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`);
154
+ }
155
+ }
156
+ /**
157
+ * The account a native view's first argument names, as `viewAcct` records it: a declared parameter's name, or "?"
158
+ * when it is not one (a remaining account, a choice between accounts).
159
+ */
160
+ viewAccountKey(node) {
161
+ while (ts.isParenthesizedExpression(node))
162
+ node = node.expression;
163
+ return ts.isIdentifier(node) && !this.lookup(node.text) && this.accounts.has(node.text) ? node.text : "?";
164
+ }
165
+ /**
166
+ * Whether two accounts `viewAccountKey` named may be one account at run time: the same name, one not a declared
167
+ * parameter, or two parameters the runtime does not keep apart (a helper's, any two under NATIVE_ACCOUNT_WRITES, a
168
+ * read-only or Dup one; function.ts refuses two writable parameters naming one account otherwise).
169
+ */
170
+ mayBeSameAccount(a, b) {
171
+ if (a === b || a === "?" || b === "?" || this.nativeAccountWrites())
172
+ return true;
173
+ const [x, y] = [this.accounts.get(a), this.accounts.get(b)];
174
+ if (!x || !y || x.index === -1 || y.index === -1)
175
+ return true;
176
+ return !(isWritable(x.kind) && isWritable(y.kind) && !x.constraints.dup && !y.constraints.dup);
177
+ }
178
+ /**
179
+ * `closeRaw(acct, …)` / `resizeAccount(acct, n)` (or a helper that may do either, `target` "?"): a view checks its
180
+ * bounds once, when it is made, so a view of the account made before (and anything read through it) would reach past
181
+ * the account's new end afterwards. Refused when it is used later; the fix is to take the view again.
182
+ */
183
+ assertNoViewAfter(target, at, what) {
184
+ const dead = new Set();
185
+ for (const scope of this.scopes)
186
+ for (const l of scope.values())
187
+ if (l.viewAcct !== undefined && this.mayBeSameAccount(l.viewAcct, target))
188
+ dead.add(l.c);
189
+ if (!dead.size)
190
+ return;
191
+ for (const scope of this.scopes)
192
+ for (const [name, l] of scope) {
193
+ if (!l.decl)
194
+ continue;
195
+ const hit = dead.has(l.c) || !!l.paths?.some((p) => p.startsWith("@") && dead.has(p.slice(1).split(/[.[]/)[0]));
196
+ if (!hit || !this.usedAfter(l.decl, at))
197
+ continue;
198
+ 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`);
199
+ }
200
+ }
201
+ /** A storage path as the source names it: `@<C local>.x` becomes `<its name>.x` (`@p_rec.items[]` → `rec.items[]`). */
202
+ showPath(path) {
203
+ if (!path.startsWith("@")) {
204
+ // A field of an account group, as the source names it: `g__pool.b[]` → `g.pool.b[]`.
205
+ const root = path.split(/[.[]/)[0];
206
+ const g = this.accounts.get(root)?.group;
207
+ return g ? [...g.path, g.field].join(".") + path.slice(root.length) : path;
208
+ }
209
+ // A @heap local is named through its pointer: `@(*l_x)`.
210
+ const c = /^@(\(\*\w+\)|\w+)/.exec(path)?.[1];
211
+ for (const s of [...this.scopes].reverse().concat(this.args))
212
+ for (const [name, l] of s)
213
+ if (c && (l.c === c || l.c === `(*${c})`))
214
+ return name + path.slice(c.length + 1);
215
+ return path;
216
+ }
217
+ /** Whether two places share storage: the same path, or one inside the other. */
218
+ placesOverlap(a, b) {
219
+ const inside = (x, y) => x === y || x.startsWith(`${y}.`) || x.startsWith(`${y}[]`);
220
+ return a.some((x) => b.some((y) => inside(x, y) || inside(y, x)));
221
+ }
222
+ /**
223
+ * Whether a place is reached through an element of a list whose elements can move: a growable Vec of an account (a
224
+ * push or pop of it, or of a Vec stored before it, moves them), a heap Vec (`@layout borsh`) or a BigVec (`retain`
225
+ * shifts them). FixedVec and FixedArray elements stay where they are.
226
+ */
227
+ throughMovableList(node) {
228
+ for (let n = node;;) {
229
+ if (ts.isParenthesizedExpression(n))
230
+ n = n.expression;
231
+ else if (ts.isConditionalExpression(n))
232
+ return this.throughMovableList(n.whenTrue) || this.throughMovableList(n.whenFalse);
233
+ else if (ts.isPropertyAccessExpression(n))
234
+ n = n.expression;
235
+ else if (ts.isNonNullExpression(n))
236
+ n = n.expression;
237
+ else if (ts.isCallExpression(n) &&
238
+ ts.isPropertyAccessExpression(n.expression) &&
239
+ (n.expression.name.text === "get" || n.expression.name.text === "slice")) {
240
+ const base = n.expression.expression;
241
+ // A list reached through another call (`a.get(i).get(j)`, `big.slice(s, e).get(i)`) is judged by the list under
242
+ // it, walked next; it is not probed itself (a probed slice would keep a view whose lines were dropped).
243
+ if (!ts.isCallExpression(base)) {
244
+ const t = this.peekType(base);
245
+ if (t?.kind === "vec" && t.cap === undefined)
246
+ return true;
247
+ }
248
+ n = base;
249
+ }
250
+ else if (ts.isIdentifier(n))
251
+ return !!this.lookup(n.text)?.movable;
252
+ else
253
+ return false;
254
+ }
255
+ }
119
256
  /** Whether a place goes through a Vec element (`v.get(i).x`, `v.get(i)`). */
120
257
  writesThroughVec(node) {
121
258
  for (let n = node;;) {
@@ -72,6 +72,11 @@ export declare abstract class EmitterBase {
72
72
  private readonly calleeCache;
73
73
  /** `file.ts:line` of the statement being lowered. */
74
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;
75
80
  protected readonly profile: boolean;
76
81
  constructor(analysis: Analysis, target: Instruction | Helper, opts?: EmitOptions);
77
82
  /** The helper a call runs: a function, a const arrow function (top-level or local), or a generic one's instance. */
@@ -100,6 +105,8 @@ export declare abstract class EmitterBase {
100
105
  * copy an earlier operand that reads storage into a temporary just before them, so it sees the old state.
101
106
  */
102
107
  protected settle(v: Value, mark: number): Value;
108
+ /** Whether a C line emitted from `mark` on assigns, increments or takes the address of the C variable `name`. */
109
+ protected writtenSince(name: string, mark: number): boolean;
103
110
  /** A string that stays valid when account data changes: views of account text are copied to the heap. */
104
111
  protected ownedString(v: Value): Value;
105
112
  /** Reject `a?.b` / `f?.()`: there is no undefined in TypeSOL. */
@@ -120,6 +127,16 @@ export declare abstract class EmitterBase {
120
127
  * once (2040) up front.
121
128
  */
122
129
  protected nativeAccountWrites(): boolean;
130
+ /**
131
+ * `const PANIC_STYLE = "solana-1.14"`: a Rust panic logs what solana_program 1.14's panic handler logs (rustc before
132
+ * 1.73 formats it as `panicked at '<message>', <file>:<line>:<col>`) and then aborts, so the runtime reports "SBF
133
+ * program panicked"; by default it logs the message and calls sol_panic_ with the location.
134
+ */
135
+ protected panicStyle(): "solana-1.14" | undefined;
136
+ /** The C statements of a Rust panic with `message` (undefined: nothing logged) at `location` ("file:line:col"). */
137
+ protected panicC(message: string | undefined, location: string): string[];
138
+ /** `file.ts:line:column` of a node (1-based, as Rust reports a location). */
139
+ protected locationWithColumn(node: ts.Node): string;
123
140
  /** Whether `node` is an EpochRewards value: `epochRewards()` or a local holding one. */
124
141
  protected isEpochRewards(node: ts.Expression): boolean;
125
142
  /**
@@ -156,7 +173,7 @@ export declare abstract class EmitterBase {
156
173
  protected abstract accountChoice(node: ts.ConditionalExpression): Value;
157
174
  protected abstract instructionsParam(node: ts.Expression): AccountParam | undefined;
158
175
  protected abstract isTxIx(node: ts.Expression): boolean;
159
- protected abstract seeds(node: ts.Expression, extra: number): {
176
+ protected abstract seeds(node: ts.Expression, extra: number, bound?: boolean): {
160
177
  name: string;
161
178
  count: number;
162
179
  idl: IdlSeed[] | undefined;
@@ -186,8 +203,18 @@ export declare abstract class EmitterBase {
186
203
  protected abstract expandClosure(c: Closure, args: readonly ts.Expression[], node: ts.Node): Value | undefined;
187
204
  protected abstract callChoice(choice: FunctionChoice, args: readonly ts.Expression[], node: ts.Node): Value | undefined;
188
205
  protected abstract listMethod(node: ts.CallExpression, method: string): Value | undefined;
206
+ protected abstract expressionStatement(e: ts.Expression, topLevel: boolean): void;
207
+ protected abstract byteListMethod(node: ts.CallExpression, method: string, v: Ref): Value | undefined;
189
208
  protected abstract programErrorFail(name: string, node: ts.Node): string;
190
209
  protected abstract isPipeline(e: ts.Expression): e is ts.CallExpression;
210
+ /** views.ts: a RedBlackTree method call, or undefined when `node` is not one. */
211
+ protected abstract treeCall(node: ts.CallExpression): {
212
+ value: Value | undefined;
213
+ } | undefined;
214
+ /** views.ts: the place a RawArray, a tree node's `.key` / `.value` or a narrowed tree result names. */
215
+ protected abstract viewRef(node: ts.Expression): Ref | undefined;
216
+ /** views.ts: `.length` / `.capacity` of a tree, `.index` of a tree node. */
217
+ protected abstract viewProperty(node: ts.PropertyAccessExpression): Value | undefined;
191
218
  protected abstract closureOf(arg: ts.Expression): Closure;
192
219
  /** The arguments and accounts code written here can name (what a closure written here keeps). */
193
220
  protected envNow(): Closure["env"];
@@ -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, passedByPointer, } 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.
@@ -54,6 +54,11 @@ export class EmitterBase {
54
54
  calleeCache = new Map();
55
55
  /** `file.ts:line` of the statement being lowered. */
56
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;
57
62
  profile;
58
63
  constructor(analysis, target, opts = {}) {
59
64
  this.profile = !!opts.profile;
@@ -81,24 +86,47 @@ export class EmitterBase {
81
86
  ((a.kind.kind === "token" || a.kind.kind === "mint") && a.kind.init))
82
87
  this.pendingInit.add(a.name);
83
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).
84
91
  for (const a of target.args)
85
92
  this.args.set(a.name, a.type.kind === "dataEnumArg"
86
- ? { 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 }
87
94
  : a.type.kind === "arrayArg"
88
- ? { c: `(*arg_${a.name})`, type: a.type.array, mutable: false, readonly: true }
89
- : { 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 } : {}) });
90
97
  }
91
98
  else {
92
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 } : {};
93
103
  for (const p of target.params) {
94
104
  if (p.account)
95
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
+ }
96
121
  else if (p.type.kind === "arrayArg")
97
- 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 });
98
123
  else if (p.type.kind === "dataEnumArg")
99
- 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 });
125
+ // A Pubkey, Option, string or u256 comes as a const pointer (see passedByPointer): read through it.
126
+ else if (passedByPointer(p.type))
127
+ this.args.set(p.name, { c: `(*p_${p.name})`, type: p.type, mutable: false });
100
128
  else
101
- this.args.set(p.name, { c: `p_${p.name}`, type: p.type, mutable: false });
129
+ this.args.set(p.name, { c: `p_${p.name}`, type: p.type, mutable: false, ...(p.type.kind === "structRef" ? owned : {}) });
102
130
  }
103
131
  }
104
132
  }
@@ -240,8 +268,13 @@ export class EmitterBase {
240
268
  settle(v, mark) {
241
269
  if (this.lines.length === mark || v.isNull || v.literal !== undefined || v.stringLiteral !== undefined)
242
270
  return v;
243
- if (isStable(v.c))
244
- return v;
271
+ // A local (or a temporary) is stable unless what was emitted since writes it: a closure or list callback expanded
272
+ // in the later operand (`x + bump()` with `bump` doing `x += 1n`), or an outlined loop given its address.
273
+ if (isStable(v.c)) {
274
+ const name = /^(?:\w+|\(&(\w+)\))$/.exec(v.c) ? (/^\w+$/.test(v.c) ? v.c : v.c.slice(2, -1)) : undefined;
275
+ if (!name || !this.writtenSince(name, mark))
276
+ return v;
277
+ }
245
278
  const t = this.tmp("snap");
246
279
  const pad = " ".repeat(this.indent);
247
280
  const decl = [];
@@ -272,6 +305,15 @@ export class EmitterBase {
272
305
  this.lines.splice(mark, 0, ...decl.map((l) => pad + l));
273
306
  return out;
274
307
  }
308
+ /** Whether a C line emitted from `mark` on assigns, increments or takes the address of the C variable `name`. */
309
+ writtenSince(name, mark) {
310
+ const n = name.replace(/\W/g, "");
311
+ const w = new RegExp(`(?:\\b${n}(?:\\.\\w+|\\[[^\\]]*\\])*\\s*(?:[-+*/%&|^]|<<|>>)?=(?!=)|&\\s*\\(?\\s*${n}\\b|\\b${n}\\s*(?:\\+\\+|--)|(?:\\+\\+|--)\\s*${n}\\b)`);
312
+ for (let i = mark; i < this.lines.length; i++)
313
+ if (this.lines[i].includes(n) && w.test(this.lines[i]))
314
+ return true;
315
+ return false;
316
+ }
275
317
  /** A string that stays valid when account data changes: views of account text are copied to the heap. */
276
318
  ownedString(v) {
277
319
  if (v.type.kind !== "string" || !v.c.startsWith("ts_fstr_view"))
@@ -368,6 +410,32 @@ export class EmitterBase {
368
410
  nativeAccountWrites() {
369
411
  return this.model.constants.get("NATIVE_ACCOUNT_WRITES")?.value === true;
370
412
  }
413
+ /**
414
+ * `const PANIC_STYLE = "solana-1.14"`: a Rust panic logs what solana_program 1.14's panic handler logs (rustc before
415
+ * 1.73 formats it as `panicked at '<message>', <file>:<line>:<col>`) and then aborts, so the runtime reports "SBF
416
+ * program panicked"; by default it logs the message and calls sol_panic_ with the location.
417
+ */
418
+ panicStyle() {
419
+ return this.model.constants.get("PANIC_STYLE")?.value === "solana-1.14" ? "solana-1.14" : undefined;
420
+ }
421
+ /** The C statements of a Rust panic with `message` (undefined: nothing logged) at `location` ("file:line:col"). */
422
+ panicC(message, location) {
423
+ if (this.panicStyle())
424
+ return [`sol_log(${cString(`panicked at '${message}', ${location}`)});`, `abort();`, `__builtin_unreachable();`];
425
+ const m = /^(.*?):(\d+)(?::(\d+))?$/.exec(location);
426
+ const [file, line, col] = m ? [m[1], m[2], m[3] ?? "0"] : [location, "0", "0"];
427
+ return [
428
+ ...(message !== undefined ? [`sol_log(${cString(message)});`] : []),
429
+ `sol_panic_(${cString(file)}, ${Buffer.byteLength(file)}, ${line}, ${col});`,
430
+ `__builtin_unreachable();`,
431
+ ];
432
+ }
433
+ /** `file.ts:line:column` of a node (1-based, as Rust reports a location). */
434
+ locationWithColumn(node) {
435
+ const sf = node.getSourceFile();
436
+ const lc = sf.getLineAndCharacterOfPosition(node.getStart(sf));
437
+ return `${sf.fileName.split("/").pop()}:${lc.line + 1}:${lc.character + 1}`;
438
+ }
371
439
  /** Whether `node` is an EpochRewards value: `epochRewards()` or a local holding one. */
372
440
  isEpochRewards(node) {
373
441
  if (ts.isParenthesizedExpression(node))
@@ -184,8 +184,11 @@ function codec(s, model, o) {
184
184
  ? borshMinSize(variableStruct(t, model), model)
185
185
  : fixedBytes(t, model);
186
186
  const minAfter = s.fields.map((_, i) => s.fields.slice(i + 1).reduce((n, f) => n + minOf(f.type), 0));
187
- const need = (n, rest, pad) => `${pad}if (${n} > len - at - ${rest}) ${DESER};`;
188
- const room = (n, rest, pad) => `${pad}if (${n} > cap - at - ${rest}) ${SER};`;
187
+ // Compared without a subtraction that could wrap: `at` may already be within `rest` of the end (a Some tag or a
188
+ // list element reserves only its own smallest form), and `len - at - rest` would then pass anything. `n` is at
189
+ // most 2^32 elements of at most a few KiB, `at` and `rest` stay near `len`: the sum cannot overflow 64 bits.
190
+ const need = (n, rest, pad) => `${pad}if ((uint64_t)(${n}) + at + ${rest} > len) ${DESER};`;
191
+ const room = (n, rest, pad) => `${pad}if ((uint64_t)(${n}) + at + ${rest} > cap) ${SER};`;
189
192
  // A String / Vec / Option field, `rest` bytes of later fields still to come.
190
193
  const unpackVar = (t, lv, rest, pad) => {
191
194
  switch (t.kind) {
@@ -227,12 +230,13 @@ function codec(s, model, o) {
227
230
  ...(check.length ? [`${pad}for (uint64_t ${i} = 0; ${i} < ${l}; ${i}++) {`, ...check, `${pad}}`] : []),
228
231
  ];
229
232
  }
230
- // Strings: each element's length prefix is checked as it is reached.
233
+ // Strings and structs holding Options: each element's smallest form is checked as it is reached (its length
234
+ // prefix, or its fixed fields and tags), before anything of it is read.
231
235
  const i = tmp("i");
232
236
  return [
233
237
  ...head,
234
238
  `${pad}for (uint64_t ${i} = 0; ${i} < ${l}; ${i}++) {`,
235
- need("4", rest, `${pad} `),
239
+ need(String(minOf(t.elem)), rest, `${pad} `),
236
240
  ...unpackVar(t.elem, `${lv}.items[${i}]`, rest, `${pad} `),
237
241
  `${pad}}`,
238
242
  ];
@@ -263,6 +267,8 @@ function codec(s, model, o) {
263
267
  `${pad}if (${tag} > 1) ${DESER};`,
264
268
  `${pad}${lv}.some = ${tag};`,
265
269
  `${pad}if (${tag}) {`,
270
+ // The tag reserved one byte: the struct's smallest form must be there before its fields are read.
271
+ need(String(minOf(t.inner)), rest, `${pad} `),
266
272
  ...unpackVar(t.inner, `${lv}.v`, rest, `${pad} `),
267
273
  `${pad}}`,
268
274
  ];
@@ -305,7 +311,7 @@ function codec(s, model, o) {
305
311
  for (const f of v.fields) {
306
312
  const flv = `${lv}.v.${v.name}.${f.name}`;
307
313
  if (f.type.kind === "string") {
308
- lines.push(`${pad} if (4 > len - at - ${rest}) ${DESER};`, ...unpackVar(f.type, flv, rest, `${pad} `));
314
+ lines.push(need("4", rest, `${pad} `), ...unpackVar(f.type, flv, rest, `${pad} `));
309
315
  continue;
310
316
  }
311
317
  const n = fixedBytes(f.type, model);
@@ -123,6 +123,28 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
123
123
  * from byte 0, checked as a `#[repr(C)]` type's load_checked does: this program's (3007), large enough (3003).
124
124
  */
125
125
  protected loadRaw(node: ts.CallExpression, mut: boolean): Value;
126
+ /**
127
+ * A native account view's owner check (3007). In a program that makes such views the check goes through ts_owned: the
128
+ * last account found this program's passes with a pointer compare until a CPI or an owner write forgets it.
129
+ */
130
+ protected viewOwnerCheck(h: string): string;
131
+ /** An owner write or a CPI: the owner checks' cache (viewOwnerCheck) is forgotten. */
132
+ protected forgetOwners(): void;
133
+ /**
134
+ * The account a loadRaw-style view reads (its first argument): a remaining account, or an AccountInfo parameter of
135
+ * the instruction (`param`: its position, for the claim). `fn` names the call in messages.
136
+ */
137
+ protected rawAccount(node: ts.CallExpression, fn: string, mut: boolean): {
138
+ h: string;
139
+ param?: number;
140
+ };
141
+ /**
142
+ * A writable view's checks: the account is writable and loaded mutably once in the instruction (2040).
143
+ * NATIVE_ACCOUNT_WRITES: no writability check and no claim. The view writes in place; the runtime refuses the
144
+ * instruction if a read-only account's data changed, and two views of one account share its bytes (the loader
145
+ * gives a duplicate the same record), as two AccountInfos of one account share one buffer in Rust.
146
+ */
147
+ protected claimRawMut(node: ts.CallExpression, h: string, param: number | undefined): void;
126
148
  /**
127
149
  * `const v = loadBorsh<T>(acct)`: the account's data from byte 0 decoded as Borsh into a local `T` (a copy), as
128
150
  * `try_from_slice_unchecked` reads it: no owner check, no discriminator, trailing bytes ignored; bytes that are not
@@ -139,8 +161,20 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
139
161
  private borshNativeStruct;
140
162
  /** The account loadBorsh reads or storeBorsh writes (writable: checked at run time, or Mut<AccountInfo>). */
141
163
  private borshAccount;
164
+ /**
165
+ * An account `closeRaw` / `assignOwner` writes in place: a remaining account (a helper's RemainingAccount, a ternary
166
+ * between them) or an AccountInfo parameter. Without NATIVE_ACCOUNT_WRITES it is checked as the other writes to
167
+ * accounts the compiler cannot see are: writable (3006; a parameter must be Mut<AccountInfo>), passed once (2040), and
168
+ * for `owned` this program's (3007). With the flag nothing is checked: the runtime judges the result, as it judges a
169
+ * native program's.
170
+ */
171
+ protected inPlaceAccount(node: ts.Expression, what: string, owned: boolean): string;
142
172
  /** `TS_FAIL` with a built-in ProgramError (no custom code), logged as `require(…, ProgramError.X)` logs it. */
143
173
  protected programErrorFail(name: string, node: ts.Node): string;
174
+ /** A failure with a built-in ProgramError's code: logged with `text`, or nothing under `PROGRAM_ERROR_LOG_PREFIX = null`. */
175
+ protected programFail(code: string, text: string): string;
176
+ /** `const ERROR_LOG_PREFIX = null`: the program's own errors (and codes returned by its helpers) log nothing. */
177
+ protected quietErrors(): boolean;
144
178
  /** `loadAccount<T>(acct)` / `loadAccountMut<T>(acct)`: checked view of a program account. */
145
179
  protected loadAccount(node: ts.CallExpression, mut: boolean): Value;
146
180
  /**
@@ -151,6 +185,18 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
151
185
  protected migrate(node: ts.CallExpression, a: AccountParam, topLevel: boolean): Value | undefined;
152
186
  /** Whether a helper (or one it calls) grows a Vec, which needs the instruction's SystemProgram for rent. */
153
187
  private helperGrows;
188
+ /**
189
+ * After close(acct, dest) the account holds no data and belongs to the System Program: reading or writing it later in
190
+ * the function (or on a later turn of a loop around the close) would read zeros or write bytes that are dropped. The
191
+ * same holds for a reference into it read later. Refused, like a view used after closeRaw (assertNoViewAfter).
192
+ */
193
+ protected assertNotUsedAfterClose(a: AccountParam, at: ts.CallExpression): void;
194
+ /** Whether a helper's body (or a helper it calls) closes or resizes an account: closeRaw / resizeAccount. */
195
+ private helperResizes;
196
+ /** Whether a helper's body (or a helper it calls) makes a writable tree view, which may change a tree's structure. */
197
+ private helperMakesMutTree;
198
+ /** Whether a helper's body (or a helper it calls) calls one of these built-ins. */
199
+ private helperCalls;
154
200
  /**
155
201
  * A helper given a closure (a function that reads the caller's variables) for a function parameter: a closure only
156
202
  * runs where it is declared, so the helper is expanded here, like a closure, with the closure bound to the
@@ -169,8 +215,31 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
169
215
  /** A function given for a function parameter of an expanded helper or closure, as something to expand. */
170
216
  protected closureOf(arg: ts.Expression): Closure;
171
217
  protected callHelper(node: ts.CallExpression, h: Helper): Value | undefined;
218
+ /**
219
+ * A Pubkey, Option, string or u256 helper argument, passed as a pointer (see passedByPointer). When the helper can
220
+ * write (it takes accounts or Inout places) and the argument is not a named C object nothing passed can reach (see
221
+ * unreachableArg), the pointer is to a copy taken here: JS gives the helper the value as it is at the call. A
222
+ * helper that writes nothing reads the caller's value in place.
223
+ */
224
+ protected pointerArg(v: Value, mayWrite: boolean): string;
172
225
  /** One helper argument: a C argument list fragment (accounts, seeds, references) or a value to settle. */
173
226
  protected helperArg(h: Helper, p: Helper["params"][number], n: ts.Expression): Value | string;
227
+ /**
228
+ * An `Inout<T>` argument: a pointer to the caller's place itself (never a copy), which must be writable. A literal
229
+ * (`f({ … })`, `fixedArray(…)`) is built in a local of its own, as JS passes a fresh object; a ternary must pick
230
+ * between two places (a literal branch would be a copy the helper's writes never reach).
231
+ */
232
+ protected inoutArg(h: Helper, p: Helper["params"][number], n: ts.Expression): string;
233
+ /**
234
+ * The rules of a call with `Inout<T>` arguments, so the helper's pointer is the only way to the place while it runs
235
+ * (Rust's one `&mut` at a time) and stays valid: no other argument may share storage with an Inout one (two places,
236
+ * one inside the other, the same list's elements whatever their indexes, an account and a place in it); a place in
237
+ * a list whose elements can move is refused when the call may move them; a reference into the place read after the
238
+ * call is refused (the helper may replace what it points at). Places whose roots differ but may be the same bytes at
239
+ * run time (two `Dup<…>` accounts, two loadRawMut views under NATIVE_ACCOUNT_WRITES, a helper's account parameters)
240
+ * are compared at run time (2040).
241
+ */
242
+ protected checkInoutCall(node: ts.CallExpression, h: Helper, argNodes: readonly ts.Expression[], passed: (string | undefined)[]): void;
174
243
  /**
175
244
  * A struct, array or data-enum helper argument written as a literal (`f({ a: 1n, b: { c } })`, `g([1n, 2n])`, or a
176
245
  * ternary with a literal branch): built in a local of its own, as `const x: T = { … }; f(x)` would, and passed by
@@ -182,6 +251,17 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
182
251
  * copy taken at the call (JS passes the object as it was); other helpers cannot write, so a pointer is enough.
183
252
  */
184
253
  protected snapshotPlace(lv: string, type: FieldType, h: Helper, node?: ts.Expression): string;
254
+ /**
255
+ * A FixedVec or FixedArray of `elem` given for a read-only list parameter: a `TS_VecArg` view of its elements (the
256
+ * length as it is at the call). A list this function holds (a local, a field of a struct it owns) is read in place;
257
+ * one in account data is copied first when the helper takes accounts, as a struct argument is (the helper may write
258
+ * the account). Undefined when `n` is not such a list.
259
+ */
260
+ protected listViewArg(n: ts.Expression, want: ValueType & {
261
+ kind: "vecArg";
262
+ }, h: Helper): string | undefined;
263
+ /** Whether `node` is a list this function holds on its stack (a local list, a field of a struct it owns), not account data. */
264
+ protected callerHoldsList(node: ts.Expression): boolean;
185
265
  /** Whether `node` is (part of) a struct value this function owns: `h`, `h.inner`, `h.list.get(i)`. */
186
266
  protected ownedRoot(node: ts.Expression): boolean;
187
267
  /** `signer([...seeds])` (one PDA signature), or a SignerSeeds parameter passed on. */