@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.
Files changed (62) hide show
  1. package/CHANGELOG.md +319 -0
  2. package/README.md +11 -7
  3. package/dist/compiler/analyze.js +484 -13
  4. package/dist/compiler/diagnostics.d.ts +1 -0
  5. package/dist/compiler/diagnostics.js +13 -0
  6. package/dist/compiler/emit/alias.d.ts +44 -0
  7. package/dist/compiler/emit/alias.js +135 -4
  8. package/dist/compiler/emit/base.d.ts +65 -7
  9. package/dist/compiler/emit/base.js +91 -7
  10. package/dist/compiler/emit/borsh.d.ts +7 -0
  11. package/dist/compiler/emit/borsh.js +86 -1
  12. package/dist/compiler/emit/calls.d.ts +169 -2
  13. package/dist/compiler/emit/calls.js +1170 -81
  14. package/dist/compiler/emit/cpi-core.d.ts +28 -5
  15. package/dist/compiler/emit/cpi-core.js +238 -12
  16. package/dist/compiler/emit/cpi.js +16 -16
  17. package/dist/compiler/emit/create.d.ts +3 -3
  18. package/dist/compiler/emit/create.js +33 -25
  19. package/dist/compiler/emit/expressions.js +89 -9
  20. package/dist/compiler/emit/function.js +2 -2
  21. package/dist/compiler/emit/outline.d.ts +24 -0
  22. package/dist/compiler/emit/outline.js +100 -0
  23. package/dist/compiler/emit/program.js +37 -3
  24. package/dist/compiler/emit/rbtree.d.ts +7 -0
  25. package/dist/compiler/emit/rbtree.js +142 -0
  26. package/dist/compiler/emit/shared.d.ts +43 -1
  27. package/dist/compiler/emit/shared.js +18 -2
  28. package/dist/compiler/emit/statements.d.ts +58 -1
  29. package/dist/compiler/emit/statements.js +549 -22
  30. package/dist/compiler/emit/storage.d.ts +48 -1
  31. package/dist/compiler/emit/storage.js +220 -63
  32. package/dist/compiler/emit/token.d.ts +11 -8
  33. package/dist/compiler/emit/token.js +233 -104
  34. package/dist/compiler/emit/views.d.ts +60 -0
  35. package/dist/compiler/emit/views.js +523 -0
  36. package/dist/compiler/hints.js +6 -0
  37. package/dist/compiler/idl.js +2 -1
  38. package/dist/compiler/model.d.ts +84 -4
  39. package/dist/compiler/model.js +19 -0
  40. package/dist/compiler/toolchain.d.ts +15 -0
  41. package/dist/compiler/toolchain.js +146 -11
  42. package/dist/testing-stake.d.ts +216 -0
  43. package/dist/testing-stake.js +526 -0
  44. package/dist/testing.d.ts +1 -0
  45. package/dist/testing.js +1 -0
  46. package/docs/architecture.md +9 -2
  47. package/docs/case-study-phoenix.md +226 -0
  48. package/docs/case-study-spl-stake-pool.md +122 -0
  49. package/docs/errors.md +1 -1
  50. package/docs/language.md +244 -20
  51. package/docs/migrate-from-anchor.md +1 -0
  52. package/docs/runtime.md +1 -1
  53. package/docs/security-model.md +4 -0
  54. package/docs/stability.md +33 -1
  55. package/docs/test-your-program.md +47 -0
  56. package/docs/testing.md +19 -0
  57. package/docs/troubleshooting.md +5 -2
  58. package/lib/typesol.d.ts +462 -44
  59. package/llms-full.txt +338 -26
  60. package/llms.txt +1 -1
  61. package/package.json +2 -2
  62. package/runtime/typesol_rt.h +476 -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,12 @@ 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;
88
+ /** A `rawArrayAt` view (with `big` and `slice`): `len` its run-time count, nothing stored. */
89
+ raw?: boolean;
60
90
  /** Growable Vecs stored after this one move when it grows or shrinks: where its elements end, and their paths. */
