@typesol/cli 0.49.0 → 0.51.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 (79) hide show
  1. package/CHANGELOG.md +541 -0
  2. package/NOTICE +9 -0
  3. package/README.md +34 -15
  4. package/SECURITY.md +6 -3
  5. package/dist/cli.js +36 -5
  6. package/dist/compiler/analyze.d.ts +10 -1
  7. package/dist/compiler/analyze.js +234 -20
  8. package/dist/compiler/diagnostics.d.ts +4 -0
  9. package/dist/compiler/diagnostics.js +5 -1
  10. package/dist/compiler/emit/base.d.ts +35 -4
  11. package/dist/compiler/emit/base.js +46 -4
  12. package/dist/compiler/emit/borsh.js +8 -8
  13. package/dist/compiler/emit/calls.d.ts +6 -0
  14. package/dist/compiler/emit/calls.js +98 -18
  15. package/dist/compiler/emit/cpi-core.d.ts +3 -0
  16. package/dist/compiler/emit/cpi-core.js +11 -5
  17. package/dist/compiler/emit/cpi.js +6 -4
  18. package/dist/compiler/emit/create.js +9 -9
  19. package/dist/compiler/emit/expressions.d.ts +9 -1
  20. package/dist/compiler/emit/expressions.js +77 -0
  21. package/dist/compiler/emit/function.d.ts +2 -0
  22. package/dist/compiler/emit/function.js +71 -15
  23. package/dist/compiler/emit/outline.d.ts +35 -0
  24. package/dist/compiler/emit/outline.js +547 -0
  25. package/dist/compiler/emit/program.js +19 -4
  26. package/dist/compiler/emit/rbtree.js +1 -1
  27. package/dist/compiler/emit/shared.d.ts +69 -4
  28. package/dist/compiler/emit/shared.js +44 -9
  29. package/dist/compiler/emit/statements.d.ts +36 -2
  30. package/dist/compiler/emit/statements.js +332 -29
  31. package/dist/compiler/emit/storage.d.ts +16 -0
  32. package/dist/compiler/emit/storage.js +134 -13
  33. package/dist/compiler/emit/views.js +1 -1
  34. package/dist/compiler/hints.d.ts +1 -1
  35. package/dist/compiler/hints.js +9 -1
  36. package/dist/compiler/idl.js +1 -1
  37. package/dist/compiler/index.d.ts +30 -2
  38. package/dist/compiler/index.js +94 -16
  39. package/dist/compiler/model.d.ts +13 -1
  40. package/dist/compiler/stack.d.ts +71 -0
  41. package/dist/compiler/stack.js +309 -0
  42. package/dist/compiler/toolchain.d.ts +87 -5
  43. package/dist/compiler/toolchain.js +384 -19
  44. package/dist/keys.d.ts +12 -1
  45. package/dist/keys.js +57 -7
  46. package/dist/workspace.d.ts +9 -0
  47. package/dist/workspace.js +91 -16
  48. package/docker/deps/0.50.0.lock.json +1206 -0
  49. package/docker/deps/0.51.0.lock.json +1206 -0
  50. package/docs/architecture.md +1 -1
  51. package/docs/audit.md +16 -13
  52. package/docs/case-study-escrow.md +1 -1
  53. package/docs/case-study-jito-mev.md +14 -14
  54. package/docs/case-study-marginfi.md +127 -127
  55. package/docs/case-study-multisig.md +16 -4
  56. package/docs/case-study-raydium-clmm.md +44 -28
  57. package/docs/case-study-raydium-cp-swap.md +18 -18
  58. package/docs/cli.md +5 -4
  59. package/docs/glossary.md +2 -1
  60. package/docs/language-accounts.md +16 -10
  61. package/docs/language-basics.md +29 -2
  62. package/docs/language-builtins.md +4 -2
  63. package/docs/language-cpi.md +34 -0
  64. package/docs/language-native.md +50 -4
  65. package/docs/language-pdas.md +6 -2
  66. package/docs/language-statements.md +103 -12
  67. package/docs/language-types.md +93 -8
  68. package/docs/runtime.md +20 -3
  69. package/docs/security-model.md +6 -3
  70. package/docs/stability.md +10 -5
  71. package/docs/testing.md +6 -2
  72. package/docs/troubleshooting.md +45 -1
  73. package/lib/typesol.d.ts +25 -3
  74. package/llms-full.txt +403 -54
  75. package/package.json +1 -1
  76. package/releases/0.49.0.json +857 -0
  77. package/releases/0.50.0.json +874 -0
  78. package/runtime/typesol_builtins.c +47 -2
  79. package/runtime/typesol_rt.h +254 -54
