@typesol/cli 0.41.0 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +319 -0
- package/README.md +11 -7
- package/dist/compiler/analyze.js +484 -13
- 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 +65 -7
- package/dist/compiler/emit/base.js +91 -7
- package/dist/compiler/emit/borsh.d.ts +7 -0
- package/dist/compiler/emit/borsh.js +86 -1
- package/dist/compiler/emit/calls.d.ts +169 -2
- package/dist/compiler/emit/calls.js +1170 -81
- package/dist/compiler/emit/cpi-core.d.ts +28 -5
- package/dist/compiler/emit/cpi-core.js +238 -12
- package/dist/compiler/emit/cpi.js +16 -16
- package/dist/compiler/emit/create.d.ts +3 -3
- package/dist/compiler/emit/create.js +33 -25
- package/dist/compiler/emit/expressions.js +89 -9
- package/dist/compiler/emit/function.js +2 -2
- package/dist/compiler/emit/outline.d.ts +24 -0
- package/dist/compiler/emit/outline.js +100 -0
- package/dist/compiler/emit/program.js +37 -3
- package/dist/compiler/emit/rbtree.d.ts +7 -0
- package/dist/compiler/emit/rbtree.js +142 -0
- package/dist/compiler/emit/shared.d.ts +43 -1
- package/dist/compiler/emit/shared.js +18 -2
- package/dist/compiler/emit/statements.d.ts +58 -1
- package/dist/compiler/emit/statements.js +549 -22
- package/dist/compiler/emit/storage.d.ts +48 -1
- package/dist/compiler/emit/storage.js +220 -63
- package/dist/compiler/emit/token.d.ts +11 -8
- package/dist/compiler/emit/token.js +233 -104
- package/dist/compiler/emit/views.d.ts +60 -0
- package/dist/compiler/emit/views.js +523 -0
- package/dist/compiler/hints.js +6 -0
- package/dist/compiler/idl.js +2 -1
- package/dist/compiler/model.d.ts +84 -4
- package/dist/compiler/model.js +19 -0
- package/dist/compiler/toolchain.d.ts +15 -0
- package/dist/compiler/toolchain.js +146 -11
- package/dist/testing-stake.d.ts +216 -0
- package/dist/testing-stake.js +526 -0
- package/dist/testing.d.ts +1 -0
- package/dist/testing.js +1 -0
- package/docs/architecture.md +9 -2
- package/docs/case-study-phoenix.md +226 -0
- package/docs/case-study-spl-stake-pool.md +122 -0
- package/docs/errors.md +1 -1
- package/docs/language.md +244 -20
- package/docs/migrate-from-anchor.md +1 -0
- package/docs/runtime.md +1 -1
- package/docs/security-model.md +4 -0
- package/docs/stability.md +33 -1
- package/docs/test-your-program.md +47 -0
- package/docs/testing.md +19 -0
- package/docs/troubleshooting.md +5 -2
- package/lib/typesol.d.ts +462 -44
- package/llms-full.txt +338 -26
- package/llms.txt +1 -1
- package/package.json +2 -2
- package/runtime/typesol_rt.h +476 -0
|
@@ -27,8 +27,29 @@ export declare abstract class StorageEmitter extends AliasEmitter {
|
|
|
27
27
|
} | undefined;
|
|
28
28
|
/** Cheap syntactic pre-check (no code emitted) for struct places. */
|
|
29
29
|
protected looksLikeStructPlace(node: ts.Expression): boolean;
|
|
30
|
+
/**
|
|
31
|
+
* A local list lives in the function's stack frame (4 KiB on SBPF v0, shared with every other local and the helpers
|
|
32
|
+
* clang inlines): one list's elements may take at most 2 KiB, so the failure is a clear compile error, not clang's
|
|
33
|
+
* frame error. A FixedVec's u32 length is not counted: `FixedVec<u32, 512>` (2,052 bytes) is 2 KiB of elements, and
|
|
34
|
+
* a frame that then overflows is reported by the frame check, which names the biggest locals.
|
|
35
|
+
*/
|
|
36
|
+
protected checkLocalListSize(t: FieldType & {
|
|
37
|
+
kind: "vec" | "array";
|
|
38
|
+
}, at: ts.Node, what?: string, declared?: boolean): void;
|
|
39
|
+
/**
|
|
40
|
+
* `FixedVec<T, N>` / `FixedArray<T, N>` written as a local's type: T an integer, boolean, Pubkey, enum,
|
|
41
|
+
* `FixedString<N>` or fixed-size struct, N a literal. Undefined for other types; a list type with anything else fails.
|
|
42
|
+
*/
|
|
43
|
+
protected listAnnotation(t: ts.TypeNode): (FieldType & {
|
|
44
|
+
kind: "vec";
|
|
45
|
+
cap: number;
|
|
46
|
+
}) | (FieldType & {
|
|
47
|
+
kind: "array";
|
|
48
|
+
}) | undefined;
|
|
49
|
+
/** A local list's element type: a scalar, a FixedString<N> or a fixed-size struct (no Vec, no heap). */
|
|
50
|
+
protected localElem(node: ts.TypeNode): FieldType | undefined;
|
|
30
51
|
/** `fixedArray<T, N>(fill)` as a local declaration. */
|
|
31
|
-
protected localArray(init: ts.CallExpression, c: string): FieldType & {
|
|
52
|
+
protected localArray(init: ts.CallExpression, c: string, annotation?: ts.TypeNode): FieldType & {
|
|
32
53
|
kind: "array";
|
|
33
54
|
};
|
|
34
55
|
/** Resolve an expression to a storage location, if it names one. */
|
|
@@ -60,15 +81,39 @@ export declare abstract class StorageEmitter extends AliasEmitter {
|
|
|
60
81
|
*/
|
|
61
82
|
/** A whole struct account copied as a value (`return vault`, `info = vault`): fixed-size structs only. */
|
|
62
83
|
private wholeAccount;
|
|
84
|
+
/**
|
|
85
|
+
* A data enum literal (`{ kind: "Variant", … }`), checked: its variant, and `writeFields(base)`, which evaluates the
|
|
86
|
+
* fields in source order (as JS does) into `${base}.<field>`, a `TSV_<Enum>__<Variant>` place (or, given a function,
|
|
87
|
+
* into the place it names for each field).
|
|
88
|
+
*/
|
|
89
|
+
protected dataEnumLiteral(name: string, valueNode: ts.ObjectLiteralExpression): {
|
|
90
|
+
e: import("../model.js").DataEnumDef;
|
|
91
|
+
vi: number;
|
|
92
|
+
variant: {
|
|
93
|
+
name: string;
|
|
94
|
+
fields: import("../model.js").StructField[];
|
|
95
|
+
size: number;
|
|
96
|
+
};
|
|
97
|
+
writeFields: (base: string | ((field: string) => string)) => void;
|
|
98
|
+
};
|
|
63
99
|
/**
|
|
64
100
|
* Write an aggregate value into `target`. `fresh`: the target is a value just declared (or a temporary), which no
|
|
65
101
|
* expression can read yet, so a literal is built in it directly rather than in a temporary first.
|
|
66
102
|
*/
|
|
67
103
|
protected writeAggregate(target: Ref, valueNode: ts.Expression, fresh?: boolean): void;
|
|
104
|
+
/** `fixedVec([…])` or `[…]`: a list literal, which writeAggregate builds in a fresh target with its free slots zeroed. */
|
|
105
|
+
protected isListLiteral(node: ts.Expression): boolean;
|
|
68
106
|
/** The Vec view of a FixedVec stored at `lv` (`{ len, items[cap] }`). */
|
|
69
107
|
protected fixedVec(lv: string, elem: FieldType, cap: number): NonNullable<Ref["vec"]>;
|
|
70
108
|
/** A heap Vec (a Vec<T> in a `@layout borsh` struct) at `lv`: `{ len, cap, items }`, grown by ts_hvec_reserve. */
|
|
71
109
|
protected heapVec(lv: string, elem: FieldType): NonNullable<Ref["vec"]>;
|
|
110
|
+
/** Slices lowered once before a loop over them (see eachElement): the loop's length and element reads reuse them. */
|
|
111
|
+
protected sliceViews: Map<ts.Node, Ref>;
|
|
112
|
+
/**
|
|
113
|
+
* `bigVec.slice(start, end)`: elements start..end-1 in place, as BigVec::deserialize_mut_slice(start, end - start)
|
|
114
|
+
* gives them. Out of range fails with ProgramError::AccountDataTooSmall, as that does (JS's slice would clamp).
|
|
115
|
+
*/
|
|
116
|
+
protected bigVecSlice(node: ts.CallExpression, base: Ref): Ref;
|
|
72
117
|
/** A place whose type is a FixedVec (or a heap Vec) gets its Vec view. */
|
|
73
118
|
protected withFixedVec(r: Ref): Ref;
|
|
74
119
|
/** `arr.get(i)` reads storage rather than calling anything. */
|
|
@@ -77,6 +122,8 @@ export declare abstract class StorageEmitter extends AliasEmitter {
|
|
|
77
122
|
protected peekArray(node: ts.Expression): boolean;
|
|
78
123
|
/** The kind of storage an expression names (struct, array, dataEnum…), without emitting code or failing. */
|
|
79
124
|
protected peekKind(node: ts.Expression): FieldType["kind"] | undefined;
|
|
125
|
+
/** The type of the storage an expression names, without emitting code or failing. */
|
|
126
|
+
protected peekType(node: ts.Expression): FieldType | undefined;
|
|
80
127
|
protected place(node: ts.Expression): {
|
|
81
128
|
type: ValueType;
|
|
82
129
|
read: string;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
|
-
import { heapVecOf, resolveScalarType } from "../analyze.js";
|
|
2
|
+
import { heapVecOf, resolveScalarType, structNameOf, typesolName } 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
5
|
import { AliasEmitter } from "./alias.js";
|
|
@@ -134,28 +134,99 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
134
134
|
const r = this.probe(() => this.ref(node));
|
|
135
135
|
return r?.type.kind === "struct";
|
|
136
136
|
}
|
|
137
|
+
/**
|
|
138
|
+
* A local list lives in the function's stack frame (4 KiB on SBPF v0, shared with every other local and the helpers
|
|
139
|
+
* clang inlines): one list's elements may take at most 2 KiB, so the failure is a clear compile error, not clang's
|
|
140
|
+
* frame error. A FixedVec's u32 length is not counted: `FixedVec<u32, 512>` (2,052 bytes) is 2 KiB of elements, and
|
|
141
|
+
* a frame that then overflows is reported by the frame check, which names the biggest locals.
|
|
142
|
+
*/
|
|
143
|
+
checkLocalListSize(t, at, what = typeName(t), declared = false) {
|
|
144
|
+
const bytes = this.fieldBytes(t);
|
|
145
|
+
const elements = t.kind === "vec" ? bytes - 4 : bytes;
|
|
146
|
+
const smaller = t.kind === "vec" ? "FixedVec<T, N>" : "FixedArray<T, N>";
|
|
147
|
+
if (elements > 2048)
|
|
148
|
+
this.fail(at, `${what} takes ${bytes} bytes; locals live on the 4 KiB stack, so keep it under 2 KiB of elements (${elements} here: a smaller ${smaller}${declared ? ", or /** @heap */ on the declaration to keep it on the heap" : ""})`);
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* `FixedVec<T, N>` / `FixedArray<T, N>` written as a local's type: T an integer, boolean, Pubkey, enum,
|
|
152
|
+
* `FixedString<N>` or fixed-size struct, N a literal. Undefined for other types; a list type with anything else fails.
|
|
153
|
+
*/
|
|
154
|
+
listAnnotation(t) {
|
|
155
|
+
const list = typesolName(t, this.scope.imports);
|
|
156
|
+
if ((list !== "FixedVec" && list !== "FixedArray") || !ts.isTypeReferenceNode(t))
|
|
157
|
+
return undefined;
|
|
158
|
+
const [elemNode, nNode] = t.typeArguments ?? [];
|
|
159
|
+
const n = nNode && ts.isLiteralTypeNode(nNode) && ts.isNumericLiteral(nNode.literal) ? Number(nNode.literal.text) : NaN;
|
|
160
|
+
if (!Number.isInteger(n) || n < 1)
|
|
161
|
+
this.fail(t, `${list}<T, N>: N must be a literal of at least 1`);
|
|
162
|
+
const elem = elemNode && this.localElem(elemNode);
|
|
163
|
+
if (!elem)
|
|
164
|
+
this.fail(elemNode ?? t, `${list}<T, N> as a local: T is an integer, boolean, Pubkey, enum, FixedString<N> or a struct of fixed size`);
|
|
165
|
+
return list === "FixedVec" ? { kind: "vec", elem, cap: n } : { kind: "array", elem, len: n };
|
|
166
|
+
}
|
|
167
|
+
/** A local list's element type: a scalar, a FixedString<N> or a fixed-size struct (no Vec, no heap). */
|
|
168
|
+
localElem(node) {
|
|
169
|
+
const scalar = resolveScalarType(node, this.scope);
|
|
170
|
+
if (scalar)
|
|
171
|
+
return scalar;
|
|
172
|
+
if (typesolName(node, this.scope.imports) === "FixedString") {
|
|
173
|
+
const a = node.typeArguments?.[0];
|
|
174
|
+
const cap = a && ts.isLiteralTypeNode(a) && ts.isNumericLiteral(a.literal) ? Number(a.literal.text) : NaN;
|
|
175
|
+
if (!Number.isInteger(cap) || cap < 1)
|
|
176
|
+
return undefined;
|
|
177
|
+
this.model.fstrings.add(cap);
|
|
178
|
+
return { kind: "fstring", cap };
|
|
179
|
+
}
|
|
180
|
+
const sn = structNameOf(node, this.scope);
|
|
181
|
+
const s = sn ? this.model.structs.get(sn) : undefined;
|
|
182
|
+
if (s && s.size !== undefined && !s.vec && !heapVecOf(s))
|
|
183
|
+
return { kind: "struct", name: s.name };
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
137
186
|
/** `fixedArray<T, N>(fill)` as a local declaration. */
|
|
138
|
-
localArray(init, c) {
|
|
139
|
-
|
|
140
|
-
const
|
|
187
|
+
localArray(init, c, annotation) {
|
|
188
|
+
// The type arguments, or the declaration's `FixedArray<T, N>` when the call has none.
|
|
189
|
+
const fromType = !init.typeArguments?.length && annotation && ts.isTypeReferenceNode(annotation) ? annotation.typeArguments : undefined;
|
|
190
|
+
const [elemNode, lenNode] = init.typeArguments ?? fromType ?? [];
|
|
191
|
+
const scalar = elemNode && resolveScalarType(elemNode, this.scope);
|
|
192
|
+
// A struct (or FixedString) element: the fill is built once and copied into every slot, as JS fills with one value.
|
|
193
|
+
const elem = scalar ?? (elemNode && this.localElem(elemNode));
|
|
141
194
|
if (!elem)
|
|
142
|
-
this.fail(init, "fixedArray<T, N>(fill): T must be an integer, boolean or
|
|
195
|
+
this.fail(init, "fixedArray<T, N>(fill): T must be an integer, boolean, Pubkey, enum, FixedString<N> or a struct of fixed size");
|
|
143
196
|
const len = lenNode && ts.isLiteralTypeNode(lenNode) && ts.isNumericLiteral(lenNode.literal) ? Number(lenNode.literal.text) : NaN;
|
|
144
197
|
if (!Number.isInteger(len) || len < 1 || len > 256)
|
|
145
198
|
this.fail(init, "fixedArray<T, N>: N must be a literal 1..256 (locals live on the 4KB stack)");
|
|
146
199
|
if (init.arguments.length !== 1)
|
|
147
200
|
this.fail(init, "fixedArray<T, N>(fill) takes the fill value");
|
|
148
|
-
const fill = this.expect(this.expr(init.arguments[0], elem), elem, init.arguments[0]);
|
|
149
201
|
const type = { kind: "array", elem, len };
|
|
150
|
-
this.line(`${storageDecl(type, c)};`);
|
|
151
202
|
const i = this.tmp("i");
|
|
152
|
-
|
|
203
|
+
if (scalar) {
|
|
204
|
+
const fill = this.expect(this.expr(init.arguments[0], scalar), scalar, init.arguments[0]);
|
|
205
|
+
this.line(`${storageDecl(type, c)};`);
|
|
206
|
+
this.line(`for (uint64_t ${i} = 0; ${i} < ${len}; ${i}++) ${this.writeStorage({ lv: `${c}[${i}]`, type: elem, writable: true }, fill.c)};`);
|
|
207
|
+
return type;
|
|
208
|
+
}
|
|
209
|
+
this.checkLocalListSize(type, init);
|
|
210
|
+
const one = this.tmp("fill");
|
|
211
|
+
this.line(`${storageDecl(elem, one)};`);
|
|
212
|
+
this.line(`ts_memzero(&${one}, sizeof(${one}));`);
|
|
213
|
+
const vt = this.storageValueType(elem);
|
|
214
|
+
if (vt)
|
|
215
|
+
this.line(this.writeStorage({ lv: one, type: elem, writable: true }, this.expect(this.expr(init.arguments[0], vt), vt, init.arguments[0]).c) + ";");
|
|
216
|
+
else
|
|
217
|
+
this.writeAggregate({ lv: one, type: elem, writable: true }, init.arguments[0], true);
|
|
218
|
+
this.line(`${storageDecl(type, c)};`);
|
|
219
|
+
this.line(`for (uint64_t ${i} = 0; ${i} < ${len}; ${i}++) ts_memcpy(&${c}[${i}], &${one}, sizeof(${one}));`);
|
|
153
220
|
return type;
|
|
154
221
|
}
|
|
155
222
|
/** Resolve an expression to a storage location, if it names one. */
|
|
156
223
|
ref(node) {
|
|
157
224
|
if (ts.isParenthesizedExpression(node))
|
|
158
225
|
return this.ref(node.expression);
|
|
226
|
+
// A RawArray, a tree node's key / value, a narrowed tree result (views.ts).
|
|
227
|
+
const view = this.viewRef(node);
|
|
228
|
+
if (view)
|
|
229
|
+
return view;
|
|
159
230
|
const unbanged = this.withoutBang(node);
|
|
160
231
|
if (unbanged)
|
|
161
232
|
return this.ref(unbanged);
|
|
@@ -179,7 +250,7 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
179
250
|
return { lv: l.c, type: l.type.option, writable: false };
|
|
180
251
|
// A struct loaded from a remaining account.
|
|
181
252
|
if (l && l.type.kind === "structRef")
|
|
182
|
-
return { lv: `(*${l.c})`, type: { kind: "struct", name: l.type.struct }, writable: l.type.writable };
|
|
253
|
+
return { lv: `(*${l.c})`, type: { kind: "struct", name: l.type.struct }, writable: l.type.writable, ...(l.bigCap ? { bigCap: l.bigCap } : {}) };
|
|
183
254
|
if (l && l.type.kind === "enumRef")
|
|
184
255
|
return { lv: `(*${l.c})`, type: { kind: "dataEnum", name: l.type.name }, writable: l.type.writable };
|
|
185
256
|
return undefined;
|
|
@@ -288,7 +359,20 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
288
359
|
if (!f)
|
|
289
360
|
this.fail(node.name, `${s.name} has no field "${field}"`);
|
|
290
361
|
const r = { ...base, lv: `${base.lv}.${f.name}`, type: f.type, path: base.path && [...base.path, f.name], vec: undefined };
|
|
291
|
-
if (f.type.kind === "vec" && f.type.
|
|
362
|
+
if (f.type.kind === "vec" && f.type.big) {
|
|
363
|
+
// A loadRaw view sits at the account's data, so its room is what the account holds past the struct.
|
|
364
|
+
const elemSize = s.bigVec.elemSize;
|
|
365
|
+
r.vec = {
|
|
366
|
+
len: `${base.lv}.${f.name}__len`,
|
|
367
|
+
items: r.lv,
|
|
368
|
+
fixed: "",
|
|
369
|
+
elemSize,
|
|
370
|
+
resizable: false,
|
|
371
|
+
// Computed once at the load for a view bound to a local; for one used in place, here.
|
|
372
|
+
big: base.bigCap ?? `ts_bigvec_cap((const uint8_t *)&${base.lv}, sizeof(TSS_${s.name}), ${elemSize})`,
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
else if (f.type.kind === "vec" && f.type.heap)
|
|
292
376
|
r.vec = this.heapVec(r.lv, f.type.elem);
|
|
293
377
|
// Vecs of loaded accounts can be read and updated in place but not resized (no entry length known).
|
|
294
378
|
else if (f.type.kind === "vec" && f.type.cap === undefined) {
|
|
@@ -301,6 +385,16 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
301
385
|
}
|
|
302
386
|
return undefined;
|
|
303
387
|
}
|
|
388
|
+
// bigVec.slice(start, end): a view of elements start..end-1, for for … of and the list methods.
|
|
389
|
+
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "slice") {
|
|
390
|
+
const cached = this.sliceViews.get(node);
|
|
391
|
+
if (cached)
|
|
392
|
+
return cached;
|
|
393
|
+
const base = this.ref(node.expression.expression);
|
|
394
|
+
if (base?.vec?.big !== undefined && !base.vec.slice)
|
|
395
|
+
return this.bigVecSlice(node, base);
|
|
396
|
+
return undefined;
|
|
397
|
+
}
|
|
304
398
|
// arr.get(i) / vec.get(i)
|
|
305
399
|
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === "get") {
|
|
306
400
|
const owner = node.expression.expression;
|
|
@@ -350,6 +444,12 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
350
444
|
return `"${r.account.name}" is read-only; declare it Mut<...>`;
|
|
351
445
|
if (r.lv.startsWith("(*arg_") || r.lv.startsWith("arg_"))
|
|
352
446
|
return "instruction arguments are read-only; copy the value into a local first";
|
|
447
|
+
// An element of a Vec argument (or of a helper's Vec parameter): a view into the instruction data.
|
|
448
|
+
if (/^\(\([\w ]+\*\)(arg|p)_\w+\.ptr\)\[/.test(r.lv))
|
|
449
|
+
return "Vec arguments are read-only (a view of the instruction data); copy the element into a local first";
|
|
450
|
+
const param = /^\(\*p_(\w+)\)/.exec(r.lv)?.[1];
|
|
451
|
+
if (param && this.helper?.params.some((p) => p.name === param && !p.inout))
|
|
452
|
+
return `helper parameters are read-only: declare ${param} as Inout<T> to change the caller's value in place, or copy it into a local first`;
|
|
353
453
|
return "this is read-only: it was loaded with loadAccount() (use loadAccountMut()) or comes from a read-only account";
|
|
354
454
|
}
|
|
355
455
|
/** Lower call arguments left to right, settling earlier ones when a later one runs statements. */
|
|
@@ -418,6 +518,8 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
418
518
|
this.fail(node, `this is a ${r.type.name}; compare .kind or read a field of the narrowed variant`);
|
|
419
519
|
case "array":
|
|
420
520
|
case "vec":
|
|
521
|
+
if (r.vec?.slice)
|
|
522
|
+
this.fail(node, "a slice is not stored: use it where it is written (for (const x of list.slice(a, b)), list.slice(a, b).forEach(…), .get(i), .length)");
|
|
421
523
|
this.fail(node, "this is a list; use .get(i), .set(i, v) or .length");
|
|
422
524
|
case "struct":
|
|
423
525
|
this.fail(node, `this is a ${r.type.name}; read one of its fields`);
|
|
@@ -467,6 +569,49 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
467
569
|
this.assertUsable(a, node);
|
|
468
570
|
return { lv: `(*d_${a.name})`, type: { kind: "struct", name: a.kind.struct.name }, writable: false };
|
|
469
571
|
}
|
|
572
|
+
/**
|
|
573
|
+
* A data enum literal (`{ kind: "Variant", … }`), checked: its variant, and `writeFields(base)`, which evaluates the
|
|
574
|
+
* fields in source order (as JS does) into `${base}.<field>`, a `TSV_<Enum>__<Variant>` place (or, given a function,
|
|
575
|
+
* into the place it names for each field).
|
|
576
|
+
*/
|
|
577
|
+
dataEnumLiteral(name, valueNode) {
|
|
578
|
+
const e = this.model.dataEnums.get(name);
|
|
579
|
+
const kindProp = valueNode.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "kind");
|
|
580
|
+
if (!kindProp)
|
|
581
|
+
this.fail(valueNode, `a ${e.name} literal needs kind: "Variant"`);
|
|
582
|
+
const vi = this.variantIndex(e.name, kindProp.initializer);
|
|
583
|
+
const variant = e.variants[vi];
|
|
584
|
+
const given = new Map();
|
|
585
|
+
for (const p of valueNode.properties) {
|
|
586
|
+
if (p === kindProp)
|
|
587
|
+
continue;
|
|
588
|
+
if (ts.isPropertyAssignment(p) && ts.isIdentifier(p.name))
|
|
589
|
+
given.set(p.name.text, p.initializer);
|
|
590
|
+
else if (ts.isShorthandPropertyAssignment(p))
|
|
591
|
+
given.set(p.name.text, p.name);
|
|
592
|
+
else
|
|
593
|
+
this.fail(p, "use plain `field: value` entries");
|
|
594
|
+
}
|
|
595
|
+
for (const k of given.keys())
|
|
596
|
+
if (!variant.fields.some((f) => f.name === k))
|
|
597
|
+
this.fail(valueNode, `${e.name}.${variant.name} has no field "${k}"`);
|
|
598
|
+
const writeFields = (base) => {
|
|
599
|
+
for (const f of variant.fields)
|
|
600
|
+
if (!given.has(f.name))
|
|
601
|
+
this.fail(valueNode, `missing field "${f.name}" of ${e.name}.${variant.name}`);
|
|
602
|
+
for (const [name, ex] of given) {
|
|
603
|
+
const f = variant.fields.find((x) => x.name === name);
|
|
604
|
+
const sub = { lv: typeof base === "string" ? `${base}.${f.name}` : base(f.name), type: f.type, writable: true };
|
|
605
|
+
const vt = this.storageValueType(f.type);
|
|
606
|
+
// A string kept in a variable enum holds its own copy of account text (the account may change later).
|
|
607
|
+
if (vt)
|
|
608
|
+
this.line(this.writeStorage(sub, this.ownedString(this.expect(this.expr(ex, vt), vt, ex)).c) + ";");
|
|
609
|
+
else
|
|
610
|
+
this.writeAggregate(sub, ex);
|
|
611
|
+
}
|
|
612
|
+
};
|
|
613
|
+
return { e, vi, variant, writeFields };
|
|
614
|
+
}
|
|
470
615
|
/**
|
|
471
616
|
* Write an aggregate value into `target`. `fresh`: the target is a value just declared (or a temporary), which no
|
|
472
617
|
* expression can read yet, so a literal is built in it directly rather than in a temporary first.
|
|
@@ -503,45 +648,14 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
503
648
|
return;
|
|
504
649
|
}
|
|
505
650
|
if (target.type.kind === "dataEnum" && ts.isObjectLiteralExpression(valueNode)) {
|
|
506
|
-
const
|
|
507
|
-
const
|
|
508
|
-
if (!kindProp)
|
|
509
|
-
this.fail(valueNode, `a ${e.name} literal needs kind: "Variant"`);
|
|
510
|
-
const vi = this.variantIndex(e.name, kindProp.initializer);
|
|
511
|
-
const variant = e.variants[vi];
|
|
512
|
-
const given = new Map();
|
|
513
|
-
for (const p of valueNode.properties) {
|
|
514
|
-
if (p === kindProp)
|
|
515
|
-
continue;
|
|
516
|
-
if (ts.isPropertyAssignment(p) && ts.isIdentifier(p.name))
|
|
517
|
-
given.set(p.name.text, p.initializer);
|
|
518
|
-
else if (ts.isShorthandPropertyAssignment(p))
|
|
519
|
-
given.set(p.name.text, p.name);
|
|
520
|
-
else
|
|
521
|
-
this.fail(p, "use plain `field: value` entries");
|
|
522
|
-
}
|
|
523
|
-
for (const k of given.keys())
|
|
524
|
-
if (!variant.fields.some((f) => f.name === k))
|
|
525
|
-
this.fail(valueNode, `${e.name}.${variant.name} has no field "${k}"`);
|
|
651
|
+
const lit = this.dataEnumLiteral(target.type.name, valueNode);
|
|
652
|
+
const { e, vi, variant } = lit;
|
|
526
653
|
// Build the new value in a temporary: its fields may read the old value of the target.
|
|
527
654
|
const tmp = this.tmp("de");
|
|
528
655
|
this.line(`TSE_${e.name} ${tmp};`);
|
|
529
656
|
this.line(`ts_memzero(&${tmp}, sizeof(${tmp}));`);
|
|
530
657
|
this.line(`${tmp}.tag = ${vi};`);
|
|
531
|
-
|
|
532
|
-
if (!given.has(f.name))
|
|
533
|
-
this.fail(valueNode, `missing field "${f.name}" of ${e.name}.${variant.name}`);
|
|
534
|
-
// Fields are evaluated in source order, as in JS, straight into the temporary.
|
|
535
|
-
for (const [name, ex] of given) {
|
|
536
|
-
const f = variant.fields.find((x) => x.name === name);
|
|
537
|
-
const sub = { lv: `${tmp}.v.${variant.name}.${f.name}`, type: f.type, writable: true };
|
|
538
|
-
const vt = this.storageValueType(f.type);
|
|
539
|
-
// A string kept in a variable enum holds its own copy of account text (the account may change later).
|
|
540
|
-
if (vt)
|
|
541
|
-
this.line(this.writeStorage(sub, this.ownedString(this.expect(this.expr(ex, vt), vt, ex)).c) + ";");
|
|
542
|
-
else
|
|
543
|
-
this.writeAggregate(sub, ex);
|
|
544
|
-
}
|
|
658
|
+
lit.writeFields(`${tmp}.v.${variant.name}`);
|
|
545
659
|
this.line(`ts_memcpy(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
|
|
546
660
|
return;
|
|
547
661
|
}
|
|
@@ -549,34 +663,43 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
549
663
|
const list = valueNode.arguments[0];
|
|
550
664
|
if (valueNode.arguments.length !== 1 || !ts.isArrayLiteralExpression(list))
|
|
551
665
|
this.fail(valueNode, "fixedVec([…]) takes an array literal");
|
|
552
|
-
return this.writeAggregate(target, list);
|
|
666
|
+
return this.writeAggregate(target, list, fresh);
|
|
553
667
|
}
|
|
554
668
|
if (target.type.kind === "vec" && target.type.cap !== undefined && ts.isArrayLiteralExpression(valueNode)) {
|
|
555
|
-
// `list = [a, b]`: built in a temporary (the elements may read the old list), the unused slots zeroed.
|
|
556
669
|
const t = target.type;
|
|
557
670
|
const els = valueNode.elements;
|
|
558
671
|
if (els.length > t.cap)
|
|
559
672
|
this.fail(valueNode, `${els.length} elements do not fit in ${typeName(t)}`);
|
|
560
|
-
//
|
|
561
|
-
|
|
562
|
-
|
|
673
|
+
// The slots past the elements are zeroed (so the list's whole layout, copied into account data or an event, reads
|
|
674
|
+
// the same whatever ran before), large regions by the memset syscall: about constant compute units at any size.
|
|
675
|
+
const size = this.fieldBytes(t.elem);
|
|
676
|
+
const writeInto = (lv) => {
|
|
677
|
+
const free = (t.cap - els.length) * size;
|
|
678
|
+
if (free > 0)
|
|
679
|
+
this.line(`ts_memzero_bulk(${els.length ? `(uint8_t *)${lv}.items + ${els.length * size}` : `${lv}.items`}, ${free});`);
|
|
680
|
+
this.line(`${lv}.len = ${els.length};`);
|
|
681
|
+
els.forEach((e, i) => {
|
|
682
|
+
if (ts.isSpreadElement(e))
|
|
683
|
+
this.fail(e, "list the elements one by one");
|
|
684
|
+
const sub = { lv: `${lv}.items[${i}]`, type: t.elem, writable: true };
|
|
685
|
+
const vt = this.storageValueType(t.elem);
|
|
686
|
+
if (vt)
|
|
687
|
+
this.line(this.writeStorage(sub, this.ownedString(this.expect(this.expr(e, vt), vt, e)).c) + ";");
|
|
688
|
+
else
|
|
689
|
+
this.writeAggregate(sub, e, true);
|
|
690
|
+
});
|
|
691
|
+
};
|
|
692
|
+
// A fresh list (a declaration, a struct literal's field) is built in place: nothing can read it yet. So is an
|
|
693
|
+
// empty one, which reads nothing.
|
|
694
|
+
if (fresh || els.length === 0) {
|
|
695
|
+
writeInto(target.lv);
|
|
563
696
|
return;
|
|
564
697
|
}
|
|
698
|
+
// `list = [a, b]`: built in a temporary, since the elements may read the old list.
|
|
565
699
|
const tmp = this.tmp("fv");
|
|
566
700
|
this.line(`${fixedVecC(t)} ${tmp};`);
|
|
567
|
-
|
|
568
|
-
this.line(
|
|
569
|
-
els.forEach((e, i) => {
|
|
570
|
-
if (ts.isSpreadElement(e))
|
|
571
|
-
this.fail(e, "list the elements one by one");
|
|
572
|
-
const sub = { lv: `${tmp}.items[${i}]`, type: t.elem, writable: true };
|
|
573
|
-
const vt = this.storageValueType(t.elem);
|
|
574
|
-
if (vt)
|
|
575
|
-
this.line(this.writeStorage(sub, this.ownedString(this.expect(this.expr(e, vt), vt, e)).c) + ";");
|
|
576
|
-
else
|
|
577
|
-
this.writeAggregate(sub, e);
|
|
578
|
-
});
|
|
579
|
-
this.line(`ts_memcpy(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
|
|
701
|
+
writeInto(tmp);
|
|
702
|
+
this.line(`ts_memcpy_const(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
|
|
580
703
|
return;
|
|
581
704
|
}
|
|
582
705
|
// A struct holding a heap Vec is copied field by field: a whole copy would share one list between two places.
|
|
@@ -637,7 +760,9 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
637
760
|
const heap = target.type.kind === "vec" && !!target.type.heap;
|
|
638
761
|
if (target.type.kind === "vec" && (target.type.cap !== undefined || heap) && target.type.elem.kind !== "string" && target.type.elem.kind !== "fstring") {
|
|
639
762
|
const t = target.type;
|
|
640
|
-
|
|
763
|
+
// A slice of a Vec argument or the instruction data is a view like the list itself.
|
|
764
|
+
const view = !ts.isIdentifier(valueNode) && this.isVecArgView(valueNode) ? this.vecArgView(valueNode) : undefined;
|
|
765
|
+
const l = ts.isIdentifier(valueNode) ? this.lookup(valueNode.text) : view;
|
|
641
766
|
const r = l?.type.kind === "vecArg" ? undefined : this.reporter.guard(() => this.ref(valueNode));
|
|
642
767
|
const from = l?.type.kind === "vecArg" && sameType(l.type.elem, t.elem)
|
|
643
768
|
? { items: `${l.c}.ptr`, count: `((uint64_t)${l.c}.len)` }
|
|
@@ -677,6 +802,12 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
677
802
|
// Same-typed places are either distinct or identical (`a.p = a.p`); ts_copy skips the latter.
|
|
678
803
|
this.line(`ts_copy(&${target.lv}, &${src.lv}, sizeof(${target.lv}));`);
|
|
679
804
|
}
|
|
805
|
+
/** `fixedVec([…])` or `[…]`: a list literal, which writeAggregate builds in a fresh target with its free slots zeroed. */
|
|
806
|
+
isListLiteral(node) {
|
|
807
|
+
while (ts.isParenthesizedExpression(node))
|
|
808
|
+
node = node.expression;
|
|
809
|
+
return ts.isArrayLiteralExpression(node) || (ts.isCallExpression(node) && this.exportName(node.expression) === "fixedVec");
|
|
810
|
+
}
|
|
680
811
|
/** The Vec view of a FixedVec stored at `lv` (`{ len, items[cap] }`). */
|
|
681
812
|
fixedVec(lv, elem, cap) {
|
|
682
813
|
return { len: `${lv}.len`, items: `${lv}.items`, fixed: "", elemSize: this.fieldBytes(elem), resizable: false, cap };
|
|
@@ -685,6 +816,28 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
685
816
|
heapVec(lv, elem) {
|
|
686
817
|
return { len: `${lv}.len`, items: `${lv}.items`, fixed: "", elemSize: this.fieldBytes(elem), resizable: false, heap: true };
|
|
687
818
|
}
|
|
819
|
+
/** Slices lowered once before a loop over them (see eachElement): the loop's length and element reads reuse them. */
|
|
820
|
+
sliceViews = new Map();
|
|
821
|
+
/**
|
|
822
|
+
* `bigVec.slice(start, end)`: elements start..end-1 in place, as BigVec::deserialize_mut_slice(start, end - start)
|
|
823
|
+
* gives them. Out of range fails with ProgramError::AccountDataTooSmall, as that does (JS's slice would clamp).
|
|
824
|
+
*/
|
|
825
|
+
bigVecSlice(node, base) {
|
|
826
|
+
const args = node.arguments;
|
|
827
|
+
if (args.length < 1 || args.length > 2)
|
|
828
|
+
this.fail(node, "slice(start, end) takes the first element's index and the index after the last one");
|
|
829
|
+
const info = base.vec;
|
|
830
|
+
const start = this.tmp("sl_start");
|
|
831
|
+
const end = this.tmp("sl_end");
|
|
832
|
+
this.line(`uint64_t ${start} = ${this.expect(this.expr(args[0], U64), U64, args[0]).c};`);
|
|
833
|
+
this.line(`uint64_t ${end} = ${args[1] ? this.expect(this.expr(args[1], U64), U64, args[1]).c : vecCount(info)};`);
|
|
834
|
+
this.line(`if (${end} > ${vecCount(info)} || ${start} > ${end}) ${this.programErrorFail("AccountDataTooSmall", node)};`);
|
|
835
|
+
// Named in scope, so a loop over the slice moved into a function of its own is given them (see outlinedLoop).
|
|
836
|
+
for (const c of [start, end])
|
|
837
|
+
this.scopes.at(-1).set(`__${c}`, { c, type: U64, mutable: false });
|
|
838
|
+
const items = `((${fieldC(base.type.elem)} *)${info.items} + ${start})`;
|
|
839
|
+
return { ...base, lv: items, path: undefined, vec: { ...info, len: `(${end} - ${start})`, items, slice: true } };
|
|
840
|
+
}
|
|
688
841
|
/** A place whose type is a FixedVec (or a heap Vec) gets its Vec view. */
|
|
689
842
|
withFixedVec(r) {
|
|
690
843
|
if (r.type.kind === "vec" && r.type.cap !== undefined)
|
|
@@ -706,6 +859,10 @@ export class StorageEmitter extends AliasEmitter {
|
|
|
706
859
|
peekKind(node) {
|
|
707
860
|
return this.probe(() => this.ref(node))?.type.kind;
|
|
708
861
|
}
|
|
862
|
+
/** The type of the storage an expression names, without emitting code or failing. */
|
|
863
|
+
peekType(node) {
|
|
864
|
+
return this.probe(() => this.ref(node))?.type;
|
|
865
|
+
}
|
|
709
866
|
place(node) {
|
|
710
867
|
if (ts.isIdentifier(node)) {
|
|
711
868
|
const l = this.lookup(node.text);
|
|
@@ -1,16 +1,19 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
|
-
import { type
|
|
2
|
+
import { type CpiProgram, type Value } from "./shared.js";
|
|
3
3
|
import { CreateEmitter } from "./create.js";
|
|
4
4
|
/** SPL Token and Token-2022 instructions (`tokenProgram.transfer(…)` and the rest) and the ATA program's. */
|
|
5
5
|
export declare abstract class TokenEmitter extends CreateEmitter {
|
|
6
|
-
protected tokenOp(node: ts.CallExpression, program:
|
|
7
|
-
protected ataOp(node: ts.CallExpression, program:
|
|
6
|
+
protected tokenOp(node: ts.CallExpression, program: CpiProgram, method: string): undefined;
|
|
7
|
+
protected ataOp(node: ts.CallExpression, program: CpiProgram, method: string): undefined;
|
|
8
8
|
/** memoProgram.memo(text, signers?, signerSeeds?): SPL Memo v2, the UTF-8 text as data, each signer a signing account. */
|
|
9
|
-
protected memoOp(node: ts.CallExpression, program:
|
|
9
|
+
protected memoOp(node: ts.CallExpression, program: CpiProgram, method: string): undefined;
|
|
10
10
|
/**
|
|
11
|
-
* The Stake program (bincode: a u32 instruction tag
|
|
12
|
-
*
|
|
13
|
-
*
|
|
11
|
+
* The Stake program (bincode: a u32 instruction tag, as solana-stake-interface's StakeInstruction numbers them):
|
|
12
|
+
* initialize, authorize, delegate, split, deactivate, withdraw, merge and getMinimumDelegation, with the account
|
|
13
|
+
* metas of its instruction builders and the sysvar and config accounts it reads passed in. Each authority signs (a
|
|
14
|
+
* PDA of this program with `signerSeeds`).
|
|
14
15
|
*/
|
|
15
|
-
protected stakeOp(node: ts.CallExpression, program:
|
|
16
|
+
protected stakeOp(node: ts.CallExpression, program: CpiProgram, method: string): Value | undefined;
|
|
17
|
+
/** A stake Lockup { unix_timestamp: i64, epoch: u64, custodian: Pubkey } from `{ unixTimestamp, epoch, custodian }`. */
|
|
18
|
+
protected stakeLockup(n: ts.Expression, put: (src: string, n: string, bytes?: number) => void): void;
|
|
16
19
|
}
|