@typesol/cli 0.41.0 → 0.42.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 +92 -0
- package/README.md +2 -1
- package/dist/compiler/analyze.js +41 -1
- package/dist/compiler/emit/base.d.ts +40 -7
- package/dist/compiler/emit/base.js +33 -0
- package/dist/compiler/emit/borsh.d.ts +7 -0
- package/dist/compiler/emit/borsh.js +86 -1
- package/dist/compiler/emit/calls.d.ts +102 -2
- package/dist/compiler/emit/calls.js +663 -49
- package/dist/compiler/emit/cpi-core.d.ts +9 -3
- package/dist/compiler/emit/cpi-core.js +12 -7
- package/dist/compiler/emit/cpi.js +8 -14
- package/dist/compiler/emit/create.d.ts +3 -3
- package/dist/compiler/emit/create.js +33 -25
- package/dist/compiler/emit/expressions.js +51 -2
- 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 +7 -2
- package/dist/compiler/emit/shared.d.ts +35 -1
- package/dist/compiler/emit/shared.js +9 -1
- package/dist/compiler/emit/statements.d.ts +31 -0
- package/dist/compiler/emit/statements.js +272 -14
- package/dist/compiler/emit/storage.d.ts +27 -1
- package/dist/compiler/emit/storage.js +124 -11
- package/dist/compiler/emit/token.d.ts +11 -8
- package/dist/compiler/emit/token.js +233 -104
- package/dist/compiler/hints.js +6 -0
- package/dist/compiler/model.d.ts +20 -1
- package/dist/compiler/model.js +5 -0
- 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 +1 -1
- package/docs/case-study-spl-stake-pool.md +122 -0
- package/docs/errors.md +1 -1
- package/docs/language.md +107 -14
- package/docs/security-model.md +4 -0
- package/docs/stability.md +13 -0
- package/docs/test-your-program.md +47 -0
- package/docs/testing.md +19 -0
- package/lib/typesol.d.ts +241 -40
- package/llms-full.txt +172 -15
- package/llms.txt +1 -1
- package/package.json +1 -1
- package/runtime/typesol_rt.h +69 -0
|
@@ -23,6 +23,26 @@ export declare const HASH: ScalarType;
|
|
|
23
23
|
* A lowered expression: a side-effect-free C expression plus its type.
|
|
24
24
|
* Pubkeys are `const SolPubkey *`, strings are `TS_Str` views.
|
|
25
25
|
*/
|
|
26
|
+
/**
|
|
27
|
+
* An account a typed CPI names (`stakeProgram.split(stake, …)`): `c` is its `TsAccount *`. `param` is set for a
|
|
28
|
+
* declared account parameter, whose kind and writability are checked at compile time; a remaining account (or a
|
|
29
|
+
* local bound to one, a RemainingAccount helper parameter, a loaded struct) has none, and the called program and the
|
|
30
|
+
* runtime check what it is, that it is writable and that it signed.
|
|
31
|
+
*/
|
|
32
|
+
export interface CpiAcct {
|
|
33
|
+
c: string;
|
|
34
|
+
param?: AccountParam;
|
|
35
|
+
/**
|
|
36
|
+
* `named(account, address)` (a Stake CPI's sysvar or config slot): the meta names `address` (a `const SolPubkey *`)
|
|
37
|
+
* while `c`, the slot's account, is the account info handed to the runtime, whatever its key.
|
|
38
|
+
*/
|
|
39
|
+
named?: string;
|
|
40
|
+
}
|
|
41
|
+
/** The program a typed CPI goes to: a declared program parameter, or what `programAt<P>(acct)` checked. */
|
|
42
|
+
export interface CpiProgram {
|
|
43
|
+
c: string;
|
|
44
|
+
kind: ParamKind;
|
|
45
|
+
}
|
|
26
46
|
export interface Value {
|
|
27
47
|
c: string;
|
|
28
48
|
type: ValueType;
|
|
@@ -32,6 +52,8 @@ export interface Value {
|
|
|
32
52
|
stringLiteral?: string;
|
|
33
53
|
/** The `null` literal; becomes an empty option once the expected Option type is known. */
|
|
34
54
|
isNull?: boolean;
|
|
55
|
+
/** A loadRaw view of a struct ending in a BigVec: the C local holding its capacity, computed once at the load. */
|
|
56
|
+
bigCap?: string;
|
|
35
57
|
}
|
|
36
58
|
/** A storage location: account data, a nested field, an array element, or a local array. */
|
|
37
59
|
export interface Ref {
|
|
@@ -40,6 +62,8 @@ export interface Ref {
|
|
|
40
62
|
writable: boolean;
|
|
41
63
|
/** Owning account, for diagnostics and IDL seed paths. */
|
|
42
64
|
account?: AccountParam;
|
|
65
|
+
/** A loadRaw view of a struct ending in a BigVec, bound to a local: the C local holding its capacity. */
|
|
66
|
+
bigCap?: string;
|
|
43
67
|
/** Field path from the account root, when it is a plain chain of fields. */
|
|
44
68
|
path?: string[];
|
|
45
69
|
/** For a Vec: the u32 length lvalue, the fixed-part size expression, and whether it may be resized here. */
|
|
@@ -57,6 +81,10 @@ export interface Ref {
|
|
|
57
81
|
cap?: number;
|
|
58
82
|
/** A heap Vec (in a `@layout borsh` struct): `cap` is the C lvalue of its capacity, grown by ts_hvec_reserve. */
|
|
59
83
|
heap?: boolean;
|
|
84
|
+
/** A BigVec (its room set by the account's size, never resized): the C expression of its capacity. */
|
|
85
|
+
big?: string;
|
|
86
|
+
/** `bigVec.slice(start, end)`: a view of some of its elements (`len` is then a value, not the stored length). */
|
|
87
|
+
slice?: boolean;
|
|
60
88
|
/** Growable Vecs stored after this one move when it grows or shrinks: where its elements end, and their paths. */
|
|
61
89
|
tail?: {
|
|
62
90
|
end: string;
|
|
@@ -102,6 +130,8 @@ export interface Local {
|
|
|
102
130
|
};
|
|
103
131
|
/** A struct value this function holds itself (a literal, or what a helper returned): never account data. */
|
|
104
132
|
owned?: boolean;
|
|
133
|
+
/** A loadRaw view of a struct ending in a BigVec: the C local holding its capacity, computed at the load. */
|
|
134
|
+
bigCap?: string;
|
|
105
135
|
}
|
|
106
136
|
/** A closure and the scopes it was declared in (its free names resolve there, wherever it is called). */
|
|
107
137
|
export interface Closure {
|
|
@@ -169,5 +199,9 @@ export declare function vecLenCheck(s: StructDef, a: string, d: string, pad?: st
|
|
|
169
199
|
export declare function fixedVecC(t: FieldType & {
|
|
170
200
|
kind: "vec";
|
|
171
201
|
}): string;
|
|
172
|
-
/**
|
|
202
|
+
/**
|
|
203
|
+
* The element count of a Vec place to read: a FixedVec's stored length is clamped to its capacity, and so is a
|
|
204
|
+
* BigVec's, to the room its account holds (the length is checked at the load, but the account's bytes may be written
|
|
205
|
+
* again after it: writeData, storeBorsh, another view). A BigVec slice's length is in range already.
|
|
206
|
+
*/
|
|
173
207
|
export declare function vecCount(v: NonNullable<Ref["vec"]>): string;
|
|
@@ -73,6 +73,8 @@ export function valueC(t) {
|
|
|
73
73
|
return "TsAccount *";
|
|
74
74
|
case "txIx":
|
|
75
75
|
return "TsIx";
|
|
76
|
+
case "epochRewards":
|
|
77
|
+
return "TsEpochRewards";
|
|
76
78
|
case "structRef":
|
|
77
79
|
return `TSS_${t.struct} *`;
|
|
78
80
|
case "enumRef":
|
|
@@ -270,7 +272,13 @@ export function vecLenCheck(s, a, d, pad = " ") {
|
|
|
270
272
|
export function fixedVecC(t) {
|
|
271
273
|
return `TSF_${fixedVecName(t)}`;
|
|
272
274
|
}
|
|
273
|
-
/**
|
|
275
|
+
/**
|
|
276
|
+
* The element count of a Vec place to read: a FixedVec's stored length is clamped to its capacity, and so is a
|
|
277
|
+
* BigVec's, to the room its account holds (the length is checked at the load, but the account's bytes may be written
|
|
278
|
+
* again after it: writeData, storeBorsh, another view). A BigVec slice's length is in range already.
|
|
279
|
+
*/
|
|
274
280
|
export function vecCount(v) {
|
|
281
|
+
if (v.big !== undefined && !v.slice)
|
|
282
|
+
return `((uint64_t)${v.len} < ${v.big} ? (uint64_t)${v.len} : ${v.big})`;
|
|
275
283
|
return v.cap === undefined || v.heap ? `((uint64_t)${v.len})` : `((uint64_t)(${v.len} < ${v.cap} ? ${v.len} : ${v.cap}))`;
|
|
276
284
|
}
|
|
@@ -49,6 +49,18 @@ export declare abstract class StatementEmitter extends CpiEmitter {
|
|
|
49
49
|
fn: ts.ArrowFunction | ts.FunctionExpression;
|
|
50
50
|
}[];
|
|
51
51
|
};
|
|
52
|
+
/** List bases already made into locals (see holdList), so a list method and the loop under it make them once. */
|
|
53
|
+
protected heldLists: Map<ts.Node, ts.Identifier>;
|
|
54
|
+
/**
|
|
55
|
+
* A list written inline that must be made before it is read: `fixedArray<T, N>(fill)` (a local array, filled once)
|
|
56
|
+
* or a slice of a Vec argument or the instruction data (a view, range-checked once). Made here, in a local named by
|
|
57
|
+
* a synthetic identifier the loop reads; undefined for any other list (read in place).
|
|
58
|
+
*/
|
|
59
|
+
protected holdList(base: ts.Expression): ts.Identifier | undefined;
|
|
60
|
+
/** The type of an inline `fixedArray<T, N>(fill)` from its type arguments, without emitting code. */
|
|
61
|
+
protected inlineArrayType(e: ts.Expression): (FieldType & {
|
|
62
|
+
kind: "array";
|
|
63
|
+
}) | undefined;
|
|
52
64
|
/**
|
|
53
65
|
* Run `body` for each element of a list, or of a chain of `map` / `filter` calls on one (`xs.filter(f).map(g)`):
|
|
54
66
|
* one index loop over the list (its length read every step, as `for … of`), each callback expanded in it. A
|
|
@@ -62,7 +74,25 @@ export declare abstract class StatementEmitter extends CpiEmitter {
|
|
|
62
74
|
next?: string;
|
|
63
75
|
alwaysNext?: boolean;
|
|
64
76
|
atNext?: () => void;
|
|
77
|
+
body?: ts.Node;
|
|
65
78
|
}, body: (element: ts.Expression, index: ts.Expression) => void): void;
|
|
79
|
+
private eachElementLoop;
|
|
80
|
+
/**
|
|
81
|
+
* Run `emit` (a loop) as a C function of its own, called here: `TS_TRY(fn__loopN(params, …))`. SBF has ten
|
|
82
|
+
* registers, four of them kept across calls; a loop inside a large function shares them with every value the
|
|
83
|
+
* function holds across it, and clang spills the loop's own (the stake pool's pass over 20,000 validators paid a
|
|
84
|
+
* reload and a store per entry). A function of its own has them all. It gets the caller's variables the loop uses:
|
|
85
|
+
* by value when the loop only reads them, else through a pointer, copied in and back out when it is done (a failure
|
|
86
|
+
* returns at once, as it would here). False, with nothing emitted, when the loop cannot move: its body returns from
|
|
87
|
+
* the function, declares an account (create), or uses a variable of the caller that is not one of its locals or
|
|
88
|
+
* parameters (a claim slot, a list held in place); it then stays where it is.
|
|
89
|
+
*/
|
|
90
|
+
protected outlinedLoop(body: ts.Node | undefined, emit: () => void): boolean;
|
|
91
|
+
/**
|
|
92
|
+
* The parameters a loop moved out of this function takes for the caller's variables its C uses, or undefined when
|
|
93
|
+
* it uses one that cannot be passed (or that is not a local or parameter at all).
|
|
94
|
+
*/
|
|
95
|
+
private outlinedParams;
|
|
66
96
|
/**
|
|
67
97
|
* `const ys = xs.map(…)` / `xs.filter(…)`: the chain's elements in a local FixedVec, as big as the list it starts
|
|
68
98
|
* from (a FixedArray's length, a FixedVec's capacity) or as annotated (`const ys: FixedVec<u64, 16> = …`, needed
|
|
@@ -95,6 +125,7 @@ export declare abstract class StatementEmitter extends CpiEmitter {
|
|
|
95
125
|
* `find` gives an Option of the element (scalar elements), `findIndex` / `indexOf` an i64 (-1 when absent).
|
|
96
126
|
*/
|
|
97
127
|
protected listMethod(node: ts.CallExpression, method: string): Value | undefined;
|
|
128
|
+
private listMethodLoop;
|
|
98
129
|
/** `return` inside an expanded closure: the value goes to the closure's result, then past its body. */
|
|
99
130
|
protected closureReturn(stmt: ts.ReturnStatement, frame: (typeof this.inlineFrames)[number]): void;
|
|
100
131
|
/** Store a closure's result (fixing its type on the first one) and jump past the rest of its body. */
|
|
@@ -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
3
|
import { INT_INFO, isScalar, optionKey, scalarSize, typeName } from "../model.js";
|
|
4
|
-
import { U64, BOOL, cString, fixedVecC, optC, scalarC, scalarStorageC, valueC, } from "./shared.js";
|
|
4
|
+
import { U64, BOOL, 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
|
*/
|
|
@@ -269,7 +270,7 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
269
270
|
const ci = this.tmp("of_i");
|
|
270
271
|
const label = this.tmp("ts_continue_");
|
|
271
272
|
const release = this.iterationClaims(stmt.statement);
|
|
272
|
-
this.eachElement(stmt.expression, stmt, { index, ci, next: label, alwaysNext: true, atNext: release }, (element) => {
|
|
273
|
+
this.eachElement(stmt.expression, stmt, { index, ci, next: label, alwaysNext: true, atNext: release, body: stmt.statement }, (element) => {
|
|
273
274
|
// The element's declaration: the source's own name (so aliasing checks find its uses) bound to the element.
|
|
274
275
|
const decl = f.createVariableDeclaration(d.name, undefined, undefined, element);
|
|
275
276
|
ts.setTextRange(decl, d);
|
|
@@ -449,11 +450,53 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
449
450
|
}
|
|
450
451
|
if (stages.length) {
|
|
451
452
|
const l = ts.isIdentifier(base) ? this.lookup(base.text) : undefined;
|
|
452
|
-
if (!(l?.type.kind === "vecArg" || l?.type.kind === "array" || this.peekArray(base)))
|
|
453
|
+
if (!(l?.type.kind === "vecArg" || l?.type.kind === "array" || this.peekArray(base) || this.isVecArgView(base) || this.isInlineArray(base)))
|
|
453
454
|
this.fail(base, "map and filter work on a Vec, FixedArray or FixedVec");
|
|
454
455
|
}
|
|
455
456
|
return { base, stages };
|
|
456
457
|
}
|
|
458
|
+
/** List bases already made into locals (see holdList), so a list method and the loop under it make them once. */
|
|
459
|
+
heldLists = new Map();
|
|
460
|
+
/**
|
|
461
|
+
* A list written inline that must be made before it is read: `fixedArray<T, N>(fill)` (a local array, filled once)
|
|
462
|
+
* or a slice of a Vec argument or the instruction data (a view, range-checked once). Made here, in a local named by
|
|
463
|
+
* a synthetic identifier the loop reads; undefined for any other list (read in place).
|
|
464
|
+
*/
|
|
465
|
+
holdList(base) {
|
|
466
|
+
const held = this.heldLists.get(base);
|
|
467
|
+
if (held)
|
|
468
|
+
return held;
|
|
469
|
+
let made;
|
|
470
|
+
if (this.isInlineArray(base)) {
|
|
471
|
+
let call = base;
|
|
472
|
+
while (ts.isParenthesizedExpression(call))
|
|
473
|
+
call = call.expression;
|
|
474
|
+
const c = this.tmp("fa");
|
|
475
|
+
made = { c, type: this.localArray(call, c), mutable: false };
|
|
476
|
+
}
|
|
477
|
+
else if (!ts.isIdentifier(base) && this.isVecArgView(base)) {
|
|
478
|
+
const v = this.vecArgView(base);
|
|
479
|
+
made = { c: v.c, type: v.type, mutable: false };
|
|
480
|
+
}
|
|
481
|
+
if (!made)
|
|
482
|
+
return undefined;
|
|
483
|
+
const id = ts.factory.createIdentifier(`__hl${this.temp++}`);
|
|
484
|
+
ts.setTextRange(id, base);
|
|
485
|
+
id.parent = base.parent;
|
|
486
|
+
this.scopes.at(-1).set(id.text, made);
|
|
487
|
+
return id;
|
|
488
|
+
}
|
|
489
|
+
/** The type of an inline `fixedArray<T, N>(fill)` from its type arguments, without emitting code. */
|
|
490
|
+
inlineArrayType(e) {
|
|
491
|
+
while (ts.isParenthesizedExpression(e))
|
|
492
|
+
e = e.expression;
|
|
493
|
+
if (!this.isInlineArray(e))
|
|
494
|
+
return undefined;
|
|
495
|
+
const [elemNode, lenNode] = e.typeArguments ?? [];
|
|
496
|
+
const elem = elemNode && this.localElem(elemNode);
|
|
497
|
+
const len = lenNode && ts.isLiteralTypeNode(lenNode) && ts.isNumericLiteral(lenNode.literal) ? Number(lenNode.literal.text) : NaN;
|
|
498
|
+
return elem && Number.isInteger(len) ? { kind: "array", elem, len } : undefined;
|
|
499
|
+
}
|
|
457
500
|
/**
|
|
458
501
|
* Run `body` for each element of a list, or of a chain of `map` / `filter` calls on one (`xs.filter(f).map(g)`):
|
|
459
502
|
* one index loop over the list (its length read every step, as `for … of`), each callback expanded in it. A
|
|
@@ -462,13 +505,31 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
462
505
|
* filter, the count of elements it let through, as JS gives callbacks).
|
|
463
506
|
*/
|
|
464
507
|
eachElement(list, at, names, body) {
|
|
508
|
+
const stagesOf = this.pipelineStages(list);
|
|
509
|
+
const { stages } = stagesOf;
|
|
510
|
+
// An inline fixedArray(…) or a slice of a Vec argument / the instruction data: made once, before the loop.
|
|
511
|
+
const base = this.holdList(stagesOf.base) ?? stagesOf.base;
|
|
512
|
+
// A BigVec slice is lowered (and range-checked) once, here; the loop reads its length and elements from that.
|
|
513
|
+
const sliced = ts.isCallExpression(base) && ts.isPropertyAccessExpression(base.expression) && base.expression.name.text === "slice" ? this.ref(base) : undefined;
|
|
514
|
+
if (sliced?.vec?.slice)
|
|
515
|
+
this.sliceViews.set(base, sliced);
|
|
516
|
+
try {
|
|
517
|
+
// A BigVec runs to the size of its account (20,000 validators): its loops get a C function of their own.
|
|
518
|
+
const big = (sliced ?? this.probe(() => this.ref(base)))?.vec?.big !== undefined;
|
|
519
|
+
if (!big || !this.outlinedLoop(names.body, () => this.eachElementLoop(base, stages, at, names, body)))
|
|
520
|
+
this.eachElementLoop(base, stages, at, names, body);
|
|
521
|
+
}
|
|
522
|
+
finally {
|
|
523
|
+
this.sliceViews.delete(base);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
eachElementLoop(base, stages, at, names, body) {
|
|
465
527
|
const f = ts.factory;
|
|
466
528
|
const place = (n) => {
|
|
467
529
|
ts.setTextRange(n, at);
|
|
468
530
|
n.parent = at;
|
|
469
531
|
return n;
|
|
470
532
|
};
|
|
471
|
-
const { base, stages } = this.pipelineStages(list);
|
|
472
533
|
const { index, ci } = names;
|
|
473
534
|
const indexId = place(f.createIdentifier(index));
|
|
474
535
|
const length = place(f.createPropertyAccessExpression(base, "length"));
|
|
@@ -558,6 +619,139 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
558
619
|
});
|
|
559
620
|
this.line(`}`);
|
|
560
621
|
}
|
|
622
|
+
/**
|
|
623
|
+
* Run `emit` (a loop) as a C function of its own, called here: `TS_TRY(fn__loopN(params, …))`. SBF has ten
|
|
624
|
+
* registers, four of them kept across calls; a loop inside a large function shares them with every value the
|
|
625
|
+
* function holds across it, and clang spills the loop's own (the stake pool's pass over 20,000 validators paid a
|
|
626
|
+
* reload and a store per entry). A function of its own has them all. It gets the caller's variables the loop uses:
|
|
627
|
+
* by value when the loop only reads them, else through a pointer, copied in and back out when it is done (a failure
|
|
628
|
+
* returns at once, as it would here). False, with nothing emitted, when the loop cannot move: its body returns from
|
|
629
|
+
* the function, declares an account (create), or uses a variable of the caller that is not one of its locals or
|
|
630
|
+
* parameters (a claim slot, a list held in place); it then stays where it is.
|
|
631
|
+
*/
|
|
632
|
+
outlinedLoop(body, emit) {
|
|
633
|
+
const returns = (n) => ts.isReturnStatement(n) || (!ts.isFunctionLike(n) && !ts.isClassLike(n) && (ts.forEachChild(n, returns) ?? false));
|
|
634
|
+
if (body && returns(body))
|
|
635
|
+
return false;
|
|
636
|
+
// The variables visible here, by C name (innermost first, as lookup finds them).
|
|
637
|
+
const visible = new Map();
|
|
638
|
+
for (const scope of [...[...this.scopes].reverse(), this.args])
|
|
639
|
+
for (const l of scope.values())
|
|
640
|
+
if (!visible.has(l.c))
|
|
641
|
+
visible.set(l.c, l);
|
|
642
|
+
const saved = {
|
|
643
|
+
lines: this.lines,
|
|
644
|
+
hoisted: this.hoisted,
|
|
645
|
+
indent: this.indent,
|
|
646
|
+
temp: this.temp,
|
|
647
|
+
diagnostics: this.reporter.diagnostics.length,
|
|
648
|
+
outlined: this.outlinedLoops.length,
|
|
649
|
+
seedArrays: new Map(this.seedArrays),
|
|
650
|
+
state: () => JSON.stringify([[...this.created], [...this.pendingInit], [...this.bumps]]),
|
|
651
|
+
};
|
|
652
|
+
const state = saved.state();
|
|
653
|
+
this.lines = [];
|
|
654
|
+
this.hoisted = [];
|
|
655
|
+
this.indent = 1;
|
|
656
|
+
let lines;
|
|
657
|
+
let hoisted;
|
|
658
|
+
try {
|
|
659
|
+
emit();
|
|
660
|
+
}
|
|
661
|
+
finally {
|
|
662
|
+
lines = this.lines;
|
|
663
|
+
hoisted = this.hoisted;
|
|
664
|
+
this.lines = saved.lines;
|
|
665
|
+
this.hoisted = saved.hoisted;
|
|
666
|
+
this.indent = saved.indent;
|
|
667
|
+
// Seed arrays the loop declared live in its function (their positions are in its lines).
|
|
668
|
+
this.seedArrays.clear();
|
|
669
|
+
saved.seedArrays.forEach((v, k) => this.seedArrays.set(k, v));
|
|
670
|
+
}
|
|
671
|
+
const plan = saved.state() === state ? this.outlinedParams([...hoisted, ...lines].join("\n"), visible) : undefined;
|
|
672
|
+
if (!plan) {
|
|
673
|
+
this.temp = saved.temp;
|
|
674
|
+
this.reporter.diagnostics.length = saved.diagnostics;
|
|
675
|
+
this.outlinedLoops.length = saved.outlined;
|
|
676
|
+
return false;
|
|
677
|
+
}
|
|
678
|
+
// Heap buffers taken on first use stay declared in the caller, which passes each in by pointer: declared in the
|
|
679
|
+
// 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
|
|
680
|
+
// times would exhaust the heap).
|
|
681
|
+
const lazy = hoisted.filter((l) => this.lazyHoists.has(l));
|
|
682
|
+
for (const l of lazy) {
|
|
683
|
+
const { name: buffer, decl } = this.lazyHoists.get(l);
|
|
684
|
+
this.hoisted.push(l);
|
|
685
|
+
plan.params.push(decl(`*cp_${buffer}`));
|
|
686
|
+
plan.args.push(`&${buffer}`);
|
|
687
|
+
plan.copyIn.push(` ${decl(buffer)} = *cp_${buffer};`);
|
|
688
|
+
plan.copyOut.push(` *cp_${buffer} = ${buffer};`);
|
|
689
|
+
}
|
|
690
|
+
hoisted = hoisted.filter((l) => !lazy.includes(l));
|
|
691
|
+
const name = `${this.helper ? `fn_${this.helper.name}` : `ix_${this.ix.name}`}__loop${this.outlinedLoops.length}`;
|
|
692
|
+
this.outlinedLoops.push([
|
|
693
|
+
`static __attribute__((noinline)) uint64_t ${name}(${["TsParams *params", ...plan.params].join(", ")}) {`,
|
|
694
|
+
...plan.copyIn,
|
|
695
|
+
...hoisted,
|
|
696
|
+
...lines,
|
|
697
|
+
...plan.copyOut,
|
|
698
|
+
` return SUCCESS;`,
|
|
699
|
+
`}`,
|
|
700
|
+
``,
|
|
701
|
+
].join("\n"));
|
|
702
|
+
this.line(`TS_TRY(${name}(${["params", ...plan.args].join(", ")}));`);
|
|
703
|
+
return true;
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* The parameters a loop moved out of this function takes for the caller's variables its C uses, or undefined when
|
|
707
|
+
* it uses one that cannot be passed (or that is not a local or parameter at all).
|
|
708
|
+
*/
|
|
709
|
+
outlinedParams(c, visible) {
|
|
710
|
+
const toks = cTokens(c);
|
|
711
|
+
const own = declaredNames(toks);
|
|
712
|
+
const signature = this.helper ? parameterDecls(helperSignature(this.helper)) : new Map();
|
|
713
|
+
const out = { params: [], args: [], copyIn: [], copyOut: [] };
|
|
714
|
+
for (const n of [...usedNames(toks)].sort()) {
|
|
715
|
+
if (own.has(n) || n === "params" || isGlobalName(n))
|
|
716
|
+
continue;
|
|
717
|
+
const param = signature.get(n);
|
|
718
|
+
if (param) {
|
|
719
|
+
out.params.push(param);
|
|
720
|
+
out.args.push(n);
|
|
721
|
+
continue;
|
|
722
|
+
}
|
|
723
|
+
if (this.ix && n.startsWith("a_") && this.accounts.has(n.slice(2))) {
|
|
724
|
+
out.params.push(`TsAccount *${n}`);
|
|
725
|
+
out.args.push(n);
|
|
726
|
+
continue;
|
|
727
|
+
}
|
|
728
|
+
const l = visible.get(n);
|
|
729
|
+
if (!l || l.closure || l.choice)
|
|
730
|
+
return undefined;
|
|
731
|
+
const t = l.type;
|
|
732
|
+
if (t.kind === "array" ||
|
|
733
|
+
t.kind === "vec" ||
|
|
734
|
+
t.kind === "remaining" ||
|
|
735
|
+
t.kind === "arrayArg" ||
|
|
736
|
+
t.kind === "optionArg" ||
|
|
737
|
+
t.kind === "signerSeeds" ||
|
|
738
|
+
t.kind === "dataEnumArg")
|
|
739
|
+
return undefined;
|
|
740
|
+
const ct = t.kind === "pubkey" ? (l.ptr ? "const SolPubkey *" : "SolPubkey") : valueC(t);
|
|
741
|
+
const decl = (name) => (ct.endsWith("*") ? `${ct}${name}` : `${ct} ${name}`);
|
|
742
|
+
if (!l.mutable && (ct.endsWith("*") || t.kind === "int" || t.kind === "bool" || t.kind === "enum")) {
|
|
743
|
+
out.params.push(decl(n));
|
|
744
|
+
out.args.push(n);
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
out.params.push(decl(`*cp_${n}`));
|
|
748
|
+
out.args.push(`&${n}`);
|
|
749
|
+
out.copyIn.push(` ${decl(n)} = *cp_${n};`);
|
|
750
|
+
if (l.mutable)
|
|
751
|
+
out.copyOut.push(` *cp_${n} = ${n};`);
|
|
752
|
+
}
|
|
753
|
+
return out;
|
|
754
|
+
}
|
|
561
755
|
/**
|
|
562
756
|
* `const ys = xs.map(…)` / `xs.filter(…)`: the chain's elements in a local FixedVec, as big as the list it starts
|
|
563
757
|
* from (a FixedArray's length, a FixedVec's capacity) or as annotated (`const ys: FixedVec<u64, 16> = …`, needed
|
|
@@ -585,7 +779,11 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
585
779
|
this.fail(t, "annotate the new list as FixedVec<T, N> (N a literal)");
|
|
586
780
|
cap = n;
|
|
587
781
|
}
|
|
782
|
+
else if (this.inlineArrayType(base))
|
|
783
|
+
cap = this.inlineArrayType(base).len;
|
|
588
784
|
else {
|
|
785
|
+
if (this.isVecArgView(base))
|
|
786
|
+
this.fail(init, "this list has no fixed size: annotate the new one with its capacity, const ys: FixedVec<T, N> = …");
|
|
589
787
|
const r = this.reporter.guard(() => this.ref(base));
|
|
590
788
|
const l = ts.isIdentifier(base) ? this.lookup(base.text) : undefined;
|
|
591
789
|
if (r?.type.kind === "array")
|
|
@@ -634,9 +832,7 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
634
832
|
this.line(`${c}.len++;`);
|
|
635
833
|
});
|
|
636
834
|
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>)`);
|
|
835
|
+
this.checkLocalListSize(t, init, "the new list");
|
|
640
836
|
this.model.localVecs.set(fixedVecC(t), t);
|
|
641
837
|
const pad = " ".repeat(this.indent);
|
|
642
838
|
this.lines[declAt] = `${pad}${fixedVecC(t)} ${c};\n${pad}ts_memzero(&${c}, sizeof(${c}));`;
|
|
@@ -644,7 +840,20 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
644
840
|
}
|
|
645
841
|
/** The element type of a Vec, FixedArray, FixedVec or Vec argument. */
|
|
646
842
|
listElem(list) {
|
|
647
|
-
const
|
|
843
|
+
const inline = this.inlineArrayType(list);
|
|
844
|
+
if (inline)
|
|
845
|
+
return inline.elem;
|
|
846
|
+
// A slice of a Vec argument or the instruction data: the elements of the list it slices.
|
|
847
|
+
let root = list;
|
|
848
|
+
for (;;) {
|
|
849
|
+
if (ts.isParenthesizedExpression(root))
|
|
850
|
+
root = root.expression;
|
|
851
|
+
else if (ts.isCallExpression(root) && ts.isPropertyAccessExpression(root.expression) && root.expression.name.text === "slice" && this.isVecArgView(root))
|
|
852
|
+
root = root.expression.expression;
|
|
853
|
+
else
|
|
854
|
+
break;
|
|
855
|
+
}
|
|
856
|
+
const l = ts.isIdentifier(root) ? this.lookup(root.text) : undefined;
|
|
648
857
|
if (l?.type.kind === "vecArg")
|
|
649
858
|
return l.type.elem;
|
|
650
859
|
const r = this.ref(list);
|
|
@@ -830,6 +1039,20 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
830
1039
|
* `find` gives an Option of the element (scalar elements), `findIndex` / `indexOf` an i64 (-1 when absent).
|
|
831
1040
|
*/
|
|
832
1041
|
listMethod(node, method) {
|
|
1042
|
+
// A list written inline is made first, as JS evaluates the receiver before the arguments (reduce's initial value).
|
|
1043
|
+
const base = this.pipelineStages(node.expression.expression).base;
|
|
1044
|
+
const held = this.holdList(base);
|
|
1045
|
+
if (!held)
|
|
1046
|
+
return this.listMethodLoop(node, method);
|
|
1047
|
+
this.heldLists.set(base, held);
|
|
1048
|
+
try {
|
|
1049
|
+
return this.listMethodLoop(node, method);
|
|
1050
|
+
}
|
|
1051
|
+
finally {
|
|
1052
|
+
this.heldLists.delete(base);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
listMethodLoop(node, method) {
|
|
833
1056
|
const access = node.expression;
|
|
834
1057
|
const list = access.expression;
|
|
835
1058
|
const args = node.arguments;
|
|
@@ -892,6 +1115,9 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
892
1115
|
this.line(`/* ${res} */`);
|
|
893
1116
|
}
|
|
894
1117
|
const findDecl = method === "find" ? this.lines.length - 1 : -1;
|
|
1118
|
+
// The result is the loop's to set: named in scope, so a loop moved into a function of its own gets it (outlinedLoop).
|
|
1119
|
+
if (result && method !== "find")
|
|
1120
|
+
this.scopes.at(-1).set(`__${res}`, { c: res, type: result.type, mutable: true });
|
|
895
1121
|
const ci = this.tmp("lm_i");
|
|
896
1122
|
this.eachElement(list, node, { index, ci }, (element, indexId) => {
|
|
897
1123
|
if (valueForm) {
|
|
@@ -1186,7 +1412,7 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1186
1412
|
continue;
|
|
1187
1413
|
}
|
|
1188
1414
|
if (fn === "fixedArray") {
|
|
1189
|
-
const t = this.localArray(init, c);
|
|
1415
|
+
const t = this.localArray(init, c, d.type);
|
|
1190
1416
|
this.scopes.at(-1).set(name, { c, type: t, mutable });
|
|
1191
1417
|
continue;
|
|
1192
1418
|
}
|
|
@@ -1212,7 +1438,21 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1212
1438
|
if (h)
|
|
1213
1439
|
loaded = { handle: h, struct: t.type.struct, mut: fn === "loadAccountMut" };
|
|
1214
1440
|
}
|
|
1215
|
-
this.scopes.at(-1).set(name, { c, type: t.type, mutable: false, paths: [`@${c}`], decl: d, loaded });
|
|
1441
|
+
this.scopes.at(-1).set(name, { c, type: t.type, mutable: false, paths: [`@${c}`], decl: d, loaded, ...(t.bigCap ? { bigCap: t.bigCap } : {}) });
|
|
1442
|
+
continue;
|
|
1443
|
+
}
|
|
1444
|
+
// A local decoded from an account's Borsh bytes: `const pool = loadBorsh<StakePool>(acct)` (a copy, as Rust's).
|
|
1445
|
+
if (fn === "loadBorsh") {
|
|
1446
|
+
if (mutable)
|
|
1447
|
+
this.fail(d, "bind loadBorsh<T>(...) with const (its fields can still be updated)");
|
|
1448
|
+
const named = d.type && structNameOf(d.type, this.scope);
|
|
1449
|
+
const declared = named ? this.model.structs.get(named) : undefined;
|
|
1450
|
+
if (d.type && !declared)
|
|
1451
|
+
this.fail(d.type, "loadBorsh returns a struct: declare the local as one (or leave the type out)");
|
|
1452
|
+
const s = this.loadBorsh(init, c, declared);
|
|
1453
|
+
this.scopes
|
|
1454
|
+
.at(-1)
|
|
1455
|
+
.set(name, { c, type: { kind: "structRef", struct: s.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d, owned: true });
|
|
1216
1456
|
continue;
|
|
1217
1457
|
}
|
|
1218
1458
|
// A struct another program returned: `const q = returnData<Quote>(amm)` (Anchor's `get_return_data` + deserialize).
|
|
@@ -1223,14 +1463,14 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1223
1463
|
const call = init;
|
|
1224
1464
|
if (call.arguments.length !== 1)
|
|
1225
1465
|
this.fail(call, "returnData<T>(program) takes the program that returned it");
|
|
1226
|
-
const program = this.
|
|
1466
|
+
const program = this.anyAccount(call.arguments[0], "returnData's program");
|
|
1227
1467
|
const bad = `TS_FAIL(TS_ERR_RETURN_DATA, "TypeSOL: invalid ${S.name} return data")`;
|
|
1228
1468
|
if (S.layout === "borsh") {
|
|
1229
1469
|
// Borsh of any size: unpacked into the fixed-layout struct, every byte used.
|
|
1230
1470
|
const raw = `${c}__raw`;
|
|
1231
1471
|
this.line(`uint8_t *${raw};`);
|
|
1232
1472
|
this.line(`uint64_t ${raw}_len = 0, ${raw}_used = 0;`);
|
|
1233
|
-
this.line(`TS_TRY(ts_return_data_any(
|
|
1473
|
+
this.line(`TS_TRY(ts_return_data_any(${program}, &${raw}, &${raw}_len));`);
|
|
1234
1474
|
this.line(`TSS_${S.name} *${c};`);
|
|
1235
1475
|
this.line(`TS_TRY(ts_alloc(sizeof(TSS_${S.name}), (uint8_t **)&${c}));`);
|
|
1236
1476
|
this.line(`if (ts_unpack_${S.name}(${raw}, ${raw}_len, ${c}, &${raw}_used) != SUCCESS || ${raw}_used != ${raw}_len) ${bad};`);
|
|
@@ -1241,7 +1481,7 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1241
1481
|
else {
|
|
1242
1482
|
// A fixed layout whose bytes are its Borsh form: copied in, then bools and enums checked.
|
|
1243
1483
|
this.line(`TSS_${S.name} ${c}__v;`);
|
|
1244
|
-
this.line(`TS_TRY(ts_return_data_exact(
|
|
1484
|
+
this.line(`TS_TRY(ts_return_data_exact(${program}, &${c}__v, sizeof(TSS_${S.name})));`);
|
|
1245
1485
|
for (const l of this.validation(`${c}__v`, { kind: "struct", name: S.name }, "", bad))
|
|
1246
1486
|
this.line(l.trim());
|
|
1247
1487
|
this.line(`TSS_${S.name} *${c} = &${c}__v;`);
|
|
@@ -1249,6 +1489,22 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1249
1489
|
this.scopes.at(-1).set(name, { c, type: { kind: "structRef", struct: S.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d });
|
|
1250
1490
|
continue;
|
|
1251
1491
|
}
|
|
1492
|
+
// A local list declared with its type: `const metas: FixedVec<Meta, 4> = fixedVec([{ pubkey, isSigner, … }])`,
|
|
1493
|
+
// `const buf: FixedVec<u8, 600> = fixedVec([])`, or a copy of another list (a Vec argument, instruction data).
|
|
1494
|
+
const listType = d.type ? this.listAnnotation(d.type) : undefined;
|
|
1495
|
+
if (listType) {
|
|
1496
|
+
this.checkLocalListSize(listType, d.type);
|
|
1497
|
+
if (listType.kind === "vec") {
|
|
1498
|
+
this.model.localVecs.set(fixedVecC(listType), listType);
|
|
1499
|
+
this.line(`${fixedVecC(listType)} ${c};`);
|
|
1500
|
+
this.line(`ts_memzero(&${c}, sizeof(${c}));`);
|
|
1501
|
+
}
|
|
1502
|
+
else
|
|
1503
|
+
this.line(`${storageDecl(listType, c)};`);
|
|
1504
|
+
this.writeAggregate({ lv: c, type: listType, writable: true }, init, true);
|
|
1505
|
+
this.scopes.at(-1).set(name, { c, type: listType, mutable });
|
|
1506
|
+
continue;
|
|
1507
|
+
}
|
|
1252
1508
|
// Struct values: `const p: Point = { x, y }` (or a copy of another Point) is a local of its own.
|
|
1253
1509
|
const structType = d.type && structNameOf(d.type, this.scope) ? this.model.structs.get(structNameOf(d.type, this.scope)) : undefined;
|
|
1254
1510
|
if (structType) {
|
|
@@ -1311,7 +1567,9 @@ export class StatementEmitter extends CpiEmitter {
|
|
|
1311
1567
|
continue;
|
|
1312
1568
|
}
|
|
1313
1569
|
let declared;
|
|
1314
|
-
if (d.type)
|
|
1570
|
+
if (d.type && typesolName(d.type, this.scope.imports) === "EpochRewards")
|
|
1571
|
+
declared = { kind: "epochRewards" };
|
|
1572
|
+
else if (d.type) {
|
|
1315
1573
|
declared = resolveValueType(d.type, this.scope);
|
|
1316
1574
|
if (!declared || declared.kind === "vecArg")
|
|
1317
1575
|
this.fail(d.type, "local type must be an integer, boolean, Pubkey, enum, option or string");
|
|
@@ -27,8 +27,27 @@ 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 may take at most 2 KiB, so the failure is a clear compile error, not clang's frame error.
|
|
33
|
+
*/
|
|
34
|
+
protected checkLocalListSize(t: FieldType & {
|
|
35
|
+
kind: "vec" | "array";
|
|
36
|
+
}, at: ts.Node, what?: string): void;
|
|
37
|
+
/**
|
|
38
|
+
* `FixedVec<T, N>` / `FixedArray<T, N>` written as a local's type: T an integer, boolean, Pubkey, enum,
|
|
39
|
+
* `FixedString<N>` or fixed-size struct, N a literal. Undefined for other types; a list type with anything else fails.
|
|
40
|
+
*/
|
|
41
|
+
protected listAnnotation(t: ts.TypeNode): (FieldType & {
|
|
42
|
+
kind: "vec";
|
|
43
|
+
cap: number;
|
|
44
|
+
}) | (FieldType & {
|
|
45
|
+
kind: "array";
|
|
46
|
+
}) | undefined;
|
|
47
|
+
/** A local list's element type: a scalar, a FixedString<N> or a fixed-size struct (no Vec, no heap). */
|
|
48
|
+
protected localElem(node: ts.TypeNode): FieldType | undefined;
|
|
30
49
|
/** `fixedArray<T, N>(fill)` as a local declaration. */
|
|
31
|
-
protected localArray(init: ts.CallExpression, c: string): FieldType & {
|
|
50
|
+
protected localArray(init: ts.CallExpression, c: string, annotation?: ts.TypeNode): FieldType & {
|
|
32
51
|
kind: "array";
|
|
33
52
|
};
|
|
34
53
|
/** Resolve an expression to a storage location, if it names one. */
|
|
@@ -69,6 +88,13 @@ export declare abstract class StorageEmitter extends AliasEmitter {
|
|
|
69
88
|
protected fixedVec(lv: string, elem: FieldType, cap: number): NonNullable<Ref["vec"]>;
|
|
70
89
|
/** A heap Vec (a Vec<T> in a `@layout borsh` struct) at `lv`: `{ len, cap, items }`, grown by ts_hvec_reserve. */
|
|
71
90
|
protected heapVec(lv: string, elem: FieldType): NonNullable<Ref["vec"]>;
|
|
91
|
+
/** Slices lowered once before a loop over them (see eachElement): the loop's length and element reads reuse them. */
|
|
92
|
+
protected sliceViews: Map<ts.Node, Ref>;
|
|
93
|
+
/**
|
|
94
|
+
* `bigVec.slice(start, end)`: elements start..end-1 in place, as BigVec::deserialize_mut_slice(start, end - start)
|
|
95
|
+
* gives them. Out of range fails with ProgramError::AccountDataTooSmall, as that does (JS's slice would clamp).
|
|
96
|
+
*/
|
|
97
|
+
protected bigVecSlice(node: ts.CallExpression, base: Ref): Ref;
|
|
72
98
|
/** A place whose type is a FixedVec (or a heap Vec) gets its Vec view. */
|
|
73
99
|
protected withFixedVec(r: Ref): Ref;
|
|
74
100
|
/** `arr.get(i)` reads storage rather than calling anything. */
|