@typesol/cli 0.27.0 → 0.29.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 +43 -0
- package/README.md +3 -1
- package/dist/compiler/analyze.d.ts +5 -1
- package/dist/compiler/analyze.js +53 -15
- package/dist/compiler/emit/alias.d.ts +48 -0
- package/dist/compiler/emit/alias.js +166 -0
- package/dist/compiler/emit/base.d.ts +1 -0
- package/dist/compiler/emit/borsh.js +6 -3
- package/dist/compiler/emit/calls.js +23 -4
- package/dist/compiler/emit/cpi-core.d.ts +70 -0
- package/dist/compiler/emit/cpi-core.js +356 -0
- package/dist/compiler/emit/cpi.d.ts +10 -175
- package/dist/compiler/emit/cpi.js +71 -2716
- package/dist/compiler/emit/create.d.ts +39 -0
- package/dist/compiler/emit/create.js +548 -0
- package/dist/compiler/emit/function.d.ts +11 -2
- package/dist/compiler/emit/function.js +55 -12
- package/dist/compiler/emit/metaplex.d.ts +78 -0
- package/dist/compiler/emit/metaplex.js +1345 -0
- package/dist/compiler/emit/program.js +24 -4
- package/dist/compiler/emit/shared.d.ts +5 -1
- package/dist/compiler/emit/shared.js +11 -2
- package/dist/compiler/emit/statements.d.ts +0 -9
- package/dist/compiler/emit/statements.js +2 -53
- package/dist/compiler/emit/storage.d.ts +5 -20
- package/dist/compiler/emit/storage.js +55 -100
- package/dist/compiler/emit/token.d.ts +8 -0
- package/dist/compiler/emit/token.js +493 -0
- package/dist/compiler/idl.js +1 -1
- package/dist/compiler/model.d.ts +12 -2
- package/dist/compiler/model.js +7 -1
- package/dist/tools/portgen.js +3 -0
- package/docs/architecture.md +31 -2
- package/docs/audit.md +4 -2
- package/docs/case-study-multisig.md +169 -0
- package/docs/errors.md +6 -4
- package/docs/language.md +22 -6
- package/docs/migrate-from-anchor.md +7 -2
- package/docs/security-model.md +5 -1
- package/lib/typesol.d.ts +51 -7
- package/package.json +1 -1
- package/runtime/typesol_rt.h +93 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { accountLimit, cBytes, scalarStorageC, optC, storageDecl, helperSignature, fieldC, fixedVecC, laterVecC } from "./shared.js";
|
|
2
2
|
import { FunctionEmitter } from "./function.js";
|
|
3
3
|
import { emitBorshCodecs } from "./borsh.js";
|
|
4
4
|
/**
|
|
@@ -39,6 +39,14 @@ export function emitProgram(analysis, opts = {}) {
|
|
|
39
39
|
else
|
|
40
40
|
out.push(`#define TS_HEAP_LENGTH (${heap.value}ULL * 1024)`);
|
|
41
41
|
}
|
|
42
|
+
// `const MAX_ACCOUNTS = 64n`: instructions take up to that many accounts (32 otherwise, at most 255).
|
|
43
|
+
const maxAccounts = model.constants.get("MAX_ACCOUNTS");
|
|
44
|
+
if (maxAccounts) {
|
|
45
|
+
if (typeof maxAccounts.value !== "bigint" || maxAccounts.value < 32n || maxAccounts.value > 255n)
|
|
46
|
+
reporter.error(analysis.sourceFile, "MAX_ACCOUNTS must be an integer from 32 to 255 (accounts one instruction takes)");
|
|
47
|
+
else if (maxAccounts.value > 32n)
|
|
48
|
+
out.push(`#define TS_MAX_ACCOUNTS ${maxAccounts.value}`);
|
|
49
|
+
}
|
|
42
50
|
out.push(`#include "typesol_rt.h"`, "");
|
|
43
51
|
for (const inner of model.options.values())
|
|
44
52
|
if (inner.kind !== "struct")
|
|
@@ -60,6 +68,14 @@ export function emitProgram(analysis, opts = {}) {
|
|
|
60
68
|
emitted.add(name);
|
|
61
69
|
out.push(`typedef struct __attribute__((packed)) {`, ` uint32_t len;`, ` ${storageDecl(t.elem, `items[${t.cap}]`)};`, `} ${name};`, "");
|
|
62
70
|
}
|
|
71
|
+
// A heap Vec (in a @layout borsh struct): its length, its capacity and its elements on the heap (ts_hvec_reserve).
|
|
72
|
+
if (t.kind === "vec" && t.heap) {
|
|
73
|
+
const name = fieldC(t);
|
|
74
|
+
if (emitted.has(name))
|
|
75
|
+
return;
|
|
76
|
+
emitted.add(name);
|
|
77
|
+
out.push(`typedef struct __attribute__((packed)) {`, ` uint32_t len;`, ` uint32_t cap;`, ` ${storageDecl(t.elem, `*items`)};`, `} ${name};`, "");
|
|
78
|
+
}
|
|
63
79
|
if (t.kind === "option" && t.inner.kind === "struct") {
|
|
64
80
|
const key = `opt:${t.inner.name}`;
|
|
65
81
|
if (emitted.has(key))
|
|
@@ -130,16 +146,20 @@ export function emitProgram(analysis, opts = {}) {
|
|
|
130
146
|
if (helpers.length)
|
|
131
147
|
out.push("");
|
|
132
148
|
out.push(...helperBodies, ...ixBodies);
|
|
133
|
-
|
|
149
|
+
const limit = accountLimit(model);
|
|
150
|
+
out.push(`_Static_assert(TS_MAX_ACCOUNTS == ${limit}, "TS_MAX_ACCOUNTS");`);
|
|
134
151
|
out.push(`extern uint64_t entrypoint(const uint8_t *input) {`);
|
|
135
152
|
out.push(` TsParams params; /* filled in by ts_deserialize */`);
|
|
136
153
|
// Clamping the count to what fits would make extra accounts silently vanish from remainingAccounts():
|
|
137
154
|
// refuse more than the array holds instead (ts_deserialize relies on this bound).
|
|
138
|
-
out.push(` if (*(const uint64_t *)input > TS_MAX_ACCOUNTS) TS_FAIL(TS_ERR_TOO_MANY_ACCOUNTS, "TypeSOL: at most ${
|
|
155
|
+
out.push(` if (*(const uint64_t *)input > TS_MAX_ACCOUNTS) TS_FAIL(TS_ERR_TOO_MANY_ACCOUNTS, "TypeSOL: at most ${limit} accounts per instruction");`);
|
|
139
156
|
out.push(` ts_deserialize(input, ¶ms);`);
|
|
140
157
|
// loadAccountMut's record of the accounts it loaded: set up only in programs that use it (one store otherwise wasted).
|
|
158
|
+
// Above 32 accounts the CPI scratch lists are taken from the heap when first needed.
|
|
159
|
+
if (limit > 32)
|
|
160
|
+
out.push(` params.infos_cap = 0;`, ` params.metas = NULL;`);
|
|
141
161
|
if ([...helperBodies, ...ixBodies].some((b) => b.includes("ts_claim_mut(")))
|
|
142
|
-
out.push(` params.loaded_mut = 0;`);
|
|
162
|
+
out.push(limit > 64 ? ` ts_memzero(params.loaded_mut, sizeof(params.loaded_mut));` : ` params.loaded_mut = 0;`);
|
|
143
163
|
const minDisc = Math.min(8, ...model.instructions.map((ix) => ix.discriminator.length));
|
|
144
164
|
out.push(` if (params.data_len < ${minDisc}) TS_FAIL(TS_ERR_INSTRUCTION_MISSING, "TypeSOL: instruction data too short");`);
|
|
145
165
|
// Self-CPI events (emitCpi): accept the event instruction when its authority PDA signed it, like Anchor.
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
|
-
import { type AccountParam, type FieldType, type Helper, type IntName, type ParamKind, type ScalarType, type StructDef, type ValueType } from "../model.js";
|
|
2
|
+
import { type AccountParam, type FieldType, type ProgramModel, type Helper, type IntName, type ParamKind, type ScalarType, type StructDef, type ValueType } from "../model.js";
|
|
3
3
|
/** Maximum accounts the generated entrypoint deserializes. */
|
|
4
4
|
export declare const MAX_ACCOUNTS = 32;
|
|
5
|
+
/** The most accounts one instruction takes: 32, or what the program declares with `const MAX_ACCOUNTS = …n` (33–255). */
|
|
6
|
+
export declare function accountLimit(model: Pick<ProgramModel, "constants">): number;
|
|
5
7
|
export declare const MAX_SEEDS = 15;
|
|
6
8
|
/** Max instruction data an invoke() may build, and max event payload. */
|
|
7
9
|
export declare const MAX_CPI_DATA = 1024;
|
|
@@ -52,6 +54,8 @@ export interface Ref {
|
|
|
52
54
|
elemSize: number;
|
|
53
55
|
resizable: boolean;
|
|
54
56
|
cap?: number;
|
|
57
|
+
/** A heap Vec (in a `@layout borsh` struct): `cap` is the C lvalue of its capacity, grown by ts_hvec_reserve. */
|
|
58
|
+
heap?: boolean;
|
|
55
59
|
/** Growable Vecs stored after this one move when it grows or shrinks: where its elements end, and their paths. */
|
|
56
60
|
tail?: {
|
|
57
61
|
end: string;
|
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
import { INT_INFO, fixedVecName, isWritable, optionKey, } from "../model.js";
|
|
1
|
+
import { INT_INFO, fixedVecName, heapVecName, isWritable, optionKey, } from "../model.js";
|
|
2
2
|
// Types, limits and C type helpers shared by the emitter modules.
|
|
3
3
|
/** Maximum accounts the generated entrypoint deserializes. */
|
|
4
4
|
export const MAX_ACCOUNTS = 32;
|
|
5
|
+
/** The most accounts one instruction takes: 32, or what the program declares with `const MAX_ACCOUNTS = …n` (33–255). */
|
|
6
|
+
export function accountLimit(model) {
|
|
7
|
+
const c = model.constants.get("MAX_ACCOUNTS");
|
|
8
|
+
return c && typeof c.value === "bigint" && c.value >= 32n && c.value <= 255n ? Number(c.value) : MAX_ACCOUNTS;
|
|
9
|
+
}
|
|
5
10
|
export const MAX_SEEDS = 15; // + bump = 16, the runtime limit
|
|
6
11
|
/** Max instruction data an invoke() may build, and max event payload. */
|
|
7
12
|
export const MAX_CPI_DATA = 1024;
|
|
@@ -95,6 +100,8 @@ export function fieldC(t) {
|
|
|
95
100
|
case "vec":
|
|
96
101
|
if (t.cap !== undefined)
|
|
97
102
|
return fixedVecC(t);
|
|
103
|
+
if (t.heap)
|
|
104
|
+
return heapVecName(t);
|
|
98
105
|
throw new Error("unreachable: a Vec is never an element");
|
|
99
106
|
default:
|
|
100
107
|
throw new Error(`unreachable: no element C type for ${t.kind}`);
|
|
@@ -124,6 +131,8 @@ export function storageDecl(t, name) {
|
|
|
124
131
|
case "vec":
|
|
125
132
|
if (t.cap !== undefined)
|
|
126
133
|
return `${fixedVecC(t)} ${name}`;
|
|
134
|
+
if (t.heap)
|
|
135
|
+
return `${heapVecName(t)} ${name}`;
|
|
127
136
|
// Borsh Vec as a trailing flexible array: u32 length, then the elements.
|
|
128
137
|
return `uint32_t ${name}__len;
|
|
129
138
|
${storageDecl(t.elem, `${name}[]`)}`;
|
|
@@ -254,5 +263,5 @@ export function fixedVecC(t) {
|
|
|
254
263
|
}
|
|
255
264
|
/** The element count of a Vec place to read: a FixedVec's stored length is clamped to its capacity. */
|
|
256
265
|
export function vecCount(v) {
|
|
257
|
-
return v.cap === undefined ? `((uint64_t)${v.len})` : `((uint64_t)(${v.len} < ${v.cap} ? ${v.len} : ${v.cap}))`;
|
|
266
|
+
return v.cap === undefined || v.heap ? `((uint64_t)${v.len})` : `((uint64_t)(${v.len} < ${v.cap} ? ${v.len} : ${v.cap}))`;
|
|
258
267
|
}
|
|
@@ -90,13 +90,4 @@ export declare abstract class StatementEmitter extends CpiEmitter {
|
|
|
90
90
|
protected destructure(list: ts.VariableDeclarationList, d: ts.VariableDeclaration, pattern: ts.ObjectBindingPattern, init: ts.Expression, topLevel: boolean): void;
|
|
91
91
|
protected expressionStatement(e: ts.Expression, topLevel: boolean): void;
|
|
92
92
|
protected assign(target: ts.Expression, valueNode: ts.Expression, op?: ts.BinaryOperator, topLevel?: boolean): void;
|
|
93
|
-
/** Whether a place goes through a Vec element (`v.get(i).x`, `v.get(i)`). */
|
|
94
|
-
protected writesThroughVec(node: ts.Expression): boolean;
|
|
95
|
-
protected helperTakesMutAccounts(node: ts.CallExpression): boolean;
|
|
96
|
-
/**
|
|
97
|
-
* Whether evaluating `node` may resize a growable Vec (and so move the Vecs after it): a push / pop / clear, a
|
|
98
|
-
* realloc or close, a helper taking a writable account or a function argument, or a closure (its body is not
|
|
99
|
-
* looked into: it may capture the account). Conservative: it only decides whether a Vec element may be the target.
|
|
100
|
-
*/
|
|
101
|
-
protected mayResizeVecs(node: ts.Node): boolean;
|
|
102
93
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
2
|
import { MAX_RETURN_DATA, calleeName, resolveScalarType, resolveValueType, structNameOf, typesolName } from "../analyze.js";
|
|
3
|
-
import { INT_INFO, isScalar,
|
|
3
|
+
import { INT_INFO, isScalar, optionKey, scalarSize, typeName } from "../model.js";
|
|
4
4
|
import { U64, BOOL, cString, fixedVecC, optC, scalarC, scalarStorageC, valueC } from "./shared.js";
|
|
5
5
|
import { CpiEmitter } from "./cpi.js";
|
|
6
6
|
/**
|
|
@@ -1153,7 +1153,7 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1153
1153
|
(targetRef.type.kind === "array" ||
|
|
1154
1154
|
targetRef.type.kind === "struct" ||
|
|
1155
1155
|
targetRef.type.kind === "dataEnum" ||
|
|
1156
|
-
(targetRef.type.kind === "vec" && targetRef.type.cap !== undefined) ||
|
|
1156
|
+
(targetRef.type.kind === "vec" && (targetRef.type.cap !== undefined || !!targetRef.type.heap)) ||
|
|
1157
1157
|
(targetRef.type.kind === "option" && targetRef.type.inner.kind === "struct"))) {
|
|
1158
1158
|
if (!targetRef.writable)
|
|
1159
1159
|
this.fail(target, this.readOnly(targetRef));
|
|
@@ -1173,55 +1173,4 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1173
1173
|
value = this.ownedString(value);
|
|
1174
1174
|
this.line(place.write(value.c) + ";");
|
|
1175
1175
|
}
|
|
1176
|
-
/** Whether a place goes through a Vec element (`v.get(i).x`, `v.get(i)`). */
|
|
1177
|
-
writesThroughVec(node) {
|
|
1178
|
-
for (let n = node;;) {
|
|
1179
|
-
if (ts.isParenthesizedExpression(n))
|
|
1180
|
-
n = n.expression;
|
|
1181
|
-
else if (ts.isPropertyAccessExpression(n))
|
|
1182
|
-
n = n.expression;
|
|
1183
|
-
else if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression) && n.expression.name.text === "get") {
|
|
1184
|
-
if (this.peekKind(n.expression.expression) === "vec")
|
|
1185
|
-
return true;
|
|
1186
|
-
n = n.expression.expression;
|
|
1187
|
-
}
|
|
1188
|
-
else
|
|
1189
|
-
return false;
|
|
1190
|
-
}
|
|
1191
|
-
}
|
|
1192
|
-
helperTakesMutAccounts(node) {
|
|
1193
|
-
const h = this.helperOf(node);
|
|
1194
|
-
return !!h?.params.some((p) => p.account && isWritable(p.account));
|
|
1195
|
-
}
|
|
1196
|
-
/**
|
|
1197
|
-
* Whether evaluating `node` may resize a growable Vec (and so move the Vecs after it): a push / pop / clear, a
|
|
1198
|
-
* realloc or close, a helper taking a writable account or a function argument, or a closure (its body is not
|
|
1199
|
-
* looked into: it may capture the account). Conservative: it only decides whether a Vec element may be the target.
|
|
1200
|
-
*/
|
|
1201
|
-
mayResizeVecs(node) {
|
|
1202
|
-
let found = false;
|
|
1203
|
-
const isClosure = (e) => ts.isArrowFunction(e) || ts.isFunctionExpression(e) || (ts.isIdentifier(e) && !!this.lookup(e.text)?.closure);
|
|
1204
|
-
const visit = (n) => {
|
|
1205
|
-
if (found)
|
|
1206
|
-
return;
|
|
1207
|
-
if (ts.isCallExpression(n)) {
|
|
1208
|
-
const callee = n.expression;
|
|
1209
|
-
if (ts.isPropertyAccessExpression(callee) && ["push", "pop", "clear"].includes(callee.name.text))
|
|
1210
|
-
found = true;
|
|
1211
|
-
else if (ts.isCallExpression(callee))
|
|
1212
|
-
found = true; // a function a function returns
|
|
1213
|
-
else if (ts.isIdentifier(callee)) {
|
|
1214
|
-
if (this.lookup(callee.text)?.closure)
|
|
1215
|
-
found = true;
|
|
1216
|
-
else if (["realloc", "close"].includes(this.exportName(callee) ?? ""))
|
|
1217
|
-
found = true;
|
|
1218
|
-
else if (this.helperOf(n) && (this.helperTakesMutAccounts(n) || n.arguments.some(isClosure)))
|
|
1219
|
-
found = true;
|
|
1220
|
-
}
|
|
1221
|
-
}
|
|
1222
|
-
ts.forEachChild(n, visit);
|
|
1223
|
-
};
|
|
1224
|
-
visit(node);
|
|
1225
|
-
return found;
|
|
1226
|
-
}
|
|
1227
1176
|
}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
2
|
import { type FieldType, type Helper, type ValueType } from "../model.js";
|
|
3
3
|
import { type Value, type Ref } from "./shared.js";
|
|
4
|
-
import {
|
|
4
|
+
import { AliasEmitter } from "./alias.js";
|
|
5
5
|
/**
|
|
6
6
|
* Places in account data and locals: references, reads and writes, Vec/array indexing, aliasing rules and
|
|
7
7
|
* argument validation.
|
|
8
8
|
*/
|
|
9
|
-
export declare abstract class StorageEmitter extends
|
|
9
|
+
export declare abstract class StorageEmitter extends AliasEmitter {
|
|
10
10
|
protected abstract callHelper(node: ts.CallExpression, h: Helper): Value | undefined;
|
|
11
11
|
/** C lines rejecting malformed fixed-layout data at `lv`: bools, enums, option tags, string lengths, enum tags. */
|
|
12
12
|
protected validation(lv: string, t: FieldType, pad: string, fail?: string): string[];
|
|
@@ -16,23 +16,6 @@ export declare abstract class StorageEmitter extends EmitterBase {
|
|
|
16
16
|
protected kindOf(node: ts.Expression): Ref | undefined;
|
|
17
17
|
protected looksLikeDataEnum(node: ts.Expression): boolean;
|
|
18
18
|
protected variantIndex(enumName: string, lit: ts.Expression): number;
|
|
19
|
-
/**
|
|
20
|
-
* Storage paths an expression names, syntactically: `acct.a.b` -> ["acct.a.b"], `v.get(i)` -> ["v[]"],
|
|
21
|
-
* a reference local -> the paths it aliases, a ternary -> both sides. Undefined when unknown.
|
|
22
|
-
*/
|
|
23
|
-
protected pathsOf(node: ts.Expression): string[] | undefined;
|
|
24
|
-
/**
|
|
25
|
-
* In JS, replacing an object (`acct.pos = {...}`, `v.set(i, {...})`, `v.pop()`) leaves earlier references
|
|
26
|
-
* to the old object unchanged. Here a reference is a pointer into account data, so it would see the new
|
|
27
|
-
* value. Refuse when a live reference into the replaced place is still used afterwards.
|
|
28
|
-
*/
|
|
29
|
-
protected assertNotAliased(replaced: string[] | undefined, at: ts.Node, helper?: string): void;
|
|
30
|
-
/**
|
|
31
|
-
* Whether the variable declared by `decl` is read after `at` (later in its block, or anywhere in a loop around `at`).
|
|
32
|
-
* A parameter (of a closure or helper expanded here) is read after `at` when its function reads it after `at`; when
|
|
33
|
-
* `at` is in another function (a closure or helper it calls), any read of it in its own function counts.
|
|
34
|
-
*/
|
|
35
|
-
protected usedAfter(decl: ts.VariableDeclaration | ts.ParameterDeclaration, at: ts.Node): boolean;
|
|
36
19
|
/**
|
|
37
20
|
* A pointer to a struct in storage, from `place` or `cond ? placeA : placeB` (same struct type).
|
|
38
21
|
* Returns undefined when the expression is not such a place.
|
|
@@ -75,7 +58,9 @@ export declare abstract class StorageEmitter extends EmitterBase {
|
|
|
75
58
|
protected writeAggregate(target: Ref, valueNode: ts.Expression): void;
|
|
76
59
|
/** The Vec view of a FixedVec stored at `lv` (`{ len, items[cap] }`). */
|
|
77
60
|
protected fixedVec(lv: string, elem: FieldType, cap: number): NonNullable<Ref["vec"]>;
|
|
78
|
-
/** A
|
|
61
|
+
/** A heap Vec (a Vec<T> in a `@layout borsh` struct) at `lv`: `{ len, cap, items }`, grown by ts_hvec_reserve. */
|
|
62
|
+
protected heapVec(lv: string, elem: FieldType): NonNullable<Ref["vec"]>;
|
|
63
|
+
/** A place whose type is a FixedVec (or a heap Vec) gets its Vec view. */
|
|
79
64
|
protected withFixedVec(r: Ref): Ref;
|
|
80
65
|
/** `arr.get(i)` reads storage rather than calling anything. */
|
|
81
66
|
protected isStorageCall(node: ts.CallExpression): boolean;
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
|
-
import { resolveScalarType } from "../analyze.js";
|
|
2
|
+
import { heapVecOf, resolveScalarType } from "../analyze.js";
|
|
3
3
|
import { INT_INFO, isScalar, isWritable, sameType, scalarSize, typeName } from "../model.js";
|
|
4
4
|
import { U64, BOOL, PUBKEY, STRING, optC, fieldC, fixedVecC, storageDecl, vecCount, vecPlace, emptySizeC } from "./shared.js";
|
|
5
|
-
import {
|
|
5
|
+
import { AliasEmitter } from "./alias.js";
|
|
6
6
|
/**
|
|
7
7
|
* Places in account data and locals: references, reads and writes, Vec/array indexing, aliasing rules and
|
|
8
8
|
* argument validation.
|
|
9
9
|
*/
|
|
10
|
-
export class StorageEmitter extends
|
|
10
|
+
export class StorageEmitter extends AliasEmitter {
|
|
11
11
|
/** C lines rejecting malformed fixed-layout data at `lv`: bools, enums, option tags, string lengths, enum tags. */
|
|
12
12
|
validation(lv, t, pad, fail = `TS_FAIL(TS_ERR_INSTRUCTION_DATA, "TypeSOL: invalid argument data")`) {
|
|
13
13
|
switch (t.kind) {
|
|
@@ -84,100 +84,6 @@ export class StorageEmitter extends EmitterBase {
|
|
|
84
84
|
this.fail(lit, `${enumName} has no variant "${lit.text}"`);
|
|
85
85
|
return i;
|
|
86
86
|
}
|
|
87
|
-
/**
|
|
88
|
-
* Storage paths an expression names, syntactically: `acct.a.b` -> ["acct.a.b"], `v.get(i)` -> ["v[]"],
|
|
89
|
-
* a reference local -> the paths it aliases, a ternary -> both sides. Undefined when unknown.
|
|
90
|
-
*/
|
|
91
|
-
pathsOf(node) {
|
|
92
|
-
if (ts.isParenthesizedExpression(node))
|
|
93
|
-
return this.pathsOf(node.expression);
|
|
94
|
-
if (ts.isIdentifier(node)) {
|
|
95
|
-
const l = this.lookup(node.text);
|
|
96
|
-
if (l)
|
|
97
|
-
return l.paths ?? (l.type.kind === "array" ? [`@${l.c}`] : undefined);
|
|
98
|
-
return this.accounts.has(node.text) ? [node.text] : undefined;
|
|
99
|
-
}
|
|
100
|
-
if (ts.isPropertyAccessExpression(node))
|
|
101
|
-
return this.pathsOf(node.expression)?.map((p) => `${p}.${node.name.text}`);
|
|
102
|
-
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "get")
|
|
103
|
-
return this.pathsOf(node.expression.expression)?.map((p) => `${p}[]`);
|
|
104
|
-
if (ts.isConditionalExpression(node)) {
|
|
105
|
-
const a = this.pathsOf(node.whenTrue);
|
|
106
|
-
const b = this.pathsOf(node.whenFalse);
|
|
107
|
-
return a && b ? [...a, ...b] : undefined;
|
|
108
|
-
}
|
|
109
|
-
return undefined;
|
|
110
|
-
}
|
|
111
|
-
/**
|
|
112
|
-
* In JS, replacing an object (`acct.pos = {...}`, `v.set(i, {...})`, `v.pop()`) leaves earlier references
|
|
113
|
-
* to the old object unchanged. Here a reference is a pointer into account data, so it would see the new
|
|
114
|
-
* value. Refuse when a live reference into the replaced place is still used afterwards.
|
|
115
|
-
*/
|
|
116
|
-
assertNotAliased(replaced, at, helper) {
|
|
117
|
-
if (!replaced)
|
|
118
|
-
return;
|
|
119
|
-
for (const scope of this.scopes)
|
|
120
|
-
for (const [name, l] of scope) {
|
|
121
|
-
if (!l.paths || !l.decl)
|
|
122
|
-
continue;
|
|
123
|
-
const hit = replaced.find((r) => l.paths.some((p) => p === r || p.startsWith(`${r}.`) || p.startsWith(`${r}[]`)));
|
|
124
|
-
if (!hit || !this.usedAfter(l.decl, at))
|
|
125
|
-
continue;
|
|
126
|
-
this.fail(at, helper
|
|
127
|
-
? `"${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`
|
|
128
|
-
: `"${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`);
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
/**
|
|
132
|
-
* Whether the variable declared by `decl` is read after `at` (later in its block, or anywhere in a loop around `at`).
|
|
133
|
-
* A parameter (of a closure or helper expanded here) is read after `at` when its function reads it after `at`; when
|
|
134
|
-
* `at` is in another function (a closure or helper it calls), any read of it in its own function counts.
|
|
135
|
-
*/
|
|
136
|
-
usedAfter(decl, at) {
|
|
137
|
-
const symbol = this.checker.getSymbolAtLocation(decl.name);
|
|
138
|
-
if (!symbol)
|
|
139
|
-
return true;
|
|
140
|
-
if (ts.isParameter(decl)) {
|
|
141
|
-
const fn = decl.parent;
|
|
142
|
-
const inside = at.getSourceFile() === fn.getSourceFile() && at.pos >= fn.pos && at.end <= fn.end;
|
|
143
|
-
let read = false;
|
|
144
|
-
const visitParam = (n) => {
|
|
145
|
-
if (read)
|
|
146
|
-
return;
|
|
147
|
-
if (ts.isIdentifier(n) && n !== decl.name && this.checker.getSymbolAtLocation(n) === symbol) {
|
|
148
|
-
if (!inside || n.pos >= at.end)
|
|
149
|
-
read = true;
|
|
150
|
-
// A loop inside the function, around `at`, reads it again on its next turn.
|
|
151
|
-
for (let p = at.parent; inside && p && p !== fn; p = p.parent)
|
|
152
|
-
if ((ts.isForStatement(p) || ts.isForOfStatement(p) || ts.isWhileStatement(p) || ts.isDoStatement(p)) && n.pos >= p.pos && n.end <= p.end)
|
|
153
|
-
read = true;
|
|
154
|
-
}
|
|
155
|
-
ts.forEachChild(n, visitParam);
|
|
156
|
-
};
|
|
157
|
-
const body = fn.body;
|
|
158
|
-
if (body)
|
|
159
|
-
visitParam(body);
|
|
160
|
-
return read;
|
|
161
|
-
}
|
|
162
|
-
// Loops around `at` that do not also contain the declaration run their earlier statements again later.
|
|
163
|
-
let loop;
|
|
164
|
-
for (let n = at.parent; n && n !== decl.parent; n = n.parent)
|
|
165
|
-
if ((ts.isForStatement(n) || ts.isForOfStatement(n) || ts.isWhileStatement(n) || ts.isDoStatement(n)) && !(decl.pos >= n.pos && decl.end <= n.end))
|
|
166
|
-
loop = n;
|
|
167
|
-
let found = false;
|
|
168
|
-
const scope = decl.parent.parent.parent; // VariableDeclaration -> List -> Statement -> enclosing block
|
|
169
|
-
const visit = (n) => {
|
|
170
|
-
if (found)
|
|
171
|
-
return;
|
|
172
|
-
if (ts.isIdentifier(n) && n !== decl.name && this.checker.getSymbolAtLocation(n) === symbol) {
|
|
173
|
-
if (n.pos >= at.end || (loop && n.pos >= loop.pos && n.end <= loop.end))
|
|
174
|
-
found = true;
|
|
175
|
-
}
|
|
176
|
-
ts.forEachChild(n, visit);
|
|
177
|
-
};
|
|
178
|
-
visit(scope);
|
|
179
|
-
return found;
|
|
180
|
-
}
|
|
181
87
|
/**
|
|
182
88
|
* A pointer to a struct in storage, from `place` or `cond ? placeA : placeB` (same struct type).
|
|
183
89
|
* Returns undefined when the expression is not such a place.
|
|
@@ -306,6 +212,8 @@ export class StorageEmitter extends EmitterBase {
|
|
|
306
212
|
const r = { lv: `d_${a.name}->${f.name}`, type: f.type, writable: isWritable(a.kind), account: a, path: [f.name] };
|
|
307
213
|
if (f.type.kind === "vec" && f.type.cap !== undefined)
|
|
308
214
|
r.vec = this.fixedVec(r.lv, f.type.elem, f.type.cap);
|
|
215
|
+
else if (f.type.kind === "vec" && f.type.heap)
|
|
216
|
+
r.vec = this.heapVec(r.lv, f.type.elem);
|
|
309
217
|
else if (f.type.kind === "vec") {
|
|
310
218
|
// Growing needs the account's length at instruction entry: instructions have it, helpers get it passed.
|
|
311
219
|
const s = a.kind.struct;
|
|
@@ -377,8 +285,10 @@ export class StorageEmitter extends EmitterBase {
|
|
|
377
285
|
if (!f)
|
|
378
286
|
this.fail(node.name, `${s.name} has no field "${field}"`);
|
|
379
287
|
const r = { ...base, lv: `${base.lv}.${f.name}`, type: f.type, path: base.path && [...base.path, f.name], vec: undefined };
|
|
288
|
+
if (f.type.kind === "vec" && f.type.heap)
|
|
289
|
+
r.vec = this.heapVec(r.lv, f.type.elem);
|
|
380
290
|
// Vecs of loaded accounts can be read and updated in place but not resized (no entry length known).
|
|
381
|
-
if (f.type.kind === "vec" && f.type.cap === undefined) {
|
|
291
|
+
else if (f.type.kind === "vec" && f.type.cap === undefined) {
|
|
382
292
|
const k = s.vecs.findIndex((v) => v.name === f.name);
|
|
383
293
|
const at = s.vecs.length === 1 ? { len: `${base.lv}.${f.name}__len`, items: r.lv } : vecPlace(s, base.lv, k);
|
|
384
294
|
r.lv = at.items;
|
|
@@ -639,6 +549,9 @@ export class StorageEmitter extends EmitterBase {
|
|
|
639
549
|
this.line(`ts_memcpy(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
|
|
640
550
|
return;
|
|
641
551
|
}
|
|
552
|
+
// A struct holding a heap Vec is copied field by field: a whole copy would share one list between two places.
|
|
553
|
+
if (target.type.kind === "struct" && heapVecOf(this.model.structs.get(target.type.name)))
|
|
554
|
+
this.fail(valueNode, `${target.type.name} holds a Vec<T>: assign its fields one by one`);
|
|
642
555
|
if (ts.isObjectLiteralExpression(valueNode)) {
|
|
643
556
|
if (target.type.kind !== "struct")
|
|
644
557
|
this.fail(valueNode, `expected a ${typeName(target.type)}, not an object literal`);
|
|
@@ -685,9 +598,43 @@ export class StorageEmitter extends EmitterBase {
|
|
|
685
598
|
this.line(`}`);
|
|
686
599
|
return;
|
|
687
600
|
}
|
|
601
|
+
// `list = owners`: a Vec argument, or a Vec / FixedVec of the same elements, copied whole into a FixedVec or a heap
|
|
602
|
+
// Vec (Anchor's `multisig.owners = owners`). More than a FixedVec holds fail with 5104, as push does; a heap Vec
|
|
603
|
+
// grows (the account bounds it when it is written back, 3004).
|
|
604
|
+
const heap = target.type.kind === "vec" && !!target.type.heap;
|
|
605
|
+
if (target.type.kind === "vec" && (target.type.cap !== undefined || heap) && target.type.elem.kind !== "string" && target.type.elem.kind !== "fstring") {
|
|
606
|
+
const t = target.type;
|
|
607
|
+
const l = ts.isIdentifier(valueNode) ? this.lookup(valueNode.text) : undefined;
|
|
608
|
+
const r = l?.type.kind === "vecArg" ? undefined : this.reporter.guard(() => this.ref(valueNode));
|
|
609
|
+
const from = l?.type.kind === "vecArg" && sameType(l.type.elem, t.elem)
|
|
610
|
+
? { items: `${l.c}.ptr`, count: `((uint64_t)${l.c}.len)` }
|
|
611
|
+
: r?.vec && r.type.kind === "vec" && sameType(r.type.elem, t.elem) && (heap || !sameType(r.type, t))
|
|
612
|
+
? { items: r.vec.items, count: vecCount(r.vec) }
|
|
613
|
+
: undefined;
|
|
614
|
+
if (from) {
|
|
615
|
+
const size = this.fieldBytes(t.elem);
|
|
616
|
+
const n = this.tmp("vn");
|
|
617
|
+
this.line(`uint64_t ${n} = ${from.count};`);
|
|
618
|
+
if (heap) {
|
|
619
|
+
// Growing may move the elements: references into them cannot outlive this.
|
|
620
|
+
this.assertNotAliased(this.pathsOf(valueNode)?.map((p) => `${p}[]`), valueNode);
|
|
621
|
+
this.line(`TS_TRY(ts_hvec_reserve(&${target.lv}, ${n}, ${size}));`);
|
|
622
|
+
this.line(`ts_memmove(${target.lv}.items, (const uint8_t *)${from.items}, ${n} * ${size});`);
|
|
623
|
+
}
|
|
624
|
+
else {
|
|
625
|
+
this.line(`if (${n} > ${t.cap}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: more elements than the ${typeName(t)} holds");`);
|
|
626
|
+
// Slots past the new length keep what they held, as after pop() / clear().
|
|
627
|
+
this.line(`ts_memcpy(${target.lv}.items, (const uint8_t *)${from.items}, ${n} * ${size});`);
|
|
628
|
+
}
|
|
629
|
+
this.line(`${target.lv}.len = (uint32_t)${n};`);
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
if (heap)
|
|
634
|
+
this.fail(valueNode, `expected a ${typeName(target.type)}: a Vec argument or another list of the same elements`);
|
|
688
635
|
const src = this.ref(valueNode) ?? this.wholeAccount(valueNode);
|
|
689
636
|
if (!src || !sameType(src.type, target.type))
|
|
690
|
-
this.fail(valueNode, `expected a ${typeName(target.type)}: an object literal
|
|
637
|
+
this.fail(valueNode, `expected a ${typeName(target.type)}: an object literal, another ${typeName(target.type)}${target.type.kind === "vec" && target.type.cap !== undefined ? " or a Vec of the same elements" : ""}`);
|
|
691
638
|
// Same-typed places are either distinct or identical (`a.p = a.p`); ts_copy skips the latter.
|
|
692
639
|
this.line(`ts_copy(&${target.lv}, &${src.lv}, sizeof(${target.lv}));`);
|
|
693
640
|
}
|
|
@@ -695,10 +642,16 @@ export class StorageEmitter extends EmitterBase {
|
|
|
695
642
|
fixedVec(lv, elem, cap) {
|
|
696
643
|
return { len: `${lv}.len`, items: `${lv}.items`, fixed: "", elemSize: this.fieldBytes(elem), resizable: false, cap };
|
|
697
644
|
}
|
|
698
|
-
/** A
|
|
645
|
+
/** A heap Vec (a Vec<T> in a `@layout borsh` struct) at `lv`: `{ len, cap, items }`, grown by ts_hvec_reserve. */
|
|
646
|
+
heapVec(lv, elem) {
|
|
647
|
+
return { len: `${lv}.len`, items: `${lv}.items`, fixed: "", elemSize: this.fieldBytes(elem), resizable: false, heap: true };
|
|
648
|
+
}
|
|
649
|
+
/** A place whose type is a FixedVec (or a heap Vec) gets its Vec view. */
|
|
699
650
|
withFixedVec(r) {
|
|
700
651
|
if (r.type.kind === "vec" && r.type.cap !== undefined)
|
|
701
652
|
r.vec = this.fixedVec(r.lv, r.type.elem, r.type.cap);
|
|
653
|
+
else if (r.type.kind === "vec" && r.type.heap)
|
|
654
|
+
r.vec = this.heapVec(r.lv, r.type.elem);
|
|
702
655
|
return r;
|
|
703
656
|
}
|
|
704
657
|
/** `arr.get(i)` reads storage rather than calling anything. */
|
|
@@ -778,6 +731,8 @@ export class StorageEmitter extends EmitterBase {
|
|
|
778
731
|
case "vec":
|
|
779
732
|
if (t.cap !== undefined)
|
|
780
733
|
return 4 + this.fieldBytes(t.elem) * t.cap;
|
|
734
|
+
if (t.heap)
|
|
735
|
+
return 16; // TSH_*: length, capacity, pointer
|
|
781
736
|
throw new Error("unreachable: variable-size field has no fixed size");
|
|
782
737
|
case "string":
|
|
783
738
|
throw new Error("unreachable: variable-size field has no fixed size");
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { type AccountParam } from "../model.js";
|
|
3
|
+
import { CreateEmitter } from "./create.js";
|
|
4
|
+
/** SPL Token and Token-2022 instructions (`tokenProgram.transfer(…)` and the rest) and the ATA program's. */
|
|
5
|
+
export declare abstract class TokenEmitter extends CreateEmitter {
|
|
6
|
+
protected tokenOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
|
|
7
|
+
protected ataOp(node: ts.CallExpression, program: AccountParam, method: string): undefined;
|
|
8
|
+
}
|