@@ -6,6 +6,22 @@ export declare const MAX_ACCOUNTS = 32;
6
6
  export declare function accountLimit(model: Pick<ProgramModel, "constants">): number;
7
7
  /** Solana's limit on the seeds of one address, the bump included (MAX_SEEDS of solana-pubkey; each seed at most 32 bytes). */
8
8
  export declare const MAX_SEEDS = 16;
9
+ /**
10
+ * The runtime's derivation for a seed list the compiler proved within Solana's limits (`_fit`: no run-time check of
11
+ * the seed lengths and count, which cannot fail), or the checked one.
12
+ */
13
+ export declare const fitSuffix: (seeds: {
14
+ fit: boolean;
15
+ }) => string;
16
+ /**
17
+ * Written after a call of an account-creating runtime helper (ts_create_pda, ts_create_owned, …) given a seed list
18
+ * the compiler could not prove within the limits: the program then keeps the run-time check in those helpers
19
+ * (program.ts defines TS_PDA_SEEDS_FIT only when no body has this mark).
20
+ */
21
+ export declare const SEEDS_CHECKED_MARK = "/* seed lengths checked at run time */";
22
+ export declare const seedsCheckedMark: (seeds: {
23
+ fit: boolean;
24
+ }) => string;
9
25
  /** Max instruction data an invoke() may build, and max event payload. */
10
26
  export declare const MAX_CPI_DATA = 1024;
11
27
  export declare const MAX_EVENT = 1024;
@@ -195,13 +211,52 @@ export declare const passedByPointer: (t: ValueType) => boolean;
195
211
  * reach memory only through the accounts, remaining accounts and Inout places they are given, and pass on a subset.
196
212
  */
197
213
  export declare const unreachableArg: (c: string, pubkey: boolean) => boolean;
198
- /** Helpers get the instruction's parameters (for CPIs and accounts), then their own, then the result slot. */
199
- export declare function helperSignature(h: Helper): string;
214
+ /**
215
+ * Helpers get the instruction's parameters (for CPIs and accounts), then their own, then the result slot. `noinline`:
216
+ * the helpers (C names) the build keeps out of line to fit the stack, as if each were `@noinline`.
217
+ */
218
+ export declare function helperSignature(h: Helper, noinline?: ReadonlySet<string>): string;
219
+ /**
220
+ * How a build that would not fit the stack lays the program out instead (src/compiler/stack.ts). Empty, it changes
221
+ * nothing: the C is what the program builds to without it.
222
+ */
223
+ export interface StackPlan {
224
+ /** C functions (`ix_<name>`, `fn_<name>`) whose statements each get a C block of their own, so clang can share their temporaries' slots. */
225
+ scope?: ReadonlySet<string>;
226
+ /** Helpers (`fn_<name>`) kept out of line, as if each were `@noinline`. */
227
+ noinline?: ReadonlySet<string>;
228
+ /** Instruction locals (HeapCandidate.key) kept on the heap, as if each were `@heap`. */
229
+ heap?: ReadonlySet<string>;
230
+ /** When given, the emitter adds every instruction local that could be kept on the heap. */
231
+ candidates?: HeapCandidate[];
232
+ }
233
+ /**
234
+ * A list or struct an instruction holds itself (declared in its own body, not in a closure or a helper expanded into
235
+ * it): a local declared with its type (`const q: Big = h.b`), or the result of a helper returning a struct.
236
+ */
237
+ export interface HeapCandidate {
238
+ /** The declaration (or the helper call) in its file: `<file path>:<offset>`. */
239
+ key: string;
240
+ /** The instruction's C function (`ix_<name>`). */
241
+ fn: string;
242
+ /** What it is, for notes: "`q`", "the result of combine()". */
243
+ name: string;
244
+ /** Its C name in the generated C (`l_q_3`, `t5`), to find which C function holds it. */
245
+ c: string;
246
+ /** `file.ts:line`. */
247
+ at: string;
248
+ bytes: number;
249
+ /** `/** @stack *\/`: never moved. `/** @heap *\/`: on the heap already. */
250
+ stack?: boolean;
251
+ heap?: boolean;
252
+ }
200
253
  export interface EmitOptions {
201
254
  /** Log a marker and the remaining compute units before every statement (`typesol build --profile`). */
202
255
  profile?: boolean;
203
256
  /** Source text by absolute path (an editor's unsaved buffers), read instead of the files on disk. */
204
257
  files?: ReadonlyMap<string, string>;
258
+ /** The layout of a program that does not fit the stack otherwise (see StackPlan). */
259
+ stack?: StackPlan;
205
260
  }
