@typesol/cli 0.42.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.
- package/CHANGELOG.md +227 -0
- package/README.md +10 -7
- package/dist/compiler/analyze.js +443 -12
- package/dist/compiler/diagnostics.d.ts +1 -0
- package/dist/compiler/diagnostics.js +13 -0
- package/dist/compiler/emit/alias.d.ts +44 -0
- package/dist/compiler/emit/alias.js +135 -4
- package/dist/compiler/emit/base.d.ts +25 -0
- package/dist/compiler/emit/base.js +58 -7
- package/dist/compiler/emit/calls.d.ts +67 -0
- package/dist/compiler/emit/calls.js +521 -46
- package/dist/compiler/emit/cpi-core.d.ts +20 -3
- package/dist/compiler/emit/cpi-core.js +226 -5
- package/dist/compiler/emit/cpi.js +8 -2
- package/dist/compiler/emit/expressions.js +38 -7
- package/dist/compiler/emit/program.js +30 -1
- package/dist/compiler/emit/rbtree.d.ts +7 -0
- package/dist/compiler/emit/rbtree.js +142 -0
- package/dist/compiler/emit/shared.d.ts +8 -0
- package/dist/compiler/emit/shared.js +9 -1
- package/dist/compiler/emit/statements.d.ts +27 -1
- package/dist/compiler/emit/statements.js +288 -19
- package/dist/compiler/emit/storage.d.ts +23 -2
- package/dist/compiler/emit/storage.js +100 -56
- package/dist/compiler/emit/token.js +2 -2
- package/dist/compiler/emit/views.d.ts +60 -0
- package/dist/compiler/emit/views.js +523 -0
- package/dist/compiler/idl.js +2 -1
- package/dist/compiler/model.d.ts +65 -4
- package/dist/compiler/model.js +14 -0
- package/dist/compiler/toolchain.d.ts +15 -0
- package/dist/compiler/toolchain.js +146 -11
- package/docs/architecture.md +9 -2
- package/docs/case-study-phoenix.md +226 -0
- package/docs/language.md +139 -8
- package/docs/migrate-from-anchor.md +1 -0
- package/docs/runtime.md +1 -1
- package/docs/stability.md +21 -2
- package/docs/troubleshooting.md +5 -2
- package/lib/typesol.d.ts +221 -4
- package/llms-full.txt +169 -14
- package/llms.txt +1 -1
- package/package.json +2 -2
- package/runtime/typesol_rt.h +407 -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[]"],
|
|
@@ -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;;) {
|
|
@@ -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. */
|
|
@@ -120,6 +125,16 @@ export declare abstract class EmitterBase {
|
|
|
120
125
|
* once (2040) up front.
|
|
121
126
|
*/
|
|
122
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;
|
|
123
138
|
/** Whether `node` is an EpochRewards value: `epochRewards()` or a local holding one. */
|
|
124
139
|
protected isEpochRewards(node: ts.Expression): boolean;
|
|
125
140
|
/**
|
|
@@ -186,8 +201,18 @@ export declare abstract class EmitterBase {
|
|
|
186
201
|
protected abstract expandClosure(c: Closure, args: readonly ts.Expression[], node: ts.Node): Value | undefined;
|
|
187
202
|
protected abstract callChoice(choice: FunctionChoice, args: readonly ts.Expression[], node: ts.Node): Value | undefined;
|
|
188
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;
|
|
189
206
|
protected abstract programErrorFail(name: string, node: ts.Node): string;
|
|
190
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;
|
|
191
216
|
protected abstract closureOf(arg: ts.Expression): Closure;
|
|
192
217
|
/** The arguments and accounts code written here can name (what a closure written here keeps). */
|
|
193
218
|
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, } 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,44 @@ 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 });
|
|
100
125
|
else
|
|
101
|
-
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 : {}) });
|
|
102
127
|
}
|
|
103
128
|
}
|
|
104
129
|
}
|
|
@@ -368,6 +393,32 @@ export class EmitterBase {
|
|
|
368
393
|
nativeAccountWrites() {
|
|
369
394
|
return this.model.constants.get("NATIVE_ACCOUNT_WRITES")?.value === true;
|
|
370
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
|
+
}
|
|
371
422
|
/** Whether `node` is an EpochRewards value: `epochRewards()` or a local holding one. */
|
|
372
423
|
isEpochRewards(node) {
|
|
373
424
|
if (ts.isParenthesizedExpression(node))
|
|
@@ -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,12 @@ 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
|
+
/** Whether a helper's body (or a helper it calls) closes or resizes an account: closeRaw / resizeAccount. */
|
|
189
|
+
private helperResizes;
|
|
190
|
+
/** Whether a helper's body (or a helper it calls) makes a writable tree view, which may change a tree's structure. */
|
|
191
|
+
private helperMakesMutTree;
|
|
192
|
+
/** Whether a helper's body (or a helper it calls) calls one of these built-ins. */
|
|
193
|
+
private helperCalls;
|
|
154
194
|
/**
|
|
155
195
|
* A helper given a closure (a function that reads the caller's variables) for a function parameter: a closure only
|
|
156
196
|
* runs where it is declared, so the helper is expanded here, like a closure, with the closure bound to the
|
|
@@ -171,6 +211,22 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
|
|
|
171
211
|
protected callHelper(node: ts.CallExpression, h: Helper): Value | undefined;
|
|
172
212
|
/** One helper argument: a C argument list fragment (accounts, seeds, references) or a value to settle. */
|
|
173
213
|
protected helperArg(h: Helper, p: Helper["params"][number], n: ts.Expression): Value | string;
|
|
214
|
+
/**
|
|
215
|
+
* An `Inout<T>` argument: a pointer to the caller's place itself (never a copy), which must be writable. A literal
|
|
216
|
+
* (`f({ … })`, `fixedArray(…)`) is built in a local of its own, as JS passes a fresh object; a ternary must pick
|
|
217
|
+
* between two places (a literal branch would be a copy the helper's writes never reach).
|
|
218
|
+
*/
|
|
219
|
+
protected inoutArg(h: Helper, p: Helper["params"][number], n: ts.Expression): string;
|
|
220
|
+
/**
|
|
221
|
+
* The rules of a call with `Inout<T>` arguments, so the helper's pointer is the only way to the place while it runs
|
|
222
|
+
* (Rust's one `&mut` at a time) and stays valid: no other argument may share storage with an Inout one (two places,
|
|
223
|
+
* one inside the other, the same list's elements whatever their indexes, an account and a place in it); a place in
|
|
224
|
+
* a list whose elements can move is refused when the call may move them; a reference into the place read after the
|
|
225
|
+
* call is refused (the helper may replace what it points at). Places whose roots differ but may be the same bytes at
|
|
226
|
+
* run time (two `Dup<…>` accounts, two loadRawMut views under NATIVE_ACCOUNT_WRITES, a helper's account parameters)
|
|
227
|
+
* are compared at run time (2040).
|
|
228
|
+
*/
|
|
229
|
+
protected checkInoutCall(node: ts.CallExpression, h: Helper, argNodes: readonly ts.Expression[], passed: (string | undefined)[]): void;
|
|
174
230
|
/**
|
|
175
231
|
* A struct, array or data-enum helper argument written as a literal (`f({ a: 1n, b: { c } })`, `g([1n, 2n])`, or a
|
|
176
232
|
* ternary with a literal branch): built in a local of its own, as `const x: T = { … }; f(x)` would, and passed by
|
|
@@ -182,6 +238,17 @@ export declare abstract class CallEmitter extends ExpressionEmitter {
|
|
|
182
238
|
* copy taken at the call (JS passes the object as it was); other helpers cannot write, so a pointer is enough.
|
|
183
239
|
*/
|
|
184
240
|
protected snapshotPlace(lv: string, type: FieldType, h: Helper, node?: ts.Expression): string;
|
|
241
|
+
/**
|
|
242
|
+
* A FixedVec or FixedArray of `elem` given for a read-only list parameter: a `TS_VecArg` view of its elements (the
|
|
243
|
+
* 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;
|
|
244
|
+
* one in account data is copied first when the helper takes accounts, as a struct argument is (the helper may write
|
|
245
|
+
* the account). Undefined when `n` is not such a list.
|
|
246
|
+
*/
|
|
247
|
+
protected listViewArg(n: ts.Expression, want: ValueType & {
|
|
248
|
+
kind: "vecArg";
|
|
249
|
+
}, h: Helper): string | undefined;
|
|
250
|
+
/** Whether `node` is a list this function holds on its stack (a local list, a field of a struct it owns), not account data. */
|
|
251
|
+
protected callerHoldsList(node: ts.Expression): boolean;
|
|
185
252
|
/** Whether `node` is (part of) a struct value this function owns: `h`, `h.inner`, `h.list.get(i)`. */
|
|
186
253
|
protected ownedRoot(node: ts.Expression): boolean;
|
|
187
254
|
/** `signer([...seeds])` (one PDA signature), or a SignerSeeds parameter passed on. */
|