61
91
  tail?: {
62
92
  end: string;
@@ -87,6 +117,12 @@ export interface Local {
87
117
  /** For struct / data-enum references: the storage paths they alias (e.g. "book.asks[]"), and the declaration. */
88
118
  paths?: string[];
89
119
  decl?: ts.VariableDeclaration | ts.ParameterDeclaration;
120
+ /** A struct reference into an element of a list whose elements can move (a growable Vec, a heap Vec, a BigVec). */
121
+ movable?: boolean;
122
+ /** A native view (`loadRaw`, `loadRawMutAt`, `rawArrayMutAt`, `rbTreeMutAt` …): under NATIVE_ACCOUNT_WRITES two views may share bytes. */
123
+ view?: boolean;
124
+ /** For a native view: the account it reads (see `viewAccountKey`), so closeRaw / resizeAccount can end it. */
125
+ viewAcct?: string;
90
126
  /** A local closure (`const f = (…) => …` reading the enclosing function's variables), expanded where it is called. */
91
127
  closure?: Closure;
92
128
  /**
@@ -102,6 +138,8 @@ export interface Local {
102
138
  };
103
139
  /** A struct value this function holds itself (a literal, or what a helper returned): never account data. */
104
140
  owned?: boolean;
141
+ /** A loadRaw view of a struct ending in a BigVec: the C local holding its capacity, computed at the load. */
142
+ bigCap?: string;
105
143
  }
106
144
  /** A closure and the scopes it was declared in (its free names resolve there, wherever it is called). */
107
145
  export interface Closure {
@@ -169,5 +207,9 @@ export declare function vecLenCheck(s: StructDef, a: string, d: string, pad?: st
169
207
  export declare function fixedVecC(t: FieldType & {
170
208
  kind: "vec";
171
209
  }): string;
172
- /** The element count of a Vec place to read: a FixedVec's stored length is clamped to its capacity. */
210
+ /**
211
+ * The element count of a Vec place to read: a FixedVec's stored length is clamped to its capacity, and so is a
212
+ * BigVec's, to the room its account holds (the length is checked at the load, but the account's bytes may be written
213
+ * again after it: writeData, storeBorsh, another view). A BigVec slice's length is in range already.
214
+ */
173
215
  export declare function vecCount(v: NonNullable<Ref["vec"]>): string;
@@ -73,8 +73,16 @@ 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} *`;
80
+ case "rawArray":
81
+ return `${fieldC(t.elem)} *`;
82
+ case "rbTree":
83
+ return "TsRbt";
84
+ case "rbEntry":
85
+ return "TsRbtEntry";
78
86
  case "enumRef":
79
87
  case "dataEnumArg":
80
88
  return `TSE_${t.name} *`;
@@ -207,6 +215,8 @@ export function helperSignature(h) {
207
215
  if (p.account.kind === "account" && p.account.mut && p.account.struct.vec)
208
216
  params.push(`uint64_t entry_${p.name}`);
209
217
  }
218
+ else if (p.inout?.kind === "vec")
219
+ params.push(`${fixedVecC(p.inout)} *p_${p.name}`); // the caller's list itself (Inout<FixedVec<T, N>>)
210
220
  else if (p.type.kind === "signerSeeds")
211
221
  params.push(`const SolSignerSeed *p_${p.name}`, `int p_${p.name}__n`);
212
222
  // The remaining accounts: the index of the first one among the instruction's accounts.
@@ -221,7 +231,7 @@ export function helperSignature(h) {
221
231
  }
222
232
  if (h.returns)
223
233
  params.push(h.returns.kind === "struct" ? `TSS_${h.returns.name} *ret` : h.returns.kind === "string" ? `TS_Str *ret` : `${scalarC(h.returns)} *ret`);
224
- return `static uint64_t fn_${h.name}(${params.join(", ")})`;
234
+ return `${h.noinline ? "__attribute__((noinline)) " : ""}static uint64_t fn_${h.name}(${params.join(", ")})`;
225
235
  }
226
236
  /** C type of a growable Vec stored after the first one of struct `s`: `{ uint32_t len; T items[]; }`. */
227
237
  export function laterVecC(s, field) {
@@ -270,7 +280,13 @@ export function vecLenCheck(s, a, d, pad = " ") {
270
280
  export function fixedVecC(t) {
271
281
  return `TSF_${fixedVecName(t)}`;
272
282
  }
273
- /** The element count of a Vec place to read: a FixedVec's stored length is clamped to its capacity. */
283
+ /**
284
+ * The element count of a Vec place to read: a FixedVec's stored length is clamped to its capacity, and so is a
285
+ * BigVec's, to the room its account holds (the length is checked at the load, but the account's bytes may be written
286
+ * again after it: writeData, storeBorsh, another view). A BigVec slice's length is in range already.
287
+ */
274
288
  export function vecCount(v) {
289
+ if (v.big !== undefined && !v.slice)
290
+ return `((uint64_t)${v.len} < ${v.big} ? (uint64_t)${v.len} : ${v.big})`;
275
291
  return v.cap === undefined || v.heap ? `((uint64_t)${v.len})` : `((uint64_t)(${v.len} < ${v.cap} ? ${v.len} : ${v.cap}))`;
276
292
  }
@@ -1,6 +1,7 @@
1
1
  import ts from "typescript";
2
+ import { type TypeScope } from "../analyze.js";
2
3
  import { type FieldType } from "../model.js";
3
- import { type Value, type Closure, type FunctionChoice, type Ref } from "./shared.js";
4
+ import { type Value, type Local, type Closure, type FunctionChoice, type Ref } from "./shared.js";
4
5
  import { CpiEmitter } from "./cpi.js";
5
6
  /**
6
7
  * Statements: variables, assignment, control flow and return.
@@ -18,6 +19,13 @@ export declare abstract class StatementEmitter extends CpiEmitter {
18
19
  * As in JS, the length is read again before every step, so a body that pushes or pops sees the new length.
19
20
  */
20
21
  protected forOf(stmt: ts.ForOfStatement): void;
22
+ /**
23
+ * `for (const e of tree)` / `for (const e of tree.reversed())` over a RedBlackTree: lib-sokoban's in-order
24
+ * iterator (a stack of nodes, left registers down, then the right one), smallest key first or, reversed, largest
25
+ * first. `e` is the node (`e.key`, `e.value`, `e.index`), each read where it lies. The body may change values
26
+ * but not the tree's structure (insert / remove / initialize on it are compile errors, as Rust's borrow forbids).
27
+ */
28
+ protected treeForOf(stmt: ts.ForOfStatement, d: ts.VariableDeclaration): boolean;
21
29
  /** The functions a list literal names (`[f, g]`: closures, helpers or choices), or undefined when it holds anything else. */
22
30
  protected functionList(list: ts.ArrayLiteralExpression): (Closure | FunctionChoice)[] | undefined;
23
31
  /**
@@ -49,6 +57,18 @@ export declare abstract class StatementEmitter extends CpiEmitter {
49
57
  fn: ts.ArrowFunction | ts.FunctionExpression;
50
58
  }[];
51
59
  };
60
+ /** List bases already made into locals (see holdList), so a list method and the loop under it make them once. */
61
+ protected heldLists: Map<ts.Node, ts.Identifier>;
62
+ /**
63
+ * A list written inline that must be made before it is read: `fixedArray<T, N>(fill)` (a local array, filled once)
64
+ * or a slice of a Vec argument or the instruction data (a view, range-checked once). Made here, in a local named by
65
+ * a synthetic identifier the loop reads; undefined for any other list (read in place).
66
+ */
67
+ protected holdList(base: ts.Expression): ts.Identifier | undefined;
68
+ /** The type of an inline `fixedArray<T, N>(fill)` from its type arguments, without emitting code. */
69
+ protected inlineArrayType(e: ts.Expression): (FieldType & {
70
+ kind: "array";
71
+ }) | undefined;
52
72
  /**
53
73
  * Run `body` for each element of a list, or of a chain of `map` / `filter` calls on one (`xs.filter(f).map(g)`):
54
74
  * one index loop over the list (its length read every step, as `for … of`), each callback expanded in it. A
@@ -62,7 +82,25 @@ export declare abstract class StatementEmitter extends CpiEmitter {
62
82
  next?: string;
63
83
  alwaysNext?: boolean;
64
84
  atNext?: () => void;
85
+ body?: ts.Node;
65
86
  }, body: (element: ts.Expression, index: ts.Expression) => void): void;
87
+ private eachElementLoop;
88
+ /**
89
+ * Run `emit` (a loop) as a C function of its own, called here: `TS_TRY(fn__loopN(params, …))`. SBF has ten
90
+ * registers, four of them kept across calls; a loop inside a large function shares them with every value the
91
+ * function holds across it, and clang spills the loop's own (the stake pool's pass over 20,000 validators paid a
92
+ * reload and a store per entry). A function of its own has them all. It gets the caller's variables the loop uses:
93
+ * by value when the loop only reads them, else through a pointer, copied in and back out when it is done (a failure
94
+ * returns at once, as it would here). False, with nothing emitted, when the loop cannot move: its body returns from
95
+ * the function, declares an account (create), or uses a variable of the caller that is not one of its locals or
96
+ * parameters (a claim slot, a list held in place); it then stays where it is.
97
+ */
98
+ protected outlinedLoop(body: ts.Node | undefined, emit: () => void): boolean;
99
+ /**
100
+ * The parameters a loop moved out of this function takes for the caller's variables its C uses, or undefined when
101
+ * it uses one that cannot be passed (or that is not a local or parameter at all).
102
+ */
103
+ private outlinedParams;
66
104
  /**
67
105
  * `const ys = xs.map(…)` / `xs.filter(…)`: the chain's elements in a local FixedVec, as big as the list it starts
68
106
  * from (a FixedArray's length, a FixedVec's capacity) or as annotated (`const ys: FixedVec<u64, 16> = …`, needed
@@ -87,6 +125,11 @@ export declare abstract class StatementEmitter extends CpiEmitter {
87
125
  * was declared with, so a block around the call that declares the same name does not change what it reads, and
88
126
  * writes to captured `let`s are seen by the enclosing function. Returns the result (undefined for no value).
89
127
  */
128
+ /**
129
+ * An `Inout<T>` parameter of a function expanded where it is called: a pointer to the caller's place (a struct,
130
+ * FixedArray or FixedVec), which must be writable, bound as a reference local.
131
+ */
132
+ protected inoutBinding(p: ts.ParameterDeclaration, arg: ts.Expression, calleeScope: TypeScope, fnName: string): Local;
90
133
  protected expandClosure(c: Closure, args: readonly ts.Expression[], node: ts.Node, into?: Ref): Value | undefined;
91
134
  /**
92
135
  * `xs.forEach / some / every / find / findIndex / reduce / includes / indexOf` on a Vec, FixedArray, FixedVec or Vec
@@ -95,6 +138,7 @@ export declare abstract class StatementEmitter extends CpiEmitter {
95
138
  * `find` gives an Option of the element (scalar elements), `findIndex` / `indexOf` an i64 (-1 when absent).
96
139
  */
97
140
  protected listMethod(node: ts.CallExpression, method: string): Value | undefined;
141
+ private listMethodLoop;
98
142
  /** `return` inside an expanded closure: the value goes to the closure's result, then past its body. */
99
143
  protected closureReturn(stmt: ts.ReturnStatement, frame: (typeof this.inlineFrames)[number]): void;
100
144
  /** Store a closure's result (fixing its type on the first one) and jump past the rest of its body. */
@@ -110,6 +154,19 @@ export declare abstract class StatementEmitter extends CpiEmitter {
110
154
  protected iterationClaims(body: ts.Statement): () => void;
111
155
  protected body(stmt: ts.Statement): void;
112
156
  protected variable(list: ts.VariableDeclarationList, topLevel?: boolean): void;
157
+ /**
158
+ * Whether a declaration is `/** @heap *\/`: a local list or struct kept on the heap (the bump allocator) rather
159
+ * than in the function's 4 KiB stack frame. Only in an instruction, which runs once per instruction: a helper may
160
+ * run any number of times and the heap is never freed.
161
+ */
162
+ protected heapLocal(d: ts.VariableDeclaration, aggregate: boolean): boolean;
163
+ /** A `@heap` local must fit in the heap (32 KiB, or HEAP_SIZE_KIB), which other allocations share. */
164
+ protected checkHeapRoom(bytes: number, at: ts.Node): void;
165
+ /**
166
+ * `const [address, bump] = findProgramAddressWithBump(seeds, program)`: Rust's `let (address, bump) =
167
+ * Pubkey::find_program_address(…)`, both from one search (the only array destructuring the language has).
168
+ */
169
+ protected addressAndBump(d: ts.VariableDeclaration, pattern: ts.ArrayBindingPattern, mutable: boolean): void;
113
170
  /**
114
171
  * `const { a, b: c } = s`: one declaration per name, `const a = s.a`, in source order. The source must be a name or
115
172
  * a field path (no calls), so reading it once per name reads the same thing JS reads once.