206
261
  /** C type of a growable Vec stored after the first one of struct `s`: `{ uint32_t len; T items[]; }`. */
207
262
  export declare function laterVecC(s: string, field: string): string;
@@ -218,9 +273,10 @@ export declare function vecPlace(s: StructDef, base: string, k: number): {
218
273
  };
219
274
  /**
220
275
  * C lines checking that an account's size matches its growable Vecs' lengths (`d`: its TSS_<S> pointer, `a`: its
221
- * TsAccount). One Vec: ts_check_vec_len; more: each length read only once the bytes before it are known to exist.
276
+ * TsAccount, `disc`: its discriminator's length). One Vec after an 8-byte discriminator: ts_check_vec_len; otherwise
277
+ * each length read only once the bytes before it are known to exist.
222
278
  */
223
- export declare function vecLenCheck(s: StructDef, a: string, d: string, pad?: string): string[];
279
+ export declare function vecLenCheck(s: StructDef, a: string, d: string, pad?: string, disc?: number): string[];
224
280
  /** C typedef name of a FixedVec<T, N>: `{ uint32_t len; T items[N]; }`. */
225
281
  export declare function fixedVecC(t: FieldType & {
226
282
  kind: "vec";
@@ -237,3 +293,12 @@ export declare const F64_TO_INT: (to: string) => string;
237
293
  export declare const F64_TEXT = "an f64 cannot be written as text: there is no float formatting, and the digits would be its IEEE 754 bits read as an integer; to show the bits, write f64Bits(x)";
238
294
  /** An integer used where an f64 is expected. */
239
295
  export declare const INT_TO_F64: (from: string) => string;
296
+ /**
297
+ * Whether a C lvalue is reached through a pointer the optimizer cannot see behind: account data (`d_acct->f`, a
298
+ * Migrate's `(*df_a)`, a view made in place), a view or reference local, a helper's pointer parameter (`(*p_x).f`). Not a local of the
299
+ * function (`st3.f`, `l_x___v`) nor a helper's result (`(*ret)`, `(*(&t4))`), whose copies clang may fold away when it
300
+ * unrolls them: those take the memory syscalls only where it would emit a loop (runtime/typesol_rt.h).
301
+ */
302
+ export declare function throughPointer(lv: string): boolean;
303
+ /** A whole copy between two places of one type: TS_COPY when both are reached through pointers, else TS_COPY_LOCAL. */
304
+ export declare function copyMacro(dst: string, src: string): string;
@@ -9,6 +9,18 @@ export function accountLimit(model) {
9
9
  }
10
10
  /** Solana's limit on the seeds of one address, the bump included (MAX_SEEDS of solana-pubkey; each seed at most 32 bytes). */
11
11
  export const MAX_SEEDS = 16;
12
+ /**
13
+ * The runtime's derivation for a seed list the compiler proved within Solana's limits (`_fit`: no run-time check of
14
+ * the seed lengths and count, which cannot fail), or the checked one.
15
+ */
16
+ export const fitSuffix = (seeds) => (seeds.fit ? "_fit" : "");
17
+ /**
18
+ * Written after a call of an account-creating runtime helper (ts_create_pda, ts_create_owned, …) given a seed list
19
+ * the compiler could not prove within the limits: the program then keeps the run-time check in those helpers
20
+ * (program.ts defines TS_PDA_SEEDS_FIT only when no body has this mark).
21
+ */
22
+ export const SEEDS_CHECKED_MARK = "/* seed lengths checked at run time */";
23
+ export const seedsCheckedMark = (seeds) => (seeds.fit ? "" : ` ${SEEDS_CHECKED_MARK}`);
12
24
  /** Max instruction data an invoke() may build, and max event payload. */
13
25
  export const MAX_CPI_DATA = 1024;
14
26
  export const MAX_EVENT = 1024;
@@ -234,8 +246,11 @@ export const unreachableArg = (c, pubkey) => pubkey
234
246
  c === "params->program_id" ||
235
247
  /^\(&\(\*arg_\w+\)(?:\.\w+)+\)$/.test(c)
236
248
  : /^\w+$/.test(c) || /^\(\*p_\w+\)$/.test(c) || /^\(\*arg_\w+\)(?:\.\w+)+$/.test(c);
237
- /** Helpers get the instruction's parameters (for CPIs and accounts), then their own, then the result slot. */
238
- export function helperSignature(h) {
249
+ /**
250
+ * Helpers get the instruction's parameters (for CPIs and accounts), then their own, then the result slot. `noinline`:
251
+ * the helpers (C names) the build keeps out of line to fit the stack, as if each were `@noinline`.
252
+ */
253
+ export function helperSignature(h, noinline) {
239
254
  const params = ["TsParams *params"];
240
255
  for (const p of h.params) {
241
256
  if (p.account) {
@@ -265,7 +280,7 @@ export function helperSignature(h) {
265
280
  }
266
281
  if (h.returns)
267
282
  params.push(h.returns.kind === "struct" ? `TSS_${h.returns.name} *ret` : h.returns.kind === "string" ? `TS_Str *ret` : `${scalarC(h.returns)} *ret`);
268
- return `${h.noinline ? "__attribute__((noinline)) " : ""}static uint64_t fn_${h.name}(${params.join(", ")})`;
283
+ return `${h.noinline || noinline?.has(`fn_${h.name}`) ? "__attribute__((noinline)) " : ""}static uint64_t fn_${h.name}(${params.join(", ")})`;
269
284
  }
270
285
  /** C type of a growable Vec stored after the first one of struct `s`: `{ uint32_t len; T items[]; }`. */
271
286
  export function laterVecC(s, field) {
@@ -295,19 +310,20 @@ export function vecPlace(s, base, k) {
295
310
  }
296
311
  /**
297
312
  * C lines checking that an account's size matches its growable Vecs' lengths (`d`: its TSS_<S> pointer, `a`: its
298
- * TsAccount). One Vec: ts_check_vec_len; more: each length read only once the bytes before it are known to exist.
313
+ * TsAccount, `disc`: its discriminator's length). One Vec after an 8-byte discriminator: ts_check_vec_len; otherwise
314
+ * each length read only once the bytes before it are known to exist.
299
315
  */
300
- export function vecLenCheck(s, a, d, pad = " ") {
316
+ export function vecLenCheck(s, a, d, pad = " ", disc = 8) {
301
317
  const vs = s.vecs ?? [];
302
- if (vs.length === 1)
318
+ if (vs.length === 1 && disc === 8)
303
319
  return [`${pad}TS_TRY(ts_check_vec_len(${a}, sizeof(TSS_${s.name}), ${d}->${vs[0].name}__len, TS_ELEM_${s.name}));`];
304
320
  const o = `${d.replace(/\W/g, "")}__vo`;
305
321
  const lines = [`${pad}{`, `${pad} uint64_t ${o} = sizeof(TSS_${s.name}) + (uint64_t)${d}->${vs[0].name}__len * ${vs[0].elemSize};`];
306
322
  for (const v of vs.slice(1)) {
307
- lines.push(`${pad} if (${a}->data_len < 8 + ${o} + 4) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account size does not match its Vec lengths");`);
308
- lines.push(`${pad} ${o} += 4 + (uint64_t)((${laterVecC(s.name, v.name)} *)(${a}->data + 8 + ${o}))->len * ${v.elemSize};`);
323
+ lines.push(`${pad} if (${a}->data_len < ${disc} + ${o} + 4) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account size does not match its Vec lengths");`);
324
+ lines.push(`${pad} ${o} += 4 + (uint64_t)((${laterVecC(s.name, v.name)} *)(${a}->data + ${disc} + ${o}))->len * ${v.elemSize};`);
309
325
  }
310
- lines.push(`${pad} if (${a}->data_len != 8 + ${o}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account size does not match its Vec lengths");`, `${pad}}`);
326
+ lines.push(`${pad} if (${a}->data_len != ${disc} + ${o}) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account size does not match its Vec lengths");`, `${pad}}`);
311
327
  return lines;
312
328
  }
313
329
  /** C typedef name of a FixedVec<T, N>: `{ uint32_t len; T items[N]; }`. */
@@ -330,3 +346,22 @@ export const F64_TO_INT = (to) => `an f64 is not an integer, so it is not conver
330
346
  export const F64_TEXT = "an f64 cannot be written as text: there is no float formatting, and the digits would be its IEEE 754 bits read as an integer; to show the bits, write f64Bits(x)";
331
347
  /** An integer used where an f64 is expected. */
332
348
  export const INT_TO_F64 = (from) => `a ${from} is not an f64, so it is not converted: an f64 is made from its IEEE 754 bits with f64FromBits(bits)`;
349
+ /**
350
+ * Whether a C lvalue is reached through a pointer the optimizer cannot see behind: account data (`d_acct->f`, a
351
+ * Migrate's `(*df_a)`, a view made in place), a view or reference local, a helper's pointer parameter (`(*p_x).f`). Not a local of the
352
+ * function (`st3.f`, `l_x___v`) nor a helper's result (`(*ret)`, `(*(&t4))`), whose copies clang may fold away when it
353
+ * unrolls them: those take the memory syscalls only where it would emit a loop (runtime/typesol_rt.h).
354
+ */
355
+ export function throughPointer(lv) {
356
+ const m = /^\(\*([A-Za-z_][A-Za-z0-9_]*)\)/.exec(lv);
357
+ if (m)
358
+ return m[1] !== "ret";
359
+ // A view made where it is read (`(*((TSS_T *)(acct->data + off)))`, a tree node's value), not a local's address.
360
+ if (lv.startsWith("(*(") && !lv.startsWith("(*(&"))
361
+ return true;
362
+ return /^d_[A-Za-z0-9_]+->/.test(lv);
363
+ }
364
+ /** A whole copy between two places of one type: TS_COPY when both are reached through pointers, else TS_COPY_LOCAL. */
365
+ export function copyMacro(dst, src) {
366
+ return throughPointer(dst) && throughPointer(src) ? "TS_COPY" : "TS_COPY_LOCAL";
367
+ }
@@ -10,7 +10,28 @@ interface CheckCall {
10
10
  }
11
11
  export declare abstract class StatementEmitter extends CpiEmitter {
12
12
  protected statement(stmt: ts.Statement, topLevel?: boolean): void;
13
+ /** Declarations that failed (a refused const, a nested function declaration): later uses are not reported again. */
14
+ private readonly brokenDecls;
15
+ private usesBrokenName;
13
16
  protected statementInner(stmt: ts.Statement, topLevel: boolean): void;
17
+ /**
18
+ * `outer: for (…) { … }` (any loop) or `done: { … }`: the statement, then a C label after it for `break outer`, emitted
19
+ * when a jump uses it. `continue outer` goes to the loop's own `continue` label, so the step of a `for` runs, as in
20
+ * JS.
21
+ */
22
+ protected labeled(stmt: ts.LabeledStatement): void;
23
+ /**
24
+ * `break outer` / `continue outer`: a jump to the label after the statement, or to the labeled loop's `continue`
25
+ * label. The views of loadAccountMut held by the loops it leaves are dropped first, as each loop drops them at the end
26
+ * of an iteration.
27
+ */
28
+ protected labeledJump(stmt: ts.BreakStatement | ts.ContinueStatement): void;
29
+ /**
30
+ * Before a `return` from a helper or a closure: the loadAccountMut views of the loops it leaves are dropped, as each
31
+ * loop drops them at the end of an iteration, so the caller may load the same accounts again (JavaScript has no such
32
+ * claims to leak). An instruction's own return needs none: nothing of the instruction runs after it.
33
+ */
34
+ protected releaseOnReturn(stmt: ts.ReturnStatement): void;
14
35
  protected returnStatement(stmt: ts.ReturnStatement): void;
15
36
  /** `switch` on integers, enums and `.kind` of data enums: a C switch, with JS fallthrough/break semantics. */
16
37
  protected switchStatement(stmt: ts.SwitchStatement): void;
@@ -144,7 +165,7 @@ export declare abstract class StatementEmitter extends CpiEmitter {
144
165
  /** `return` inside an expanded closure: the value goes to the closure's result, then past its body. */
145
166
  protected closureReturn(stmt: ts.ReturnStatement, frame: (typeof this.inlineFrames)[number]): void;
146
167
  /** Store a closure's result (fixing its type on the first one) and jump past the rest of its body. */
147
- protected closureResult(value: Value, at: ts.Expression, frame: (typeof this.inlineFrames)[number]): void;
168
+ protected closureResult(value: Value, at: ts.Expression, frame: (typeof this.inlineFrames)[number], ret?: ts.ReturnStatement): void;
148
169
  /** `do { … } while (cond)`: the body once, then the test; `continue` goes to the test. */
149
170
  protected doLoop(stmt: ts.DoStatement): void;
150
171
  /**
@@ -164,9 +185,16 @@ export declare abstract class StatementEmitter extends CpiEmitter {
164
185
  protected heapLocal(d: ts.VariableDeclaration, aggregate: boolean): boolean;
165
186
  /** A `@heap` local must fit in the heap (32 KiB, or HEAP_SIZE_KIB), which other allocations share. */
166
187
  protected checkHeapRoom(bytes: number, at: ts.Node): void;
188
+ /**
189
+ * `const [program, data] = getReturnData()`: Rust's `get_return_data()`, the return data as the runtime holds it
190
+ * (sol_get_return_data): the program that set it and its bytes, read into 1 KiB of this function's stack frame (the
191
+ * runtime's maximum, so nothing is cut). Rust's `None` is `data.length === 0n` (the runtime keeps no empty return
192
+ * data), with `program` then all zeros.
193
+ */
194
+ protected programAndReturnData(d: ts.VariableDeclaration, pattern: ts.ArrayBindingPattern, call: ts.CallExpression, mutable: boolean): void;
167
195
  /**
168
196
  * `const [address, bump] = findProgramAddressWithBump(seeds, program)`: Rust's `let (address, bump) =
169
- * Pubkey::find_program_address(…)`, both from one search (the only array destructuring the language has).
197
+ * Pubkey::find_program_address(…)`, both from one search (with getReturnData, the only array destructuring).
170
198
  */
171
199
  protected addressAndBump(d: ts.VariableDeclaration, pattern: ts.ArrayBindingPattern, mutable: boolean): void;
172
200
  /**
@@ -204,6 +232,12 @@ export declare abstract class StatementEmitter extends CpiEmitter {
204
232
  */
205
233
  protected refuseUnreadVerifier(name: ts.Identifier, value: ts.Expression): void;
206
234
  protected expressionStatement(e: ts.Expression, topLevel: boolean): void;
235
+ /**
236
+ * `x ||= b`, `x &&= b` (booleans) and `x ??= b` (Options), as JS runs them: the place is found once, its value read,
237
+ * and only when that decides it (false, true, empty) is `b` evaluated and written; otherwise nothing runs or is
238
+ * written.
239
+ */
240
+ protected logicalAssign(e: ts.BinaryExpression, op: ts.SyntaxKind): void;
207
241
  protected assign(target: ts.Expression, valueNode: ts.Expression, op?: ts.BinaryOperator, topLevel?: boolean): void;
208
242
  }
209
243
  export {};