@typesol/cli 0.42.0 → 0.44.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +350 -0
- package/NOTICE +71 -0
- package/README.md +35 -18
- package/SECURITY.md +32 -5
- package/dist/ai.d.ts +1 -1
- package/dist/ai.js +5 -5
- package/dist/cli.js +196 -72
- package/dist/compiler/analyze.js +447 -12
- package/dist/compiler/diagnostics.d.ts +1 -0
- package/dist/compiler/diagnostics.js +13 -0
- package/dist/compiler/emit/alias.d.ts +45 -1
- package/dist/compiler/emit/alias.js +143 -6
- package/dist/compiler/emit/base.d.ts +28 -1
- package/dist/compiler/emit/base.js +77 -9
- package/dist/compiler/emit/borsh.js +11 -5
- package/dist/compiler/emit/calls.d.ts +80 -0
- package/dist/compiler/emit/calls.js +612 -54
- package/dist/compiler/emit/cpi-core.d.ts +23 -4
- package/dist/compiler/emit/cpi-core.js +261 -12
- package/dist/compiler/emit/cpi.js +8 -2
- package/dist/compiler/emit/create.js +3 -0
- package/dist/compiler/emit/expressions.js +44 -8
- package/dist/compiler/emit/function.js +10 -0
- 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 +25 -0
- package/dist/compiler/emit/shared.js +45 -4
- package/dist/compiler/emit/statements.d.ts +27 -1
- package/dist/compiler/emit/statements.js +305 -23
- package/dist/compiler/emit/storage.d.ts +25 -2
- package/dist/compiler/emit/storage.js +116 -64
- 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/index.d.ts +15 -1
- package/dist/compiler/index.js +40 -3
- package/dist/compiler/model.d.ts +65 -4
- package/dist/compiler/model.js +14 -0
- package/dist/compiler/toolchain.d.ts +56 -1
- package/dist/compiler/toolchain.js +246 -12
- package/dist/testing-stake.d.ts +2 -1
- package/dist/testing-stake.js +2 -1
- package/dist/testing.js +6 -4
- package/dist/tools/clientgen.d.ts +15 -0
- package/dist/tools/clientgen.js +173 -7
- package/dist/tools/cpigen.d.ts +0 -15
- package/dist/tools/cpigen.js +19 -8
- package/dist/tools/doctor.d.ts +17 -2
- package/dist/tools/doctor.js +64 -4
- package/dist/tools/portgen.js +43 -18
- package/dist/workspace.d.ts +20 -0
- package/dist/workspace.js +173 -6
- package/docs/ai.md +10 -5
- package/docs/architecture.md +10 -3
- package/docs/audit.md +63 -17
- package/docs/case-study-escrow.md +1 -1
- package/docs/case-study-phoenix.md +226 -0
- package/docs/case-study-raydium-amm.md +3 -3
- package/docs/case-study-spl-stake-pool.md +5 -5
- package/docs/cli.md +17 -8
- package/docs/client.md +11 -3
- package/docs/errors.md +1 -1
- package/docs/language.md +148 -12
- package/docs/mainnet.md +21 -10
- package/docs/migrate-from-anchor.md +3 -1
- package/docs/runtime.md +12 -2
- package/docs/security-model.md +38 -6
- package/docs/stability.md +42 -4
- package/docs/testing.md +25 -0
- package/docs/troubleshooting.md +17 -2
- package/lib/typesol.d.ts +221 -4
- package/llms-full.txt +336 -65
- package/llms.txt +2 -2
- package/package.json +4 -2
- package/runtime/typesol_rt.h +429 -13
- package/test/programs/LICENSE-Apache-2.0.txt +201 -0
|
@@ -1,7 +1,7 @@
|
|
|
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, optionKey, scalarSize, typeName } from "../model.js";
|
|
4
|
-
import { U64, BOOL, cString, fixedVecC, helperSignature, optC, scalarC, scalarStorageC, storageDecl, valueC, } from "./shared.js";
|
|
3
|
+
import { INT_INFO, isScalar, optionKey, sameType, scalarSize, typeName } from "../model.js";
|
|
4
|
+
import { U64, BOOL, PUBKEY, cString, fixedVecC, helperSignature, optC, scalarC, scalarStorageC, storageDecl, valueC, } from "./shared.js";
|
|
5
5
|
import { CpiEmitter } from "./cpi.js";
|
|
6
6
|
import { cTokens, declaredNames, isGlobalName, parameterDecls, usedNames } from "./outline.js";
|
|
7
7
|
/**
|
|
@@ -183,8 +183,9 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
183
183
|
const typed = subject.literal !== undefined ? this.literal(subject.literal, U64, stmt.expression) : subject;
|
|
184
184
|
if (typed.type.kind !== "int" && typed.type.kind !== "enum")
|
|
185
185
|
this.fail(stmt.expression, "switch works on integers and enums");
|
|
186
|
-
// C cannot switch on 128-bit values: pick the case's index with comparisons, then switch on that.
|
|
187
|
-
const
|
|
186
|
+
// C cannot switch on 128-bit values or u256 limbs: pick the case's index with comparisons, then switch on that.
|
|
187
|
+
const limbs = typed.type.kind === "int" && typed.type.name === "u256";
|
|
188
|
+
const wide = limbs || (typed.type.kind === "int" && INT_INFO[typed.type.name].bytes === 16);
|
|
188
189
|
const t = this.tmp("sw");
|
|
189
190
|
this.line(`${scalarC(typed.type)} ${t} = ${typed.c};`);
|
|
190
191
|
const pick = wide ? this.tmp("swi") : undefined;
|
|
@@ -225,7 +226,8 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
225
226
|
this.line(`}`);
|
|
226
227
|
if (pick && cases.length) {
|
|
227
228
|
const pad = " ".repeat(this.indent);
|
|
228
|
-
|
|
229
|
+
const eq = (c) => (limbs ? `ts_u256_cmp(${t}, ${c}) == 0` : `${t} == ${c}`);
|
|
230
|
+
this.lines.splice(pickAt + 1, 0, ...cases.map((c, i) => `${pad}${i ? "else " : ""}if (${eq(c)}) ${pick} = ${i};`));
|
|
229
231
|
}
|
|
230
232
|
}
|
|
231
233
|
forLoop(stmt) {
|
|
@@ -236,7 +238,8 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
236
238
|
if (ts.isVariableDeclarationList(init))
|
|
237
239
|
this.variable(init);
|
|
238
240
|
else
|
|
239
|
-
|
|
241
|
+
for (const e of commaList(init))
|
|
242
|
+
this.expressionStatement(e, false);
|
|
240
243
|
}
|
|
241
244
|
this.loop(stmt.condition, stmt.statement, stmt.incrementor);
|
|
242
245
|
});
|
|
@@ -258,6 +261,8 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
258
261
|
this.fail(stmt.expression, "iterate remaining accounts with for (let i = 0n; i < rest.length; i++) and rest.get(i)");
|
|
259
262
|
if (ts.isArrayLiteralExpression(stmt.expression) && this.functionList(stmt.expression))
|
|
260
263
|
return this.forOfFunctions(stmt, d.name);
|
|
264
|
+
if (this.treeForOf(stmt, d))
|
|
265
|
+
return;
|
|
261
266
|
// Synthetic `list.length` / `list.get(i)` nodes placed at the loop, so errors and checks point at the source.
|
|
262
267
|
const f = ts.factory;
|
|
263
268
|
const index = `__of${this.temp++}`;
|
|
@@ -284,6 +289,87 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
284
289
|
this.loops.pop();
|
|
285
290
|
});
|
|
286
291
|
}
|
|
292
|
+
/**
|
|
293
|
+
* `for (const e of tree)` / `for (const e of tree.reversed())` over a RedBlackTree: lib-sokoban's in-order
|
|
294
|
+
* iterator (a stack of nodes, left registers down, then the right one), smallest key first or, reversed, largest
|
|
295
|
+
* first. `e` is the node (`e.key`, `e.value`, `e.index`), each read where it lies. The body may change values
|
|
296
|
+
* but not the tree's structure (insert / remove / initialize on it are compile errors, as Rust's borrow forbids).
|
|
297
|
+
*/
|
|
298
|
+
treeForOf(stmt, d) {
|
|
299
|
+
let src = stmt.expression;
|
|
300
|
+
while (ts.isParenthesizedExpression(src))
|
|
301
|
+
src = src.expression;
|
|
302
|
+
let reversed = false;
|
|
303
|
+
if (ts.isCallExpression(src) &&
|
|
304
|
+
ts.isPropertyAccessExpression(src.expression) &&
|
|
305
|
+
src.expression.name.text === "reversed" &&
|
|
306
|
+
this.treeOf(src.expression.expression)) {
|
|
307
|
+
if (src.arguments.length)
|
|
308
|
+
this.fail(src, "reversed() takes no arguments");
|
|
309
|
+
reversed = true;
|
|
310
|
+
src = src.expression.expression;
|
|
311
|
+
}
|
|
312
|
+
const tree = this.treeOf(src);
|
|
313
|
+
if (!tree)
|
|
314
|
+
return false;
|
|
315
|
+
const t = tree.local.c;
|
|
316
|
+
const S = tree.inst.stride;
|
|
317
|
+
const [down, next] = reversed ? ["TS_RBT_RIGHT", "TS_RBT_LEFT"] : ["TS_RBT_LEFT", "TS_RBT_RIGHT"];
|
|
318
|
+
const stack = this.tmp("rbs");
|
|
319
|
+
const sp = this.tmp("rbsp");
|
|
320
|
+
const ptr = this.tmp("rbp");
|
|
321
|
+
const cur = this.tmp("rbc");
|
|
322
|
+
const e = this.tmp("rbe");
|
|
323
|
+
const label = this.tmp("ts_continue_");
|
|
324
|
+
const release = this.iterationClaims(stmt.statement);
|
|
325
|
+
this.line(`{`);
|
|
326
|
+
this.block(() => {
|
|
327
|
+
// The stack is walked with a pointer (no index arithmetic per step).
|
|
328
|
+
this.line(`uint32_t ${stack}[TS_RBT_STACK];`);
|
|
329
|
+
this.line(`uint32_t *${sp} = ${stack};`);
|
|
330
|
+
this.line(`uint32_t ${ptr} = TS_RBT_ROOT(${t}.base);`);
|
|
331
|
+
this.line(`while (1) {`);
|
|
332
|
+
this.block(() => {
|
|
333
|
+
// Each node's index is checked against the capacity once, when the walk steps onto it (the same panic, at the
|
|
334
|
+
// same point, as sokoban's indexing); popping it again reads its registers without a second check.
|
|
335
|
+
this.line(`while (${ptr} != 0) {`);
|
|
336
|
+
this.line(` if (${sp} == ${stack} + TS_RBT_STACK) ts_rbt_too_deep();`);
|
|
337
|
+
this.line(` *${sp}++ = ${ptr};`);
|
|
338
|
+
this.line(` ${ptr} = ((ts_u32_unaligned *)ts_rbt_node(&${t}, ${S}, ${ptr}))[${down}];`);
|
|
339
|
+
this.line(`}`);
|
|
340
|
+
this.line(`if (${sp} == ${stack}) break;`);
|
|
341
|
+
this.line(`uint32_t ${cur} = *--${sp};`);
|
|
342
|
+
this.line(`TsRbtEntry ${e} = {ts_rbt_node_checked(&${t}, ${S}, ${cur}), ${cur}};`);
|
|
343
|
+
// sokoban reads the next pointer when it yields the node, before the caller sees it.
|
|
344
|
+
this.line(`${ptr} = ((ts_u32_unaligned *)${e}.node)[${next}];`);
|
|
345
|
+
this.scopes.at(-1).set(d.name.text, {
|
|
346
|
+
c: e,
|
|
347
|
+
type: { kind: "rbEntry", inst: tree.inst.key, writable: tree.writable },
|
|
348
|
+
mutable: false,
|
|
349
|
+
paths: [`@${t}[]`],
|
|
350
|
+
decl: d,
|
|
351
|
+
});
|
|
352
|
+
const walking = !this.iteratingTrees.has(t);
|
|
353
|
+
this.iteratingTrees.set(t, { name: src.getText(), acct: tree.local.viewAcct ?? "?" });
|
|
354
|
+
this.loops.push(label);
|
|
355
|
+
try {
|
|
356
|
+
this.line(`{`);
|
|
357
|
+
this.block(() => this.body(stmt.statement));
|
|
358
|
+
this.line(`}`);
|
|
359
|
+
}
|
|
360
|
+
finally {
|
|
361
|
+
this.loops.pop();
|
|
362
|
+
if (walking)
|
|
363
|
+
this.iteratingTrees.delete(t);
|
|
364
|
+
}
|
|
365
|
+
this.line(`${label}:;`);
|
|
366
|
+
release();
|
|
367
|
+
});
|
|
368
|
+
this.line(`}`);
|
|
369
|
+
});
|
|
370
|
+
this.line(`}`);
|
|
371
|
+
return true;
|
|
372
|
+
}
|
|
287
373
|
/** The functions a list literal names (`[f, g]`: closures, helpers or choices), or undefined when it holds anything else. */
|
|
288
374
|
functionList(list) {
|
|
289
375
|
if (!list.elements.length)
|
|
@@ -835,7 +921,7 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
835
921
|
this.checkLocalListSize(t, init, "the new list");
|
|
836
922
|
this.model.localVecs.set(fixedVecC(t), t);
|
|
837
923
|
const pad = " ".repeat(this.indent);
|
|
838
|
-
this.lines[declAt] = `${pad}${fixedVecC(t)} ${c};\n${pad}
|
|
924
|
+
this.lines[declAt] = `${pad}${fixedVecC(t)} ${c};\n${pad}ts_memzero_bulk(&${c}, sizeof(${c}));`;
|
|
839
925
|
return t;
|
|
840
926
|
}
|
|
841
927
|
/** The element type of a Vec, FixedArray, FixedVec or Vec argument. */
|
|
@@ -887,8 +973,10 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
887
973
|
this.loops.pop();
|
|
888
974
|
this.line(`${label}:;`);
|
|
889
975
|
release();
|
|
976
|
+
// `i++, j--`: each update in order, all after the `continue` label.
|
|
890
977
|
if (step)
|
|
891
|
-
|
|
978
|
+
for (const e of commaList(step))
|
|
979
|
+
this.expressionStatement(e, false);
|
|
892
980
|
});
|
|
893
981
|
this.line(`}`);
|
|
894
982
|
}
|
|
@@ -898,6 +986,53 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
898
986
|
* was declared with, so a block around the call that declares the same name does not change what it reads, and
|
|
899
987
|
* writes to captured `let`s are seen by the enclosing function. Returns the result (undefined for no value).
|
|
900
988
|
*/
|
|
989
|
+
/**
|
|
990
|
+
* An `Inout<T>` parameter of a function expanded where it is called: a pointer to the caller's place (a struct,
|
|
991
|
+
* FixedArray or FixedVec), which must be writable, bound as a reference local.
|
|
992
|
+
*/
|
|
993
|
+
inoutBinding(p, arg, calleeScope, fnName) {
|
|
994
|
+
const inner = p.type.typeArguments?.[0];
|
|
995
|
+
if (!inner || p.type.typeArguments.length !== 1)
|
|
996
|
+
this.fail(p.type, "Inout<T> takes one type: a struct, FixedArray<T, N> or FixedVec<T, N>");
|
|
997
|
+
const saved = this.scope;
|
|
998
|
+
this.scope = calleeScope;
|
|
999
|
+
let list;
|
|
1000
|
+
let struct;
|
|
1001
|
+
try {
|
|
1002
|
+
list = this.listAnnotation(inner);
|
|
1003
|
+
const sn = list ? undefined : structNameOf(inner, calleeScope);
|
|
1004
|
+
struct = sn && this.model.structs.has(sn) ? sn : undefined;
|
|
1005
|
+
}
|
|
1006
|
+
finally {
|
|
1007
|
+
this.scope = saved;
|
|
1008
|
+
}
|
|
1009
|
+
const name = p.name.text;
|
|
1010
|
+
const c2 = `l_${name}_${this.temp++}`;
|
|
1011
|
+
const extra = { paths: this.pathsOf(arg), decl: p, ...(this.throughMovableList(arg) ? { movable: true } : {}) };
|
|
1012
|
+
if (struct) {
|
|
1013
|
+
const place = this.structPlace(arg);
|
|
1014
|
+
if (!place || place.struct !== struct)
|
|
1015
|
+
this.fail(arg, `${fnName}() takes ${name} as Inout<${struct}>: pass a ${struct} place of yours (a local, a field, a list element)`);
|
|
1016
|
+
if (!place.writable)
|
|
1017
|
+
this.fail(arg, `${fnName}() changes ${name} (Inout), and this place is read-only`);
|
|
1018
|
+
this.line(`TSS_${struct} *${c2} = ${place.ptr};`);
|
|
1019
|
+
return { c: c2, type: { kind: "structRef", struct, writable: true }, mutable: false, ...extra };
|
|
1020
|
+
}
|
|
1021
|
+
if (!list)
|
|
1022
|
+
this.fail(inner, `Inout<${inner.getText()}>: Inout<T> takes a struct of fixed size, a FixedArray<T, N> or a FixedVec<T, N>`);
|
|
1023
|
+
const r = this.ref(arg);
|
|
1024
|
+
if (!r || !sameType(r.type, list))
|
|
1025
|
+
this.fail(arg, `${fnName}() takes ${name} as Inout<${typeName(list)}>: pass a ${typeName(list)} of yours`);
|
|
1026
|
+
if (!r.writable)
|
|
1027
|
+
this.fail(arg, `${fnName}() changes ${name} (Inout): ${this.readOnly(r)}`);
|
|
1028
|
+
if (list.kind === "vec") {
|
|
1029
|
+
this.model.localVecs.set(fixedVecC(list), list);
|
|
1030
|
+
this.line(`${fixedVecC(list)} *${c2} = &${r.lv};`);
|
|
1031
|
+
}
|
|
1032
|
+
else
|
|
1033
|
+
this.line(`${storageDecl(list, `(*${c2})`)} = &${r.lv};`);
|
|
1034
|
+
return { c: `(*${c2})`, type: list, mutable: false, ...extra };
|
|
1035
|
+
}
|
|
901
1036
|
expandClosure(c, args, node, into) {
|
|
902
1037
|
const fn = c.node;
|
|
903
1038
|
if (this.inlining.has(fn))
|
|
@@ -919,6 +1054,11 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
919
1054
|
params.set(name, { c: "", type: BOOL, mutable: false, closure: this.closureOf(arg) });
|
|
920
1055
|
return;
|
|
921
1056
|
}
|
|
1057
|
+
// `Inout<T>` (a helper expanded here because it was given a closure): the caller's place, by reference.
|
|
1058
|
+
if (p.type && typesolName(p.type, calleeScope.imports) === "Inout") {
|
|
1059
|
+
params.set(name, this.inoutBinding(p, arg, calleeScope, c.name));
|
|
1060
|
+
return;
|
|
1061
|
+
}
|
|
922
1062
|
const passed = ts.isIdentifier(arg) && this.lookup(arg.text) ? undefined : this.accountAt(arg);
|
|
923
1063
|
if (p.type && passed && !resolveValueType(p.type, calleeScope)) {
|
|
924
1064
|
aliases.set(name, passed);
|
|
@@ -934,6 +1074,7 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
934
1074
|
type: { kind: "structRef", struct: place.struct, writable: place.writable },
|
|
935
1075
|
mutable: false,
|
|
936
1076
|
paths: this.pathsOf(arg),
|
|
1077
|
+
...(this.throughMovableList(arg) ? { movable: true } : {}),
|
|
937
1078
|
decl: p,
|
|
938
1079
|
});
|
|
939
1080
|
return;
|
|
@@ -1331,6 +1472,10 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1331
1472
|
this.destructure(list, d, d.name, d.initializer, topLevel);
|
|
1332
1473
|
continue;
|
|
1333
1474
|
}
|
|
1475
|
+
if (ts.isArrayBindingPattern(d.name)) {
|
|
1476
|
+
this.addressAndBump(d, d.name, mutable);
|
|
1477
|
+
continue;
|
|
1478
|
+
}
|
|
1334
1479
|
if (!ts.isIdentifier(d.name) || !d.initializer)
|
|
1335
1480
|
this.fail(d, "declare one plain name with an initializer");
|
|
1336
1481
|
// A local function is a helper of its own (lifted when the program was analyzed): nothing to run here.
|
|
@@ -1357,6 +1502,13 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1357
1502
|
this.fail(d.name, `"${name}" shadows the parameter "${name}"; use another name`);
|
|
1358
1503
|
const c = `l_${name}_${this.temp++}`;
|
|
1359
1504
|
const init = d.initializer;
|
|
1505
|
+
// `/** @heap */` names a list or struct type (checked again where such locals are made).
|
|
1506
|
+
if ([d, d.parent?.parent].some((n) => n && ts.getJSDocTags(n).some((t) => t.tagName.text === "heap")) &&
|
|
1507
|
+
!(d.type && (["FixedVec", "FixedArray"].includes(typesolName(d.type, this.scope.imports) ?? "") || structNameOf(d.type, this.scope))))
|
|
1508
|
+
this.heapLocal(d, false);
|
|
1509
|
+
// Run-time offset views (loadRawAt, rawArrayAt, rbTreeAt) and references into a tree's nodes (views.ts).
|
|
1510
|
+
if (this.bindView(d, init, name, c, mutable))
|
|
1511
|
+
continue;
|
|
1360
1512
|
// A function as a value: another name for one (`const h = g`), or the one a function returns (`adder(5n)`).
|
|
1361
1513
|
const made = ts.isCallExpression(init) ? this.madeFunction(init) : undefined;
|
|
1362
1514
|
const alias = ts.isIdentifier(init) ? this.functionNamed(init) : undefined;
|
|
@@ -1374,6 +1526,8 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1374
1526
|
continue;
|
|
1375
1527
|
}
|
|
1376
1528
|
const fn = ts.isCallExpression(init) ? this.exportName(init.expression) : undefined;
|
|
1529
|
+
if (d.type && typesolName(d.type, this.scope.imports) === "Inout")
|
|
1530
|
+
this.fail(d.type, "Inout<T> is for helper parameters; a local needs none (const r = acct.rec refers to that place and changes it, const copy: Rec = acct.rec is a copy)");
|
|
1377
1531
|
// The instruction's data as sent, discriminator included (a @fallback's input): a list of u8.
|
|
1378
1532
|
if (fn === "instructionData") {
|
|
1379
1533
|
if (init.arguments.length)
|
|
@@ -1438,7 +1592,16 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1438
1592
|
if (h)
|
|
1439
1593
|
loaded = { handle: h, struct: t.type.struct, mut: fn === "loadAccountMut" };
|
|
1440
1594
|
}
|
|
1441
|
-
this.scopes.at(-1).set(name, {
|
|
1595
|
+
this.scopes.at(-1).set(name, {
|
|
1596
|
+
c,
|
|
1597
|
+
type: t.type,
|
|
1598
|
+
mutable: false,
|
|
1599
|
+
paths: [`@${c}`],
|
|
1600
|
+
decl: d,
|
|
1601
|
+
loaded,
|
|
1602
|
+
...(fn === "loadRaw" || fn === "loadRawMut" ? { view: true, viewAcct: this.viewAccountKey(init.arguments[0]) } : {}),
|
|
1603
|
+
...(t.bigCap ? { bigCap: t.bigCap } : {}),
|
|
1604
|
+
});
|
|
1442
1605
|
continue;
|
|
1443
1606
|
}
|
|
1444
1607
|
// A local decoded from an account's Borsh bytes: `const pool = loadBorsh<StakePool>(acct)` (a copy, as Rust's).
|
|
@@ -1486,35 +1649,59 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1486
1649
|
this.line(l.trim());
|
|
1487
1650
|
this.line(`TSS_${S.name} *${c} = &${c}__v;`);
|
|
1488
1651
|
}
|
|
1489
|
-
|
|
1652
|
+
// A copy of the return data: never account data (owned).
|
|
1653
|
+
this.scopes
|
|
1654
|
+
.at(-1)
|
|
1655
|
+
.set(name, { c, type: { kind: "structRef", struct: S.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d, owned: true });
|
|
1490
1656
|
continue;
|
|
1491
1657
|
}
|
|
1492
1658
|
// A local list declared with its type: `const metas: FixedVec<Meta, 4> = fixedVec([{ pubkey, isSigner, … }])`,
|
|
1493
1659
|
// `const buf: FixedVec<u8, 600> = fixedVec([])`, or a copy of another list (a Vec argument, instruction data).
|
|
1494
1660
|
const listType = d.type ? this.listAnnotation(d.type) : undefined;
|
|
1661
|
+
// Struct values: `const p: Point = { x, y }` (or a copy of another Point) is a local of its own.
|
|
1662
|
+
const structType = d.type && structNameOf(d.type, this.scope) ? this.model.structs.get(structNameOf(d.type, this.scope)) : undefined;
|
|
1663
|
+
// `/** @heap */`: the local lives on the heap instead of the 4 KiB stack frame.
|
|
1664
|
+
const heap = this.heapLocal(d, !!listType || !!structType);
|
|
1495
1665
|
if (listType) {
|
|
1496
|
-
|
|
1497
|
-
|
|
1666
|
+
if (heap)
|
|
1667
|
+
this.checkHeapRoom(this.fieldBytes(listType), d.type);
|
|
1668
|
+
else
|
|
1669
|
+
this.checkLocalListSize(listType, d.type, undefined, true);
|
|
1670
|
+
let lv = c;
|
|
1671
|
+
if (listType.kind === "vec")
|
|
1498
1672
|
this.model.localVecs.set(fixedVecC(listType), listType);
|
|
1499
|
-
|
|
1500
|
-
|
|
1673
|
+
if (heap) {
|
|
1674
|
+
// One allocation per declaration and instruction (a loop reuses it): the heap is never freed.
|
|
1675
|
+
this.hoistLazy(c, (n) => (listType.kind === "vec" ? `${fixedVecC(listType)} *${n}` : storageDecl(listType, `(*${n})`)));
|
|
1676
|
+
this.line(`if (${c} == NULL) TS_TRY(ts_alloc(sizeof(*${c}), (uint8_t **)&${c}));`);
|
|
1677
|
+
lv = `(*${c})`;
|
|
1501
1678
|
}
|
|
1502
1679
|
else
|
|
1503
|
-
this.line(`${storageDecl(listType, c)};`);
|
|
1504
|
-
|
|
1505
|
-
|
|
1680
|
+
this.line(listType.kind === "vec" ? `${fixedVecC(listType)} ${c};` : `${storageDecl(listType, c)};`);
|
|
1681
|
+
// A literal zeroes its own free slots; anything else (a copy of another list) may fill only the first ones.
|
|
1682
|
+
if (listType.kind === "vec" && !this.isListLiteral(init))
|
|
1683
|
+
this.line(`ts_memzero_bulk(&${lv}, sizeof(${lv}));`);
|
|
1684
|
+
this.writeAggregate({ lv, type: listType, writable: true }, init, true);
|
|
1685
|
+
this.scopes.at(-1).set(name, { c: lv, type: listType, mutable });
|
|
1506
1686
|
continue;
|
|
1507
1687
|
}
|
|
1508
|
-
// Struct values: `const p: Point = { x, y }` (or a copy of another Point) is a local of its own.
|
|
1509
|
-
const structType = d.type && structNameOf(d.type, this.scope) ? this.model.structs.get(structNameOf(d.type, this.scope)) : undefined;
|
|
1510
1688
|
if (structType) {
|
|
1511
1689
|
if (mutable)
|
|
1512
1690
|
this.fail(d, "bind struct values with const (their fields can still be updated)");
|
|
1513
1691
|
if (structType.size === undefined || structType.vec)
|
|
1514
1692
|
this.fail(d.type, `${structType.name} has variable-size fields and cannot be a local`);
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1693
|
+
if (heap) {
|
|
1694
|
+
this.checkHeapRoom(structType.size, d.type);
|
|
1695
|
+
this.hoistLazy(`${c}__h`, (n) => `TSS_${structType.name} *${n}`);
|
|
1696
|
+
this.line(`if (${c}__h == NULL) TS_TRY(ts_alloc(sizeof(TSS_${structType.name}), (uint8_t **)&${c}__h));`);
|
|
1697
|
+
this.writeAggregate({ lv: `(*${c}__h)`, type: { kind: "struct", name: structType.name }, writable: true }, init, true);
|
|
1698
|
+
this.line(`TSS_${structType.name} *${c} = ${c}__h;`);
|
|
1699
|
+
}
|
|
1700
|
+
else {
|
|
1701
|
+
this.line(`TSS_${structType.name} ${c}__v;`);
|
|
1702
|
+
this.writeAggregate({ lv: `${c}__v`, type: { kind: "struct", name: structType.name }, writable: true }, init, true);
|
|
1703
|
+
this.line(`TSS_${structType.name} *${c} = &${c}__v;`);
|
|
1704
|
+
}
|
|
1518
1705
|
this.scopes
|
|
1519
1706
|
.at(-1)
|
|
1520
1707
|
.set(name, { c, type: { kind: "structRef", struct: structType.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d, owned: true });
|
|
@@ -1561,6 +1748,7 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1561
1748
|
type: { kind: "structRef", struct: target.struct, writable: target.writable },
|
|
1562
1749
|
mutable: false,
|
|
1563
1750
|
paths: owned ? [`@${c}`] : this.pathsOf(init),
|
|
1751
|
+
...(!owned && this.throughMovableList(init) ? { movable: true } : {}),
|
|
1564
1752
|
decl: d,
|
|
1565
1753
|
...(owned ? { owned } : {}),
|
|
1566
1754
|
});
|
|
@@ -1585,6 +1773,18 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1585
1773
|
this.scopes.at(-1).set(name, { c: v.c, type, mutable: false });
|
|
1586
1774
|
continue;
|
|
1587
1775
|
}
|
|
1776
|
+
// A tree node reached any other way than `const e = tree.min()` (`c ? t.min() : t.max()`, `t.get(k)!`): it
|
|
1777
|
+
// aliases the tree like the direct form, so it keeps the paths it may name; one whose tree is unknown is refused.
|
|
1778
|
+
if (type.kind === "rbEntry" || (type.kind === "structRef" && type.nullable)) {
|
|
1779
|
+
if (mutable)
|
|
1780
|
+
this.fail(d, "bind a tree node with const: it refers to a node of the tree");
|
|
1781
|
+
const paths = this.pathsOf(init);
|
|
1782
|
+
if (!paths)
|
|
1783
|
+
this.fail(init, "this refers to a node of a tree, and which tree is not clear here: bind the tree's own call to a const (const e = tree.min(), const o = tree.get(key))");
|
|
1784
|
+
this.line(`${valueC(type)} ${c} = ${v.c};`);
|
|
1785
|
+
this.scopes.at(-1).set(name, { c, type, mutable: false, paths, decl: d });
|
|
1786
|
+
continue;
|
|
1787
|
+
}
|
|
1588
1788
|
if ((type.kind === "account" || type.kind === "structRef") && mutable)
|
|
1589
1789
|
this.fail(d, "bind accounts with const");
|
|
1590
1790
|
if (type.kind === "pubkey")
|
|
@@ -1596,6 +1796,69 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1596
1796
|
this.scopes.at(-1).set(name, { c, type, mutable, ...(owned ? { paths: [`@${c}`], owned } : {}) });
|
|
1597
1797
|
}
|
|
1598
1798
|
}
|
|
1799
|
+
/**
|
|
1800
|
+
* Whether a declaration is `/** @heap *\/`: a local list or struct kept on the heap (the bump allocator) rather
|
|
1801
|
+
* than in the function's 4 KiB stack frame. Only in an instruction, which runs once per instruction: a helper may
|
|
1802
|
+
* run any number of times and the heap is never freed.
|
|
1803
|
+
*/
|
|
1804
|
+
heapLocal(d, aggregate) {
|
|
1805
|
+
const tag = [d, d.parent?.parent].flatMap((n) => (n ? ts.getJSDocTags(n) : [])).find((t) => t.tagName.text === "heap");
|
|
1806
|
+
if (!tag)
|
|
1807
|
+
return false;
|
|
1808
|
+
if (!aggregate)
|
|
1809
|
+
this.fail(d, "@heap is for a local list or struct declared with its type (const buf: FixedVec<u8, 1024> = …)");
|
|
1810
|
+
if (this.helper)
|
|
1811
|
+
this.fail(d, "@heap locals belong to instructions: a helper may run many times per instruction and the heap is never freed; declare it in the instruction and pass it (Inout<T>)");
|
|
1812
|
+
return true;
|
|
1813
|
+
}
|
|
1814
|
+
/** A `@heap` local must fit in the heap (32 KiB, or HEAP_SIZE_KIB), which other allocations share. */
|
|
1815
|
+
checkHeapRoom(bytes, at) {
|
|
1816
|
+
const kib = this.model.constants.get("HEAP_SIZE_KIB")?.value;
|
|
1817
|
+
const room = (typeof kib === "bigint" ? Number(kib) : 32) * 1024 - 8;
|
|
1818
|
+
if (bytes > room)
|
|
1819
|
+
this.fail(at, `this local takes ${bytes} bytes and the heap holds ${room} (raise HEAP_SIZE_KIB, at most 256)`);
|
|
1820
|
+
}
|
|
1821
|
+
/**
|
|
1822
|
+
* `const [address, bump] = findProgramAddressWithBump(seeds, program)`: Rust's `let (address, bump) =
|
|
1823
|
+
* Pubkey::find_program_address(…)`, both from one search (the only array destructuring the language has).
|
|
1824
|
+
*/
|
|
1825
|
+
addressAndBump(d, pattern, mutable) {
|
|
1826
|
+
const init = d.initializer;
|
|
1827
|
+
const call = init && ts.isCallExpression(init) && this.exportName(init.expression) === "findProgramAddressWithBump" ? init : undefined;
|
|
1828
|
+
if (!call)
|
|
1829
|
+
this.fail(d.name, "array destructuring is only for const [address, bump] = findProgramAddressWithBump(seeds, program)");
|
|
1830
|
+
if (mutable)
|
|
1831
|
+
this.fail(d, "bind them with const: const [address, bump] = findProgramAddressWithBump(seeds, program)");
|
|
1832
|
+
if (d.type)
|
|
1833
|
+
this.fail(d.type, "leave the type out: the address is a Pubkey and the bump a u8");
|
|
1834
|
+
if (pattern.elements.length > 2)
|
|
1835
|
+
this.fail(pattern, "findProgramAddressWithBump gives two values: const [address, bump] = …");
|
|
1836
|
+
const names = pattern.elements.map((el) => {
|
|
1837
|
+
if (ts.isOmittedExpression(el))
|
|
1838
|
+
return undefined;
|
|
1839
|
+
if (el.dotDotDotToken || el.initializer || !ts.isIdentifier(el.name))
|
|
1840
|
+
this.fail(el, "name the address and the bump: const [address, bump] = findProgramAddressWithBump(seeds, program)");
|
|
1841
|
+
const name = el.name.text;
|
|
1842
|
+
if (this.scopes.at(-1).has(name))
|
|
1843
|
+
this.fail(el.name, `"${name}" is already declared`);
|
|
1844
|
+
if (this.accounts.has(name) || this.args.has(name) || this.isGroup(name))
|
|
1845
|
+
this.fail(el.name, `"${name}" shadows the parameter "${name}"; use another name`);
|
|
1846
|
+
return name;
|
|
1847
|
+
});
|
|
1848
|
+
if (call.arguments.length !== 2)
|
|
1849
|
+
this.fail(call, "findProgramAddressWithBump(seeds, program) takes the seeds and the program's address");
|
|
1850
|
+
const seeds = this.seeds(call.arguments[0], 0);
|
|
1851
|
+
const program = this.expect(this.expr(call.arguments[1], PUBKEY), PUBKEY, call.arguments[1]);
|
|
1852
|
+
const [address, bump] = names;
|
|
1853
|
+
const key = address ? `l_${address}_${this.temp++}` : this.tmp("pda");
|
|
1854
|
+
const b = bump ? `l_${bump}_${this.temp++}` : this.tmp("bump");
|
|
1855
|
+
this.line(`SolPubkey ${key}; uint8_t ${b};`);
|
|
1856
|
+
this.line(`if (ts_find_pda(${seeds.name}, ${seeds.count}, ${program.c}, &${key}, &${b}) != SUCCESS) TS_FAIL(TS_ERR_SEEDS, "TypeSOL: no program address for these seeds");`);
|
|
1857
|
+
if (address)
|
|
1858
|
+
this.scopes.at(-1).set(address, { c: key, type: PUBKEY, mutable: false });
|
|
1859
|
+
if (bump)
|
|
1860
|
+
this.scopes.at(-1).set(bump, { c: b, type: { kind: "int", name: "u8" }, mutable: false });
|
|
1861
|
+
}
|
|
1599
1862
|
/**
|
|
1600
1863
|
* `const { a, b: c } = s`: one declaration per name, `const a = s.a`, in source order. The source must be a name or
|
|
1601
1864
|
* a field path (no calls), so reading it once per name reads the same thing JS reads once.
|
|
@@ -1729,7 +1992,18 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1729
1992
|
return;
|
|
1730
1993
|
}
|
|
1731
1994
|
const mark = this.lines.length;
|
|
1732
|
-
|
|
1995
|
+
// `x <<= n` / `x >>= n`: the amount has a type of its own, as in `x << n` (a literal is a u64).
|
|
1996
|
+
const shift = op === ts.SyntaxKind.LessThanLessThanToken || op === ts.SyntaxKind.GreaterThanGreaterThanToken;
|
|
1997
|
+
let rhs;
|
|
1998
|
+
if (shift) {
|
|
1999
|
+
rhs = this.expr(valueNode);
|
|
2000
|
+
if (rhs.literal !== undefined)
|
|
2001
|
+
rhs = this.literal(rhs.literal, U64, valueNode);
|
|
2002
|
+
if (rhs.type.kind !== "int")
|
|
2003
|
+
this.fail(valueNode, "shift amounts must be integers");
|
|
2004
|
+
}
|
|
2005
|
+
else
|
|
2006
|
+
rhs = this.expect(this.expr(valueNode, place.type), place.type, valueNode);
|
|
1733
2007
|
current = this.settle(current, mark);
|
|
1734
2008
|
this.line(place.write(this.arith(op, current, rhs, target).c) + ";");
|
|
1735
2009
|
return;
|
|
@@ -1773,3 +2047,11 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1773
2047
|
this.line(place.write(value.c) + ";");
|
|
1774
2048
|
}
|
|
1775
2049
|
}
|
|
2050
|
+
/** The expressions of a comma list (`i++, j--` in a for loop's update or initializer), left to right. */
|
|
2051
|
+
function commaList(e) {
|
|
2052
|
+
while (ts.isParenthesizedExpression(e))
|
|
2053
|
+
e = e.expression;
|
|
2054
|
+
if (ts.isBinaryExpression(e) && e.operatorToken.kind === ts.SyntaxKind.CommaToken)
|
|
2055
|
+
return [...commaList(e.left), ...commaList(e.right)];
|
|
2056
|
+
return [e];
|
|
2057
|
+
}
|
|
@@ -29,11 +29,13 @@ export declare abstract class StorageEmitter extends AliasEmitter {
|
|
|
29
29
|
protected looksLikeStructPlace(node: ts.Expression): boolean;
|
|
30
30
|
/**
|
|
31
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 may take at most 2 KiB, so the failure is a clear compile error, not clang's
|
|
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.
|
|
33
35
|
*/
|
|
34
36
|
protected checkLocalListSize(t: FieldType & {
|
|
35
37
|
kind: "vec" | "array";
|
|
36
|
-
}, at: ts.Node, what?: string): void;
|
|
38
|
+
}, at: ts.Node, what?: string, declared?: boolean): void;
|
|
37
39
|
/**
|
|
38
40
|
* `FixedVec<T, N>` / `FixedArray<T, N>` written as a local's type: T an integer, boolean, Pubkey, enum,
|
|
39
41
|
* `FixedString<N>` or fixed-size struct, N a literal. Undefined for other types; a list type with anything else fails.
|
|
@@ -65,6 +67,8 @@ export declare abstract class StorageEmitter extends AliasEmitter {
|
|
|
65
67
|
protected lowerInOrder(nodes: readonly ts.Expression[], types: ValueType[]): Value[];
|
|
66
68
|
/** An index evaluated into a temporary (sign and 128-bit range checked), bounds not yet checked. */
|
|
67
69
|
protected indexValue(n: ts.Expression): string;
|
|
70
|
+
/** An integer index in a u64 temporary: a negative one, or one past u64 (128-bit, u256 limbs), is out of bounds. */
|
|
71
|
+
private indexTemp;
|
|
68
72
|
protected checkIndex(t: string, len: string): void;
|
|
69
73
|
/** Bounds-checked index into a temporary. `len` is a C expression. */
|
|
70
74
|
protected index(n: ts.Expression, len: string | number): string;
|
|
@@ -79,11 +83,28 @@ export declare abstract class StorageEmitter extends AliasEmitter {
|
|
|
79
83
|
*/
|
|
80
84
|
/** A whole struct account copied as a value (`return vault`, `info = vault`): fixed-size structs only. */
|
|
81
85
|
private wholeAccount;
|
|
86
|
+
/**
|
|
87
|
+
* A data enum literal (`{ kind: "Variant", … }`), checked: its variant, and `writeFields(base)`, which evaluates the
|
|
88
|
+
* fields in source order (as JS does) into `${base}.<field>`, a `TSV_<Enum>__<Variant>` place (or, given a function,
|
|
89
|
+
* into the place it names for each field).
|
|
90
|
+
*/
|
|
91
|
+
protected dataEnumLiteral(name: string, valueNode: ts.ObjectLiteralExpression): {
|
|
92
|
+
e: import("../model.js").DataEnumDef;
|
|
93
|
+
vi: number;
|
|
94
|
+
variant: {
|
|
95
|
+
name: string;
|
|
96
|
+
fields: import("../model.js").StructField[];
|
|
97
|
+
size: number;
|
|
98
|
+
};
|
|
99
|
+
writeFields: (base: string | ((field: string) => string)) => void;
|
|
100
|
+
};
|
|
82
101
|
/**
|
|
83
102
|
* Write an aggregate value into `target`. `fresh`: the target is a value just declared (or a temporary), which no
|
|
84
103
|
* expression can read yet, so a literal is built in it directly rather than in a temporary first.
|
|
85
104
|
*/
|
|
86
105
|
protected writeAggregate(target: Ref, valueNode: ts.Expression, fresh?: boolean): void;
|
|
106
|
+
/** `fixedVec([…])` or `[…]`: a list literal, which writeAggregate builds in a fresh target with its free slots zeroed. */
|
|
107
|
+
protected isListLiteral(node: ts.Expression): boolean;
|
|
87
108
|
/** The Vec view of a FixedVec stored at `lv` (`{ len, items[cap] }`). */
|
|
88
109
|
protected fixedVec(lv: string, elem: FieldType, cap: number): NonNullable<Ref["vec"]>;
|
|
89
110
|
/** A heap Vec (a Vec<T> in a `@layout borsh` struct) at `lv`: `{ len, cap, items }`, grown by ts_hvec_reserve. */
|
|
@@ -103,6 +124,8 @@ export declare abstract class StorageEmitter extends AliasEmitter {
|
|
|
103
124
|
protected peekArray(node: ts.Expression): boolean;
|
|
104
125
|
/** The kind of storage an expression names (struct, array, dataEnum…), without emitting code or failing. */
|
|
105
126
|
protected peekKind(node: ts.Expression): FieldType["kind"] | undefined;
|
|
127
|
+
/** The type of the storage an expression names, without emitting code or failing. */
|
|
128
|
+
protected peekType(node: ts.Expression): FieldType | undefined;
|
|
106
129
|
protected place(node: ts.Expression): {
|
|
107
130
|
type: ValueType;
|
|
108
131
|
read: string;
|