@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
|
@@ -1,8 +1,9 @@
|
|
|
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, optC, scalarC, scalarStorageC, 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
|
+
import { cTokens, declaredNames, isGlobalName, parameterDecls, usedNames } from "./outline.js";
|
|
6
7
|
/**
|
|
7
8
|
* Statements: variables, assignment, control flow and return.
|
|
8
9
|
*/
|
|
@@ -235,7 +236,8 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
235
236
|
if (ts.isVariableDeclarationList(init))
|
|
236
237
|
this.variable(init);
|
|
237
238
|
else
|
|
238
|
-
|
|
239
|
+
for (const e of commaList(init))
|
|
240
|
+
this.expressionStatement(e, false);
|
|
239
241
|
}
|
|
240
242
|
this.loop(stmt.condition, stmt.statement, stmt.incrementor);
|
|
241
243
|
});
|
|
@@ -257,6 +259,8 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
257
259
|
this.fail(stmt.expression, "iterate remaining accounts with for (let i = 0n; i < rest.length; i++) and rest.get(i)");
|
|
258
260
|
if (ts.isArrayLiteralExpression(stmt.expression) && this.functionList(stmt.expression))
|
|
259
261
|
return this.forOfFunctions(stmt, d.name);
|
|
262
|
+
if (this.treeForOf(stmt, d))
|
|
263
|
+
return;
|
|
260
264
|
// Synthetic `list.length` / `list.get(i)` nodes placed at the loop, so errors and checks point at the source.
|
|
261
265
|
const f = ts.factory;
|
|
262
266
|
const index = `__of${this.temp++}`;
|
|
@@ -269,7 +273,7 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
269
273
|
const ci = this.tmp("of_i");
|
|
270
274
|
const label = this.tmp("ts_continue_");
|
|
271
275
|
const release = this.iterationClaims(stmt.statement);
|
|
272
|
-
this.eachElement(stmt.expression, stmt, { index, ci, next: label, alwaysNext: true, atNext: release }, (element) => {
|
|
276
|
+
this.eachElement(stmt.expression, stmt, { index, ci, next: label, alwaysNext: true, atNext: release, body: stmt.statement }, (element) => {
|
|
273
277
|
// The element's declaration: the source's own name (so aliasing checks find its uses) bound to the element.
|
|
274
278
|
const decl = f.createVariableDeclaration(d.name, undefined, undefined, element);
|
|
275
279
|
ts.setTextRange(decl, d);
|
|
@@ -283,6 +287,87 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
283
287
|
this.loops.pop();
|
|
284
288
|
});
|
|
285
289
|
}
|
|
290
|
+
/**
|
|
291
|
+
* `for (const e of tree)` / `for (const e of tree.reversed())` over a RedBlackTree: lib-sokoban's in-order
|
|
292
|
+
* iterator (a stack of nodes, left registers down, then the right one), smallest key first or, reversed, largest
|
|
293
|
+
* first. `e` is the node (`e.key`, `e.value`, `e.index`), each read where it lies. The body may change values
|
|
294
|
+
* but not the tree's structure (insert / remove / initialize on it are compile errors, as Rust's borrow forbids).
|
|
295
|
+
*/
|
|
296
|
+
treeForOf(stmt, d) {
|
|
297
|
+
let src = stmt.expression;
|
|
298
|
+
while (ts.isParenthesizedExpression(src))
|
|
299
|
+
src = src.expression;
|
|
300
|
+
let reversed = false;
|
|
301
|
+
if (ts.isCallExpression(src) &&
|
|
302
|
+
ts.isPropertyAccessExpression(src.expression) &&
|
|
303
|
+
src.expression.name.text === "reversed" &&
|
|
304
|
+
this.treeOf(src.expression.expression)) {
|
|
305
|
+
if (src.arguments.length)
|
|
306
|
+
this.fail(src, "reversed() takes no arguments");
|
|
307
|
+
reversed = true;
|
|
308
|
+
src = src.expression.expression;
|
|
309
|
+
}
|
|
310
|
+
const tree = this.treeOf(src);
|
|
311
|
+
if (!tree)
|
|
312
|
+
return false;
|
|
313
|
+
const t = tree.local.c;
|
|
314
|
+
const S = tree.inst.stride;
|
|
315
|
+
const [down, next] = reversed ? ["TS_RBT_RIGHT", "TS_RBT_LEFT"] : ["TS_RBT_LEFT", "TS_RBT_RIGHT"];
|
|
316
|
+
const stack = this.tmp("rbs");
|
|
317
|
+
const sp = this.tmp("rbsp");
|
|
318
|
+
const ptr = this.tmp("rbp");
|
|
319
|
+
const cur = this.tmp("rbc");
|
|
320
|
+
const e = this.tmp("rbe");
|
|
321
|
+
const label = this.tmp("ts_continue_");
|
|
322
|
+
const release = this.iterationClaims(stmt.statement);
|
|
323
|
+
this.line(`{`);
|
|
324
|
+
this.block(() => {
|
|
325
|
+
// The stack is walked with a pointer (no index arithmetic per step).
|
|
326
|
+
this.line(`uint32_t ${stack}[TS_RBT_STACK];`);
|
|
327
|
+
this.line(`uint32_t *${sp} = ${stack};`);
|
|
328
|
+
this.line(`uint32_t ${ptr} = TS_RBT_ROOT(${t}.base);`);
|
|
329
|
+
this.line(`while (1) {`);
|
|
330
|
+
this.block(() => {
|
|
331
|
+
// Each node's index is checked against the capacity once, when the walk steps onto it (the same panic, at the
|
|
332
|
+
// same point, as sokoban's indexing); popping it again reads its registers without a second check.
|
|
333
|
+
this.line(`while (${ptr} != 0) {`);
|
|
334
|
+
this.line(` if (${sp} == ${stack} + TS_RBT_STACK) ts_rbt_too_deep();`);
|
|
335
|
+
this.line(` *${sp}++ = ${ptr};`);
|
|
336
|
+
this.line(` ${ptr} = ((ts_u32_unaligned *)ts_rbt_node(&${t}, ${S}, ${ptr}))[${down}];`);
|
|
337
|
+
this.line(`}`);
|
|
338
|
+
this.line(`if (${sp} == ${stack}) break;`);
|
|
339
|
+
this.line(`uint32_t ${cur} = *--${sp};`);
|
|
340
|
+
this.line(`TsRbtEntry ${e} = {ts_rbt_node_checked(&${t}, ${S}, ${cur}), ${cur}};`);
|
|
341
|
+
// sokoban reads the next pointer when it yields the node, before the caller sees it.
|
|
342
|
+
this.line(`${ptr} = ((ts_u32_unaligned *)${e}.node)[${next}];`);
|
|
343
|
+
this.scopes.at(-1).set(d.name.text, {
|
|
344
|
+
c: e,
|
|
345
|
+
type: { kind: "rbEntry", inst: tree.inst.key, writable: tree.writable },
|
|
346
|
+
mutable: false,
|
|
347
|
+
paths: [`@${t}[]`],
|
|
348
|
+
decl: d,
|
|
349
|
+
});
|
|
350
|
+
const walking = !this.iteratingTrees.has(t);
|
|
351
|
+
this.iteratingTrees.set(t, { name: src.getText(), acct: tree.local.viewAcct ?? "?" });
|
|
352
|
+
this.loops.push(label);
|
|
353
|
+
try {
|
|
354
|
+
this.line(`{`);
|
|
355
|
+
this.block(() => this.body(stmt.statement));
|
|
356
|
+
this.line(`}`);
|
|
357
|
+
}
|
|
358
|
+
finally {
|
|
359
|
+
this.loops.pop();
|
|
360
|
+
if (walking)
|
|
361
|
+
this.iteratingTrees.delete(t);
|
|
362
|
+
}
|
|
363
|
+
this.line(`${label}:;`);
|
|
364
|
+
release();
|
|
365
|
+
});
|
|
366
|
+
this.line(`}`);
|
|
367
|
+
});
|
|
368
|
+
this.line(`}`);
|
|
369
|
+
return true;
|
|
370
|
+
}
|
|
286
371
|
/** The functions a list literal names (`[f, g]`: closures, helpers or choices), or undefined when it holds anything else. */
|
|
287
372
|
functionList(list) {
|
|
288
373
|
if (!list.elements.length)
|
|
@@ -449,11 +534,53 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
449
534
|
}
|
|
450
535
|
if (stages.length) {
|
|
451
536
|
const l = ts.isIdentifier(base) ? this.lookup(base.text) : undefined;
|
|
452
|
-
if (!(l?.type.kind === "vecArg" || l?.type.kind === "array" || this.peekArray(base)))
|
|
537
|
+
if (!(l?.type.kind === "vecArg" || l?.type.kind === "array" || this.peekArray(base) || this.isVecArgView(base) || this.isInlineArray(base)))
|
|
453
538
|
this.fail(base, "map and filter work on a Vec, FixedArray or FixedVec");
|
|
454
539
|
}
|
|
455
540
|
return { base, stages };
|
|
456
541
|
}
|
|
542
|
+
/** List bases already made into locals (see holdList), so a list method and the loop under it make them once. */
|
|
543
|
+
heldLists = new Map();
|
|
544
|
+
/**
|
|
545
|
+
* A list written inline that must be made before it is read: `fixedArray<T, N>(fill)` (a local array, filled once)
|
|
546
|
+
* or a slice of a Vec argument or the instruction data (a view, range-checked once). Made here, in a local named by
|
|
547
|
+
* a synthetic identifier the loop reads; undefined for any other list (read in place).
|
|
548
|
+
*/
|
|
549
|
+
holdList(base) {
|
|
550
|
+
const held = this.heldLists.get(base);
|
|
551
|
+
if (held)
|
|
552
|
+
return held;
|
|
553
|
+
let made;
|
|
554
|
+
if (this.isInlineArray(base)) {
|
|
555
|
+
let call = base;
|
|
556
|
+
while (ts.isParenthesizedExpression(call))
|
|
557
|
+
call = call.expression;
|
|
558
|
+
const c = this.tmp("fa");
|
|
559
|
+
made = { c, type: this.localArray(call, c), mutable: false };
|
|
560
|
+
}
|
|
561
|
+
else if (!ts.isIdentifier(base) && this.isVecArgView(base)) {
|
|
562
|
+
const v = this.vecArgView(base);
|
|
563
|
+
made = { c: v.c, type: v.type, mutable: false };
|
|
564
|
+
}
|
|
565
|
+
if (!made)
|
|
566
|
+
return undefined;
|
|
567
|
+
const id = ts.factory.createIdentifier(`__hl${this.temp++}`);
|
|
568
|
+
ts.setTextRange(id, base);
|
|
569
|
+
id.parent = base.parent;
|
|
570
|
+
this.scopes.at(-1).set(id.text, made);
|
|
571
|
+
return id;
|
|
572
|
+
}
|
|
573
|
+
/** The type of an inline `fixedArray<T, N>(fill)` from its type arguments, without emitting code. */
|
|
574
|
+
inlineArrayType(e) {
|
|
575
|
+
while (ts.isParenthesizedExpression(e))
|
|
576
|
+
e = e.expression;
|
|
577
|
+
if (!this.isInlineArray(e))
|
|
578
|
+
return undefined;
|
|
579
|
+
const [elemNode, lenNode] = e.typeArguments ?? [];
|
|
580
|
+
const elem = elemNode && this.localElem(elemNode);
|
|
581
|
+
const len = lenNode && ts.isLiteralTypeNode(lenNode) && ts.isNumericLiteral(lenNode.literal) ? Number(lenNode.literal.text) : NaN;
|
|
582
|
+
return elem && Number.isInteger(len) ? { kind: "array", elem, len } : undefined;
|
|
583
|
+
}
|
|
457
584
|
/**
|
|
458
585
|
* Run `body` for each element of a list, or of a chain of `map` / `filter` calls on one (`xs.filter(f).map(g)`):
|
|
459
586
|
* one index loop over the list (its length read every step, as `for … of`), each callback expanded in it. A
|
|
@@ -462,13 +589,31 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
462
589
|
* filter, the count of elements it let through, as JS gives callbacks).
|
|
463
590
|
*/
|
|
464
591
|
eachElement(list, at, names, body) {
|
|
592
|
+
const stagesOf = this.pipelineStages(list);
|
|
593
|
+
const { stages } = stagesOf;
|
|
594
|
+
// An inline fixedArray(…) or a slice of a Vec argument / the instruction data: made once, before the loop.
|
|
595
|
+
const base = this.holdList(stagesOf.base) ?? stagesOf.base;
|
|
596
|
+
// A BigVec slice is lowered (and range-checked) once, here; the loop reads its length and elements from that.
|
|
597
|
+
const sliced = ts.isCallExpression(base) && ts.isPropertyAccessExpression(base.expression) && base.expression.name.text === "slice" ? this.ref(base) : undefined;
|
|
598
|
+
if (sliced?.vec?.slice)
|
|
599
|
+
this.sliceViews.set(base, sliced);
|
|
600
|
+
try {
|
|
601
|
+
// A BigVec runs to the size of its account (20,000 validators): its loops get a C function of their own.
|
|
602
|
+
const big = (sliced ?? this.probe(() => this.ref(base)))?.vec?.big !== undefined;
|
|
603
|
+
if (!big || !this.outlinedLoop(names.body, () => this.eachElementLoop(base, stages, at, names, body)))
|
|
604
|
+
this.eachElementLoop(base, stages, at, names, body);
|
|
605
|
+
}
|
|
606
|
+
finally {
|
|
607
|
+
this.sliceViews.delete(base);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
eachElementLoop(base, stages, at, names, body) {
|
|
465
611
|
const f = ts.factory;
|
|
466
612
|
const place = (n) => {
|
|
467
613
|
ts.setTextRange(n, at);
|
|
468
614
|
n.parent = at;
|
|
469
615
|
return n;
|
|
470
616
|
};
|
|
471
|
-
const { base, stages } = this.pipelineStages(list);
|
|
472
617
|
const { index, ci } = names;
|
|
473
618
|
const indexId = place(f.createIdentifier(index));
|
|
474
619
|
const length = place(f.createPropertyAccessExpression(base, "length"));
|
|
@@ -558,6 +703,139 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
558
703
|
});
|
|
559
704
|
this.line(`}`);
|
|
560
705
|
}
|
|
706
|
+
/**
|
|
707
|
+
* Run `emit` (a loop) as a C function of its own, called here: `TS_TRY(fn__loopN(params, …))`. SBF has ten
|
|
708
|
+
* registers, four of them kept across calls; a loop inside a large function shares them with every value the
|
|
709
|
+
* function holds across it, and clang spills the loop's own (the stake pool's pass over 20,000 validators paid a
|
|
710
|
+
* reload and a store per entry). A function of its own has them all. It gets the caller's variables the loop uses:
|
|
711
|
+
* by value when the loop only reads them, else through a pointer, copied in and back out when it is done (a failure
|
|
712
|
+
* returns at once, as it would here). False, with nothing emitted, when the loop cannot move: its body returns from
|
|
713
|
+
* the function, declares an account (create), or uses a variable of the caller that is not one of its locals or
|
|
714
|
+
* parameters (a claim slot, a list held in place); it then stays where it is.
|
|
715
|
+
*/
|
|
716
|
+
outlinedLoop(body, emit) {
|
|
717
|
+
const returns = (n) => ts.isReturnStatement(n) || (!ts.isFunctionLike(n) && !ts.isClassLike(n) && (ts.forEachChild(n, returns) ?? false));
|
|
718
|
+
if (body && returns(body))
|
|
719
|
+
return false;
|
|
720
|
+
// The variables visible here, by C name (innermost first, as lookup finds them).
|
|
721
|
+
const visible = new Map();
|
|
722
|
+
for (const scope of [...[...this.scopes].reverse(), this.args])
|
|
723
|
+
for (const l of scope.values())
|
|
724
|
+
if (!visible.has(l.c))
|
|
725
|
+
visible.set(l.c, l);
|
|
726
|
+
const saved = {
|
|
727
|
+
lines: this.lines,
|
|
728
|
+
hoisted: this.hoisted,
|
|
729
|
+
indent: this.indent,
|
|
730
|
+
temp: this.temp,
|
|
731
|
+
diagnostics: this.reporter.diagnostics.length,
|
|
732
|
+
outlined: this.outlinedLoops.length,
|
|
733
|
+
seedArrays: new Map(this.seedArrays),
|
|
734
|
+
state: () => JSON.stringify([[...this.created], [...this.pendingInit], [...this.bumps]]),
|
|
735
|
+
};
|
|
736
|
+
const state = saved.state();
|
|
737
|
+
this.lines = [];
|
|
738
|
+
this.hoisted = [];
|
|
739
|
+
this.indent = 1;
|
|
740
|
+
let lines;
|
|
741
|
+
let hoisted;
|
|
742
|
+
try {
|
|
743
|
+
emit();
|
|
744
|
+
}
|
|
745
|
+
finally {
|
|
746
|
+
lines = this.lines;
|
|
747
|
+
hoisted = this.hoisted;
|
|
748
|
+
this.lines = saved.lines;
|
|
749
|
+
this.hoisted = saved.hoisted;
|
|
750
|
+
this.indent = saved.indent;
|
|
751
|
+
// Seed arrays the loop declared live in its function (their positions are in its lines).
|
|
752
|
+
this.seedArrays.clear();
|
|
753
|
+
saved.seedArrays.forEach((v, k) => this.seedArrays.set(k, v));
|
|
754
|
+
}
|
|
755
|
+
const plan = saved.state() === state ? this.outlinedParams([...hoisted, ...lines].join("\n"), visible) : undefined;
|
|
756
|
+
if (!plan) {
|
|
757
|
+
this.temp = saved.temp;
|
|
758
|
+
this.reporter.diagnostics.length = saved.diagnostics;
|
|
759
|
+
this.outlinedLoops.length = saved.outlined;
|
|
760
|
+
return false;
|
|
761
|
+
}
|
|
762
|
+
// Heap buffers taken on first use stay declared in the caller, which passes each in by pointer: declared in the
|
|
763
|
+
// loop's function, every call of it would take a new one (an emit or a helper's argument copy in a loop run many
|
|
764
|
+
// times would exhaust the heap).
|
|
765
|
+
const lazy = hoisted.filter((l) => this.lazyHoists.has(l));
|
|
766
|
+
for (const l of lazy) {
|
|
767
|
+
const { name: buffer, decl } = this.lazyHoists.get(l);
|
|
768
|
+
this.hoisted.push(l);
|
|
769
|
+
plan.params.push(decl(`*cp_${buffer}`));
|
|
770
|
+
plan.args.push(`&${buffer}`);
|
|
771
|
+
plan.copyIn.push(` ${decl(buffer)} = *cp_${buffer};`);
|
|
772
|
+
plan.copyOut.push(` *cp_${buffer} = ${buffer};`);
|
|
773
|
+
}
|
|
774
|
+
hoisted = hoisted.filter((l) => !lazy.includes(l));
|
|
775
|
+
const name = `${this.helper ? `fn_${this.helper.name}` : `ix_${this.ix.name}`}__loop${this.outlinedLoops.length}`;
|
|
776
|
+
this.outlinedLoops.push([
|
|
777
|
+
`static __attribute__((noinline)) uint64_t ${name}(${["TsParams *params", ...plan.params].join(", ")}) {`,
|
|
778
|
+
...plan.copyIn,
|
|
779
|
+
...hoisted,
|
|
780
|
+
...lines,
|
|
781
|
+
...plan.copyOut,
|
|
782
|
+
` return SUCCESS;`,
|
|
783
|
+
`}`,
|
|
784
|
+
``,
|
|
785
|
+
].join("\n"));
|
|
786
|
+
this.line(`TS_TRY(${name}(${["params", ...plan.args].join(", ")}));`);
|
|
787
|
+
return true;
|
|
788
|
+
}
|
|
789
|
+
/**
|
|
790
|
+
* The parameters a loop moved out of this function takes for the caller's variables its C uses, or undefined when
|
|
791
|
+
* it uses one that cannot be passed (or that is not a local or parameter at all).
|
|
792
|
+
*/
|
|
793
|
+
outlinedParams(c, visible) {
|
|
794
|
+
const toks = cTokens(c);
|
|
795
|
+
const own = declaredNames(toks);
|
|
796
|
+
const signature = this.helper ? parameterDecls(helperSignature(this.helper)) : new Map();
|
|
797
|
+
const out = { params: [], args: [], copyIn: [], copyOut: [] };
|
|
798
|
+
for (const n of [...usedNames(toks)].sort()) {
|
|
799
|
+
if (own.has(n) || n === "params" || isGlobalName(n))
|
|
800
|
+
continue;
|
|
801
|
+
const param = signature.get(n);
|
|
802
|
+
if (param) {
|
|
803
|
+
out.params.push(param);
|
|
804
|
+
out.args.push(n);
|
|
805
|
+
continue;
|
|
806
|
+
}
|
|
807
|
+
if (this.ix && n.startsWith("a_") && this.accounts.has(n.slice(2))) {
|
|
808
|
+
out.params.push(`TsAccount *${n}`);
|
|
809
|
+
out.args.push(n);
|
|
810
|
+
continue;
|
|
811
|
+
}
|
|
812
|
+
const l = visible.get(n);
|
|
813
|
+
if (!l || l.closure || l.choice)
|
|
814
|
+
return undefined;
|
|
815
|
+
const t = l.type;
|
|
816
|
+
if (t.kind === "array" ||
|
|
817
|
+
t.kind === "vec" ||
|
|
818
|
+
t.kind === "remaining" ||
|
|
819
|
+
t.kind === "arrayArg" ||
|
|
820
|
+
t.kind === "optionArg" ||
|
|
821
|
+
t.kind === "signerSeeds" ||
|
|
822
|
+
t.kind === "dataEnumArg")
|
|
823
|
+
return undefined;
|
|
824
|
+
const ct = t.kind === "pubkey" ? (l.ptr ? "const SolPubkey *" : "SolPubkey") : valueC(t);
|
|
825
|
+
const decl = (name) => (ct.endsWith("*") ? `${ct}${name}` : `${ct} ${name}`);
|
|
826
|
+
if (!l.mutable && (ct.endsWith("*") || t.kind === "int" || t.kind === "bool" || t.kind === "enum")) {
|
|
827
|
+
out.params.push(decl(n));
|
|
828
|
+
out.args.push(n);
|
|
829
|
+
continue;
|
|
830
|
+
}
|
|
831
|
+
out.params.push(decl(`*cp_${n}`));
|
|
832
|
+
out.args.push(`&${n}`);
|
|
833
|
+
out.copyIn.push(` ${decl(n)} = *cp_${n};`);
|
|
834
|
+
if (l.mutable)
|
|
835
|
+
out.copyOut.push(` *cp_${n} = ${n};`);
|
|
836
|
+
}
|
|
837
|
+
return out;
|
|
838
|
+
}
|
|
561
839
|
/**
|
|
562
840
|
* `const ys = xs.map(…)` / `xs.filter(…)`: the chain's elements in a local FixedVec, as big as the list it starts
|
|
563
841
|
* from (a FixedArray's length, a FixedVec's capacity) or as annotated (`const ys: FixedVec<u64, 16> = …`, needed
|
|
@@ -585,7 +863,11 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
585
863
|
this.fail(t, "annotate the new list as FixedVec<T, N> (N a literal)");
|
|
586
864
|
cap = n;
|
|
587
865
|
}
|
|
866
|
+
else if (this.inlineArrayType(base))
|
|
867
|
+
cap = this.inlineArrayType(base).len;
|
|
588
868
|
else {
|
|
869
|
+
if (this.isVecArgView(base))
|
|
870
|
+
this.fail(init, "this list has no fixed size: annotate the new one with its capacity, const ys: FixedVec<T, N> = …");
|
|
589
871
|
const r = this.reporter.guard(() => this.ref(base));
|
|
590
872
|
const l = ts.isIdentifier(base) ? this.lookup(base.text) : undefined;
|
|
591
873
|
if (r?.type.kind === "array")
|
|
@@ -634,17 +916,28 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
634
916
|
this.line(`${c}.len++;`);
|
|
635
917
|
});
|
|
636
918
|
const t = { kind: "vec", elem: annotatedElem ?? elem, cap: cap0 };
|
|
637
|
-
|
|
638
|
-
if (bytes > 2048)
|
|
639
|
-
this.fail(init, `the new list takes ${bytes} bytes; locals live on the 4 KiB stack, so keep it under 2 KiB (a smaller FixedVec<T, N>)`);
|
|
919
|
+
this.checkLocalListSize(t, init, "the new list");
|
|
640
920
|
this.model.localVecs.set(fixedVecC(t), t);
|
|
641
921
|
const pad = " ".repeat(this.indent);
|
|
642
|
-
this.lines[declAt] = `${pad}${fixedVecC(t)} ${c};\n${pad}
|
|
922
|
+
this.lines[declAt] = `${pad}${fixedVecC(t)} ${c};\n${pad}ts_memzero_bulk(&${c}, sizeof(${c}));`;
|
|
643
923
|
return t;
|
|
644
924
|
}
|
|
645
925
|
/** The element type of a Vec, FixedArray, FixedVec or Vec argument. */
|
|
646
926
|
listElem(list) {
|
|
647
|
-
const
|
|
927
|
+
const inline = this.inlineArrayType(list);
|
|
928
|
+
if (inline)
|
|
929
|
+
return inline.elem;
|
|
930
|
+
// A slice of a Vec argument or the instruction data: the elements of the list it slices.
|
|
931
|
+
let root = list;
|
|
932
|
+
for (;;) {
|
|
933
|
+
if (ts.isParenthesizedExpression(root))
|
|
934
|
+
root = root.expression;
|
|
935
|
+
else if (ts.isCallExpression(root) && ts.isPropertyAccessExpression(root.expression) && root.expression.name.text === "slice" && this.isVecArgView(root))
|
|
936
|
+
root = root.expression.expression;
|
|
937
|
+
else
|
|
938
|
+
break;
|
|
939
|
+
}
|
|
940
|
+
const l = ts.isIdentifier(root) ? this.lookup(root.text) : undefined;
|
|
648
941
|
if (l?.type.kind === "vecArg")
|
|
649
942
|
return l.type.elem;
|
|
650
943
|
const r = this.ref(list);
|
|
@@ -678,8 +971,10 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
678
971
|
this.loops.pop();
|
|
679
972
|
this.line(`${label}:;`);
|
|
680
973
|
release();
|
|
974
|
+
// `i++, j--`: each update in order, all after the `continue` label.
|
|
681
975
|
if (step)
|
|
682
|
-
|
|
976
|
+
for (const e of commaList(step))
|
|
977
|
+
this.expressionStatement(e, false);
|
|
683
978
|
});
|
|
684
979
|
this.line(`}`);
|
|
685
980
|
}
|
|
@@ -689,6 +984,53 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
689
984
|
* was declared with, so a block around the call that declares the same name does not change what it reads, and
|
|
690
985
|
* writes to captured `let`s are seen by the enclosing function. Returns the result (undefined for no value).
|
|
691
986
|
*/
|
|
987
|
+
/**
|
|
988
|
+
* An `Inout<T>` parameter of a function expanded where it is called: a pointer to the caller's place (a struct,
|
|
989
|
+
* FixedArray or FixedVec), which must be writable, bound as a reference local.
|
|
990
|
+
*/
|
|
991
|
+
inoutBinding(p, arg, calleeScope, fnName) {
|
|
992
|
+
const inner = p.type.typeArguments?.[0];
|
|
993
|
+
if (!inner || p.type.typeArguments.length !== 1)
|
|
994
|
+
this.fail(p.type, "Inout<T> takes one type: a struct, FixedArray<T, N> or FixedVec<T, N>");
|
|
995
|
+
const saved = this.scope;
|
|
996
|
+
this.scope = calleeScope;
|
|
997
|
+
let list;
|
|
998
|
+
let struct;
|
|
999
|
+
try {
|
|
1000
|
+
list = this.listAnnotation(inner);
|
|
1001
|
+
const sn = list ? undefined : structNameOf(inner, calleeScope);
|
|
1002
|
+
struct = sn && this.model.structs.has(sn) ? sn : undefined;
|
|
1003
|
+
}
|
|
1004
|
+
finally {
|
|
1005
|
+
this.scope = saved;
|
|
1006
|
+
}
|
|
1007
|
+
const name = p.name.text;
|
|
1008
|
+
const c2 = `l_${name}_${this.temp++}`;
|
|
1009
|
+
const extra = { paths: this.pathsOf(arg), decl: p, ...(this.throughMovableList(arg) ? { movable: true } : {}) };
|
|
1010
|
+
if (struct) {
|
|
1011
|
+
const place = this.structPlace(arg);
|
|
1012
|
+
if (!place || place.struct !== struct)
|
|
1013
|
+
this.fail(arg, `${fnName}() takes ${name} as Inout<${struct}>: pass a ${struct} place of yours (a local, a field, a list element)`);
|
|
1014
|
+
if (!place.writable)
|
|
1015
|
+
this.fail(arg, `${fnName}() changes ${name} (Inout), and this place is read-only`);
|
|
1016
|
+
this.line(`TSS_${struct} *${c2} = ${place.ptr};`);
|
|
1017
|
+
return { c: c2, type: { kind: "structRef", struct, writable: true }, mutable: false, ...extra };
|
|
1018
|
+
}
|
|
1019
|
+
if (!list)
|
|
1020
|
+
this.fail(inner, `Inout<${inner.getText()}>: Inout<T> takes a struct of fixed size, a FixedArray<T, N> or a FixedVec<T, N>`);
|
|
1021
|
+
const r = this.ref(arg);
|
|
1022
|
+
if (!r || !sameType(r.type, list))
|
|
1023
|
+
this.fail(arg, `${fnName}() takes ${name} as Inout<${typeName(list)}>: pass a ${typeName(list)} of yours`);
|
|
1024
|
+
if (!r.writable)
|
|
1025
|
+
this.fail(arg, `${fnName}() changes ${name} (Inout): ${this.readOnly(r)}`);
|
|
1026
|
+
if (list.kind === "vec") {
|
|
1027
|
+
this.model.localVecs.set(fixedVecC(list), list);
|
|
1028
|
+
this.line(`${fixedVecC(list)} *${c2} = &${r.lv};`);
|
|
1029
|
+
}
|
|
1030
|
+
else
|
|
1031
|
+
this.line(`${storageDecl(list, `(*${c2})`)} = &${r.lv};`);
|
|
1032
|
+
return { c: `(*${c2})`, type: list, mutable: false, ...extra };
|
|
1033
|
+
}
|
|
692
1034
|
expandClosure(c, args, node, into) {
|
|
693
1035
|
const fn = c.node;
|
|
694
1036
|
if (this.inlining.has(fn))
|
|
@@ -710,6 +1052,11 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
710
1052
|
params.set(name, { c: "", type: BOOL, mutable: false, closure: this.closureOf(arg) });
|
|
711
1053
|
return;
|
|
712
1054
|
}
|
|
1055
|
+
// `Inout<T>` (a helper expanded here because it was given a closure): the caller's place, by reference.
|
|
1056
|
+
if (p.type && typesolName(p.type, calleeScope.imports) === "Inout") {
|
|
1057
|
+
params.set(name, this.inoutBinding(p, arg, calleeScope, c.name));
|
|
1058
|
+
return;
|
|
1059
|
+
}
|
|
713
1060
|
const passed = ts.isIdentifier(arg) && this.lookup(arg.text) ? undefined : this.accountAt(arg);
|
|
714
1061
|
if (p.type && passed && !resolveValueType(p.type, calleeScope)) {
|
|
715
1062
|
aliases.set(name, passed);
|
|
@@ -725,6 +1072,7 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
725
1072
|
type: { kind: "structRef", struct: place.struct, writable: place.writable },
|
|
726
1073
|
mutable: false,
|
|
727
1074
|
paths: this.pathsOf(arg),
|
|
1075
|
+
...(this.throughMovableList(arg) ? { movable: true } : {}),
|
|
728
1076
|
decl: p,
|
|
729
1077
|
});
|
|
730
1078
|
return;
|
|
@@ -830,6 +1178,20 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
830
1178
|
* `find` gives an Option of the element (scalar elements), `findIndex` / `indexOf` an i64 (-1 when absent).
|
|
831
1179
|
*/
|
|
832
1180
|
listMethod(node, method) {
|
|
1181
|
+
// A list written inline is made first, as JS evaluates the receiver before the arguments (reduce's initial value).
|
|
1182
|
+
const base = this.pipelineStages(node.expression.expression).base;
|
|
1183
|
+
const held = this.holdList(base);
|
|
1184
|
+
if (!held)
|
|
1185
|
+
return this.listMethodLoop(node, method);
|
|
1186
|
+
this.heldLists.set(base, held);
|
|
1187
|
+
try {
|
|
1188
|
+
return this.listMethodLoop(node, method);
|
|
1189
|
+
}
|
|
1190
|
+
finally {
|
|
1191
|
+
this.heldLists.delete(base);
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
listMethodLoop(node, method) {
|
|
833
1195
|
const access = node.expression;
|
|
834
1196
|
const list = access.expression;
|
|
835
1197
|
const args = node.arguments;
|
|
@@ -892,6 +1254,9 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
892
1254
|
this.line(`/* ${res} */`);
|
|
893
1255
|
}
|
|
894
1256
|
const findDecl = method === "find" ? this.lines.length - 1 : -1;
|
|
1257
|
+
// The result is the loop's to set: named in scope, so a loop moved into a function of its own gets it (outlinedLoop).
|
|
1258
|
+
if (result && method !== "find")
|
|
1259
|
+
this.scopes.at(-1).set(`__${res}`, { c: res, type: result.type, mutable: true });
|
|
895
1260
|
const ci = this.tmp("lm_i");
|
|
896
1261
|
this.eachElement(list, node, { index, ci }, (element, indexId) => {
|
|
897
1262
|
if (valueForm) {
|
|
@@ -1105,6 +1470,10 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1105
1470
|
this.destructure(list, d, d.name, d.initializer, topLevel);
|
|
1106
1471
|
continue;
|
|
1107
1472
|
}
|
|
1473
|
+
if (ts.isArrayBindingPattern(d.name)) {
|
|
1474
|
+
this.addressAndBump(d, d.name, mutable);
|
|
1475
|
+
continue;
|
|
1476
|
+
}
|
|
1108
1477
|
if (!ts.isIdentifier(d.name) || !d.initializer)
|
|
1109
1478
|
this.fail(d, "declare one plain name with an initializer");
|
|
1110
1479
|
// A local function is a helper of its own (lifted when the program was analyzed): nothing to run here.
|
|
@@ -1131,6 +1500,13 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1131
1500
|
this.fail(d.name, `"${name}" shadows the parameter "${name}"; use another name`);
|
|
1132
1501
|
const c = `l_${name}_${this.temp++}`;
|
|
1133
1502
|
const init = d.initializer;
|
|
1503
|
+
// `/** @heap */` names a list or struct type (checked again where such locals are made).
|
|
1504
|
+
if ([d, d.parent?.parent].some((n) => n && ts.getJSDocTags(n).some((t) => t.tagName.text === "heap")) &&
|
|
1505
|
+
!(d.type && (["FixedVec", "FixedArray"].includes(typesolName(d.type, this.scope.imports) ?? "") || structNameOf(d.type, this.scope))))
|
|
1506
|
+
this.heapLocal(d, false);
|
|
1507
|
+
// Run-time offset views (loadRawAt, rawArrayAt, rbTreeAt) and references into a tree's nodes (views.ts).
|
|
1508
|
+
if (this.bindView(d, init, name, c, mutable))
|
|
1509
|
+
continue;
|
|
1134
1510
|
// A function as a value: another name for one (`const h = g`), or the one a function returns (`adder(5n)`).
|
|
1135
1511
|
const made = ts.isCallExpression(init) ? this.madeFunction(init) : undefined;
|
|
1136
1512
|
const alias = ts.isIdentifier(init) ? this.functionNamed(init) : undefined;
|
|
@@ -1148,6 +1524,8 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1148
1524
|
continue;
|
|
1149
1525
|
}
|
|
1150
1526
|
const fn = ts.isCallExpression(init) ? this.exportName(init.expression) : undefined;
|
|
1527
|
+
if (d.type && typesolName(d.type, this.scope.imports) === "Inout")
|
|
1528
|
+
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)");
|
|
1151
1529
|
// The instruction's data as sent, discriminator included (a @fallback's input): a list of u8.
|
|
1152
1530
|
if (fn === "instructionData") {
|
|
1153
1531
|
if (init.arguments.length)
|
|
@@ -1186,7 +1564,7 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1186
1564
|
continue;
|
|
1187
1565
|
}
|
|
1188
1566
|
if (fn === "fixedArray") {
|
|
1189
|
-
const t = this.localArray(init, c);
|
|
1567
|
+
const t = this.localArray(init, c, d.type);
|
|
1190
1568
|
this.scopes.at(-1).set(name, { c, type: t, mutable });
|
|
1191
1569
|
continue;
|
|
1192
1570
|
}
|
|
@@ -1212,7 +1590,30 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1212
1590
|
if (h)
|
|
1213
1591
|
loaded = { handle: h, struct: t.type.struct, mut: fn === "loadAccountMut" };
|
|
1214
1592
|
}
|
|
1215
|
-
this.scopes.at(-1).set(name, {
|
|
1593
|
+
this.scopes.at(-1).set(name, {
|
|
1594
|
+
c,
|
|
1595
|
+
type: t.type,
|
|
1596
|
+
mutable: false,
|
|
1597
|
+
paths: [`@${c}`],
|
|
1598
|
+
decl: d,
|
|
1599
|
+
loaded,
|
|
1600
|
+
...(fn === "loadRaw" || fn === "loadRawMut" ? { view: true, viewAcct: this.viewAccountKey(init.arguments[0]) } : {}),
|
|
1601
|
+
...(t.bigCap ? { bigCap: t.bigCap } : {}),
|
|
1602
|
+
});
|
|
1603
|
+
continue;
|
|
1604
|
+
}
|
|
1605
|
+
// A local decoded from an account's Borsh bytes: `const pool = loadBorsh<StakePool>(acct)` (a copy, as Rust's).
|
|
1606
|
+
if (fn === "loadBorsh") {
|
|
1607
|
+
if (mutable)
|
|
1608
|
+
this.fail(d, "bind loadBorsh<T>(...) with const (its fields can still be updated)");
|
|
1609
|
+
const named = d.type && structNameOf(d.type, this.scope);
|
|
1610
|
+
const declared = named ? this.model.structs.get(named) : undefined;
|
|
1611
|
+
if (d.type && !declared)
|
|
1612
|
+
this.fail(d.type, "loadBorsh returns a struct: declare the local as one (or leave the type out)");
|
|
1613
|
+
const s = this.loadBorsh(init, c, declared);
|
|
1614
|
+
this.scopes
|
|
1615
|
+
.at(-1)
|
|
1616
|
+
.set(name, { c, type: { kind: "structRef", struct: s.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d, owned: true });
|
|
1216
1617
|
continue;
|
|
1217
1618
|
}
|
|
1218
1619
|
// A struct another program returned: `const q = returnData<Quote>(amm)` (Anchor's `get_return_data` + deserialize).
|
|
@@ -1223,14 +1624,14 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1223
1624
|
const call = init;
|
|
1224
1625
|
if (call.arguments.length !== 1)
|
|
1225
1626
|
this.fail(call, "returnData<T>(program) takes the program that returned it");
|
|
1226
|
-
const program = this.
|
|
1627
|
+
const program = this.anyAccount(call.arguments[0], "returnData's program");
|
|
1227
1628
|
const bad = `TS_FAIL(TS_ERR_RETURN_DATA, "TypeSOL: invalid ${S.name} return data")`;
|
|
1228
1629
|
if (S.layout === "borsh") {
|
|
1229
1630
|
// Borsh of any size: unpacked into the fixed-layout struct, every byte used.
|
|
1230
1631
|
const raw = `${c}__raw`;
|
|
1231
1632
|
this.line(`uint8_t *${raw};`);
|
|
1232
1633
|
this.line(`uint64_t ${raw}_len = 0, ${raw}_used = 0;`);
|
|
1233
|
-
this.line(`TS_TRY(ts_return_data_any(
|
|
1634
|
+
this.line(`TS_TRY(ts_return_data_any(${program}, &${raw}, &${raw}_len));`);
|
|
1234
1635
|
this.line(`TSS_${S.name} *${c};`);
|
|
1235
1636
|
this.line(`TS_TRY(ts_alloc(sizeof(TSS_${S.name}), (uint8_t **)&${c}));`);
|
|
1236
1637
|
this.line(`if (ts_unpack_${S.name}(${raw}, ${raw}_len, ${c}, &${raw}_used) != SUCCESS || ${raw}_used != ${raw}_len) ${bad};`);
|
|
@@ -1241,24 +1642,64 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1241
1642
|
else {
|
|
1242
1643
|
// A fixed layout whose bytes are its Borsh form: copied in, then bools and enums checked.
|
|
1243
1644
|
this.line(`TSS_${S.name} ${c}__v;`);
|
|
1244
|
-
this.line(`TS_TRY(ts_return_data_exact(
|
|
1645
|
+
this.line(`TS_TRY(ts_return_data_exact(${program}, &${c}__v, sizeof(TSS_${S.name})));`);
|
|
1245
1646
|
for (const l of this.validation(`${c}__v`, { kind: "struct", name: S.name }, "", bad))
|
|
1246
1647
|
this.line(l.trim());
|
|
1247
1648
|
this.line(`TSS_${S.name} *${c} = &${c}__v;`);
|
|
1248
1649
|
}
|
|
1249
|
-
|
|
1650
|
+
// A copy of the return data: never account data (owned).
|
|
1651
|
+
this.scopes
|
|
1652
|
+
.at(-1)
|
|
1653
|
+
.set(name, { c, type: { kind: "structRef", struct: S.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d, owned: true });
|
|
1250
1654
|
continue;
|
|
1251
1655
|
}
|
|
1656
|
+
// A local list declared with its type: `const metas: FixedVec<Meta, 4> = fixedVec([{ pubkey, isSigner, … }])`,
|
|
1657
|
+
// `const buf: FixedVec<u8, 600> = fixedVec([])`, or a copy of another list (a Vec argument, instruction data).
|
|
1658
|
+
const listType = d.type ? this.listAnnotation(d.type) : undefined;
|
|
1252
1659
|
// Struct values: `const p: Point = { x, y }` (or a copy of another Point) is a local of its own.
|
|
1253
1660
|
const structType = d.type && structNameOf(d.type, this.scope) ? this.model.structs.get(structNameOf(d.type, this.scope)) : undefined;
|
|
1661
|
+
// `/** @heap */`: the local lives on the heap instead of the 4 KiB stack frame.
|
|
1662
|
+
const heap = this.heapLocal(d, !!listType || !!structType);
|
|
1663
|
+
if (listType) {
|
|
1664
|
+
if (heap)
|
|
1665
|
+
this.checkHeapRoom(this.fieldBytes(listType), d.type);
|
|
1666
|
+
else
|
|
1667
|
+
this.checkLocalListSize(listType, d.type, undefined, true);
|
|
1668
|
+
let lv = c;
|
|
1669
|
+
if (listType.kind === "vec")
|
|
1670
|
+
this.model.localVecs.set(fixedVecC(listType), listType);
|
|
1671
|
+
if (heap) {
|
|
1672
|
+
// One allocation per declaration and instruction (a loop reuses it): the heap is never freed.
|
|
1673
|
+
this.hoistLazy(c, (n) => (listType.kind === "vec" ? `${fixedVecC(listType)} *${n}` : storageDecl(listType, `(*${n})`)));
|
|
1674
|
+
this.line(`if (${c} == NULL) TS_TRY(ts_alloc(sizeof(*${c}), (uint8_t **)&${c}));`);
|
|
1675
|
+
lv = `(*${c})`;
|
|
1676
|
+
}
|
|
1677
|
+
else
|
|
1678
|
+
this.line(listType.kind === "vec" ? `${fixedVecC(listType)} ${c};` : `${storageDecl(listType, c)};`);
|
|
1679
|
+
// A literal zeroes its own free slots; anything else (a copy of another list) may fill only the first ones.
|
|
1680
|
+
if (listType.kind === "vec" && !this.isListLiteral(init))
|
|
1681
|
+
this.line(`ts_memzero_bulk(&${lv}, sizeof(${lv}));`);
|
|
1682
|
+
this.writeAggregate({ lv, type: listType, writable: true }, init, true);
|
|
1683
|
+
this.scopes.at(-1).set(name, { c: lv, type: listType, mutable });
|
|
1684
|
+
continue;
|
|
1685
|
+
}
|
|
1254
1686
|
if (structType) {
|
|
1255
1687
|
if (mutable)
|
|
1256
1688
|
this.fail(d, "bind struct values with const (their fields can still be updated)");
|
|
1257
1689
|
if (structType.size === undefined || structType.vec)
|
|
1258
1690
|
this.fail(d.type, `${structType.name} has variable-size fields and cannot be a local`);
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1691
|
+
if (heap) {
|
|
1692
|
+
this.checkHeapRoom(structType.size, d.type);
|
|
1693
|
+
this.hoistLazy(`${c}__h`, (n) => `TSS_${structType.name} *${n}`);
|
|
1694
|
+
this.line(`if (${c}__h == NULL) TS_TRY(ts_alloc(sizeof(TSS_${structType.name}), (uint8_t **)&${c}__h));`);
|
|
1695
|
+
this.writeAggregate({ lv: `(*${c}__h)`, type: { kind: "struct", name: structType.name }, writable: true }, init, true);
|
|
1696
|
+
this.line(`TSS_${structType.name} *${c} = ${c}__h;`);
|
|
1697
|
+
}
|
|
1698
|
+
else {
|
|
1699
|
+
this.line(`TSS_${structType.name} ${c}__v;`);
|
|
1700
|
+
this.writeAggregate({ lv: `${c}__v`, type: { kind: "struct", name: structType.name }, writable: true }, init, true);
|
|
1701
|
+
this.line(`TSS_${structType.name} *${c} = &${c}__v;`);
|
|
1702
|
+
}
|
|
1262
1703
|
this.scopes
|
|
1263
1704
|
.at(-1)
|
|
1264
1705
|
.set(name, { c, type: { kind: "structRef", struct: structType.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d, owned: true });
|
|
@@ -1305,13 +1746,16 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1305
1746
|
type: { kind: "structRef", struct: target.struct, writable: target.writable },
|
|
1306
1747
|
mutable: false,
|
|
1307
1748
|
paths: owned ? [`@${c}`] : this.pathsOf(init),
|
|
1749
|
+
...(!owned && this.throughMovableList(init) ? { movable: true } : {}),
|
|
1308
1750
|
decl: d,
|
|
1309
1751
|
...(owned ? { owned } : {}),
|
|
1310
1752
|
});
|
|
1311
1753
|
continue;
|
|
1312
1754
|
}
|
|
1313
1755
|
let declared;
|
|
1314
|
-
if (d.type)
|
|
1756
|
+
if (d.type && typesolName(d.type, this.scope.imports) === "EpochRewards")
|
|
1757
|
+
declared = { kind: "epochRewards" };
|
|
1758
|
+
else if (d.type) {
|
|
1315
1759
|
declared = resolveValueType(d.type, this.scope);
|
|
1316
1760
|
if (!declared || declared.kind === "vecArg")
|
|
1317
1761
|
this.fail(d.type, "local type must be an integer, boolean, Pubkey, enum, option or string");
|
|
@@ -1327,6 +1771,18 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1327
1771
|
this.scopes.at(-1).set(name, { c: v.c, type, mutable: false });
|
|
1328
1772
|
continue;
|
|
1329
1773
|
}
|
|
1774
|
+
// A tree node reached any other way than `const e = tree.min()` (`c ? t.min() : t.max()`, `t.get(k)!`): it
|
|
1775
|
+
// aliases the tree like the direct form, so it keeps the paths it may name; one whose tree is unknown is refused.
|
|
1776
|
+
if (type.kind === "rbEntry" || (type.kind === "structRef" && type.nullable)) {
|
|
1777
|
+
if (mutable)
|
|
1778
|
+
this.fail(d, "bind a tree node with const: it refers to a node of the tree");
|
|
1779
|
+
const paths = this.pathsOf(init);
|
|
1780
|
+
if (!paths)
|
|
1781
|
+
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))");
|
|
1782
|
+
this.line(`${valueC(type)} ${c} = ${v.c};`);
|
|
1783
|
+
this.scopes.at(-1).set(name, { c, type, mutable: false, paths, decl: d });
|
|
1784
|
+
continue;
|
|
1785
|
+
}
|
|
1330
1786
|
if ((type.kind === "account" || type.kind === "structRef") && mutable)
|
|
1331
1787
|
this.fail(d, "bind accounts with const");
|
|
1332
1788
|
if (type.kind === "pubkey")
|
|
@@ -1338,6 +1794,69 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1338
1794
|
this.scopes.at(-1).set(name, { c, type, mutable, ...(owned ? { paths: [`@${c}`], owned } : {}) });
|
|
1339
1795
|
}
|
|
1340
1796
|
}
|
|
1797
|
+
/**
|
|
1798
|
+
* Whether a declaration is `/** @heap *\/`: a local list or struct kept on the heap (the bump allocator) rather
|
|
1799
|
+
* than in the function's 4 KiB stack frame. Only in an instruction, which runs once per instruction: a helper may
|
|
1800
|
+
* run any number of times and the heap is never freed.
|
|
1801
|
+
*/
|
|
1802
|
+
heapLocal(d, aggregate) {
|
|
1803
|
+
const tag = [d, d.parent?.parent].flatMap((n) => (n ? ts.getJSDocTags(n) : [])).find((t) => t.tagName.text === "heap");
|
|
1804
|
+
if (!tag)
|
|
1805
|
+
return false;
|
|
1806
|
+
if (!aggregate)
|
|
1807
|
+
this.fail(d, "@heap is for a local list or struct declared with its type (const buf: FixedVec<u8, 1024> = …)");
|
|
1808
|
+
if (this.helper)
|
|
1809
|
+
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>)");
|
|
1810
|
+
return true;
|
|
1811
|
+
}
|
|
1812
|
+
/** A `@heap` local must fit in the heap (32 KiB, or HEAP_SIZE_KIB), which other allocations share. */
|
|
1813
|
+
checkHeapRoom(bytes, at) {
|
|
1814
|
+
const kib = this.model.constants.get("HEAP_SIZE_KIB")?.value;
|
|
1815
|
+
const room = (typeof kib === "bigint" ? Number(kib) : 32) * 1024 - 8;
|
|
1816
|
+
if (bytes > room)
|
|
1817
|
+
this.fail(at, `this local takes ${bytes} bytes and the heap holds ${room} (raise HEAP_SIZE_KIB, at most 256)`);
|
|
1818
|
+
}
|
|
1819
|
+
/**
|
|
1820
|
+
* `const [address, bump] = findProgramAddressWithBump(seeds, program)`: Rust's `let (address, bump) =
|
|
1821
|
+
* Pubkey::find_program_address(…)`, both from one search (the only array destructuring the language has).
|
|
1822
|
+
*/
|
|
1823
|
+
addressAndBump(d, pattern, mutable) {
|
|
1824
|
+
const init = d.initializer;
|
|
1825
|
+
const call = init && ts.isCallExpression(init) && this.exportName(init.expression) === "findProgramAddressWithBump" ? init : undefined;
|
|
1826
|
+
if (!call)
|
|
1827
|
+
this.fail(d.name, "array destructuring is only for const [address, bump] = findProgramAddressWithBump(seeds, program)");
|
|
1828
|
+
if (mutable)
|
|
1829
|
+
this.fail(d, "bind them with const: const [address, bump] = findProgramAddressWithBump(seeds, program)");
|
|
1830
|
+
if (d.type)
|
|
1831
|
+
this.fail(d.type, "leave the type out: the address is a Pubkey and the bump a u8");
|
|
1832
|
+
if (pattern.elements.length > 2)
|
|
1833
|
+
this.fail(pattern, "findProgramAddressWithBump gives two values: const [address, bump] = …");
|
|
1834
|
+
const names = pattern.elements.map((el) => {
|
|
1835
|
+
if (ts.isOmittedExpression(el))
|
|
1836
|
+
return undefined;
|
|
1837
|
+
if (el.dotDotDotToken || el.initializer || !ts.isIdentifier(el.name))
|
|
1838
|
+
this.fail(el, "name the address and the bump: const [address, bump] = findProgramAddressWithBump(seeds, program)");
|
|
1839
|
+
const name = el.name.text;
|
|
1840
|
+
if (this.scopes.at(-1).has(name))
|
|
1841
|
+
this.fail(el.name, `"${name}" is already declared`);
|
|
1842
|
+
if (this.accounts.has(name) || this.args.has(name) || this.isGroup(name))
|
|
1843
|
+
this.fail(el.name, `"${name}" shadows the parameter "${name}"; use another name`);
|
|
1844
|
+
return name;
|
|
1845
|
+
});
|
|
1846
|
+
if (call.arguments.length !== 2)
|
|
1847
|
+
this.fail(call, "findProgramAddressWithBump(seeds, program) takes the seeds and the program's address");
|
|
1848
|
+
const seeds = this.seeds(call.arguments[0], 0);
|
|
1849
|
+
const program = this.expect(this.expr(call.arguments[1], PUBKEY), PUBKEY, call.arguments[1]);
|
|
1850
|
+
const [address, bump] = names;
|
|
1851
|
+
const key = address ? `l_${address}_${this.temp++}` : this.tmp("pda");
|
|
1852
|
+
const b = bump ? `l_${bump}_${this.temp++}` : this.tmp("bump");
|
|
1853
|
+
this.line(`SolPubkey ${key}; uint8_t ${b};`);
|
|
1854
|
+
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");`);
|
|
1855
|
+
if (address)
|
|
1856
|
+
this.scopes.at(-1).set(address, { c: key, type: PUBKEY, mutable: false });
|
|
1857
|
+
if (bump)
|
|
1858
|
+
this.scopes.at(-1).set(bump, { c: b, type: { kind: "int", name: "u8" }, mutable: false });
|
|
1859
|
+
}
|
|
1341
1860
|
/**
|
|
1342
1861
|
* `const { a, b: c } = s`: one declaration per name, `const a = s.a`, in source order. The source must be a name or
|
|
1343
1862
|
* a field path (no calls), so reading it once per name reads the same thing JS reads once.
|
|
@@ -1515,3 +2034,11 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1515
2034
|
this.line(place.write(value.c) + ";");
|
|
1516
2035
|
}
|
|
1517
2036
|
}
|
|
2037
|
+
/** The expressions of a comma list (`i++, j--` in a for loop's update or initializer), left to right. */
|
|
2038
|
+
function commaList(e) {
|
|
2039
|
+
while (ts.isParenthesizedExpression(e))
|
|
2040
|
+
e = e.expression;
|
|
2041
|
+
if (ts.isBinaryExpression(e) && e.operatorToken.kind === ts.SyntaxKind.CommaToken)
|
|
2042
|
+
return [...commaList(e.left), ...commaList(e.right)];
|
|
2043
|
+
return [e];
|
|
2044
|
+
}
|