@typesol/cli 0.50.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 (58) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/README.md +12 -10
  3. package/SECURITY.md +5 -3
  4. package/dist/cli.js +36 -5
  5. package/dist/compiler/analyze.d.ts +8 -1
  6. package/dist/compiler/analyze.js +227 -19
  7. package/dist/compiler/diagnostics.d.ts +4 -0
  8. package/dist/compiler/diagnostics.js +5 -1
  9. package/dist/compiler/emit/base.d.ts +31 -1
  10. package/dist/compiler/emit/base.js +37 -1
  11. package/dist/compiler/emit/calls.js +27 -6
  12. package/dist/compiler/emit/cpi-core.d.ts +3 -0
  13. package/dist/compiler/emit/cpi-core.js +8 -2
  14. package/dist/compiler/emit/cpi.js +4 -2
  15. package/dist/compiler/emit/create.js +9 -9
  16. package/dist/compiler/emit/expressions.d.ts +8 -1
  17. package/dist/compiler/emit/expressions.js +65 -0
  18. package/dist/compiler/emit/function.d.ts +2 -0
  19. package/dist/compiler/emit/function.js +59 -7
  20. package/dist/compiler/emit/outline.d.ts +35 -0
  21. package/dist/compiler/emit/outline.js +547 -0
  22. package/dist/compiler/emit/program.js +11 -2
  23. package/dist/compiler/emit/shared.d.ts +57 -2
  24. package/dist/compiler/emit/shared.js +18 -3
  25. package/dist/compiler/emit/statements.d.ts +28 -1
  26. package/dist/compiler/emit/statements.js +279 -24
  27. package/dist/compiler/emit/storage.d.ts +16 -0
  28. package/dist/compiler/emit/storage.js +122 -3
  29. package/dist/compiler/hints.d.ts +1 -1
  30. package/dist/compiler/hints.js +9 -1
  31. package/dist/compiler/idl.js +1 -1
  32. package/dist/compiler/index.d.ts +15 -1
  33. package/dist/compiler/index.js +47 -10
  34. package/dist/compiler/model.d.ts +13 -1
  35. package/dist/compiler/stack.d.ts +71 -0
  36. package/dist/compiler/stack.js +309 -0
  37. package/dist/compiler/toolchain.d.ts +87 -5
  38. package/dist/compiler/toolchain.js +384 -19
  39. package/dist/workspace.d.ts +1 -0
  40. package/dist/workspace.js +1 -1
  41. package/docker/deps/0.51.0.lock.json +1206 -0
  42. package/docs/architecture.md +1 -1
  43. package/docs/audit.md +13 -11
  44. package/docs/case-study-escrow.md +1 -1
  45. package/docs/cli.md +2 -2
  46. package/docs/glossary.md +2 -1
  47. package/docs/language-basics.md +25 -1
  48. package/docs/language-pdas.md +6 -2
  49. package/docs/language-statements.md +101 -11
  50. package/docs/language-types.md +80 -5
  51. package/docs/runtime.md +1 -1
  52. package/docs/security-model.md +5 -3
  53. package/docs/stability.md +5 -1
  54. package/docs/troubleshooting.md +45 -1
  55. package/llms-full.txt +271 -27
  56. package/package.json +1 -1
  57. package/releases/0.50.0.json +874 -0
  58. package/runtime/typesol_rt.h +125 -51
@@ -98,3 +98,550 @@ export function parameterDecls(signature) {
98
98
  }
99
99
  return out;
100
100
  }
101
+ /** The comment that marks the C blocks StackPlan.scope opens around statements: `ts_scope_3{` before the `{`, `ts_scope_3}` before the `}`. */
102
+ export const SCOPE_MARK = "ts_scope_";
103
+ const SCALAR_C = /^(?:u?int(?:8|16|32|64)_t|bool|int|unsigned|__int128|__uint128_t|__int128_t)$/;
104
+ /** Runtime types with no pointer field. */
105
+ const POINTER_FREE_C = new Set(["SolPubkey", "TsU256", "ts_u32_unaligned", "ts_u64_unaligned"]);
106
+ /**
107
+ * The C of a function (with the loops moved out of it) whose statements were put in blocks of their own: each block
108
+ * stays, without its mark, unless taking its names out of scope could change the program, and then only its braces
109
+ * go. A block keeps its braces only when all of these hold (`own`: the names it declares, C's own types and the
110
+ * runtime's declaring macros included):
111
+ *
112
+ * 1. no name of `own` is used after it (a bump a later check reads, a seed list a later statement reuses);
113
+ * 2. no assignment to a variable declared outside it stores `&x` or an array, pointer or aggregate it declares not
114
+ * read through a field or an index (storesAddress);
115
+ * 3. no address of its storage can reach memory that outlives it (leaksAddress), with or without an `=`.
116
+ *
117
+ * Rule 3 follows, through every statement of the block until nothing changes, which expressions may hold an address
118
+ * of the block's storage: `&x` of a local of `own` (`&p->f` through a pointer of `own` points where the pointer does),
119
+ * an array of `own` not indexed, a local of `own` that was assigned such an expression (a *holder*, read whole or in
120
+ * part), and what ts_str and ts_fstr_view build of one; a field or element of a local of `own` may be an array that
121
+ * decays to such an address, which a number or a struct cannot take. The block loses its braces when such an
122
+ * expression
123
+ *
124
+ * - is assigned to anything but a local of `own`: a variable declared outside it, or a place reached through a
125
+ * pointer, a cast or a macro (`*p`, `p->f`, `p[i]`, `*(T *)…`, the meta list a TS_METAS macro declares, which may
126
+ * be heap scratch); a field or element only counts where a pointer may be, not in a number or in a struct of a
127
+ * type with no pointer field (`pointerFree`: the program's types, from the emitter) reached by fields, indexes and
128
+ * one dereference;
129
+ * - is returned;
130
+ * - is an argument of a call other than the runtime functions and macros that keep nothing of their arguments
131
+ * (KEEPS_NOTHING, the program's helpers and loops among them) and copies (COPIES), or of any call through a
132
+ * field or a local; a copy takes them away only when what it moves may itself hold such an address (a holder's
133
+ * own bytes, or what a holder pointing at a holder points to).
134
+ *
135
+ * Anything the analysis cannot follow (a function or macro not on the lists, an unknown declaration) is taken to keep
136
+ * what it is given, so the braces stay only where no address of the block can be read after it.
137
+ */
138
+ export function settleScopes(c, pointerFree = new Set()) {
139
+ const lines = c.split("\n");
140
+ const open = new Map();
141
+ const pairs = [];
142
+ const openRe = new RegExp(`^\\s*/\\*${SCOPE_MARK}(\\d+)\\{\\*/ \\{$`);
143
+ const closeRe = new RegExp(`^\\s*/\\*${SCOPE_MARK}(\\d+)\\}\\*/ \\}$`);
144
+ lines.forEach((l, i) => {
145
+ const o = openRe.exec(l);
146
+ if (o)
147
+ open.set(o[1], i);
148
+ const e = closeRe.exec(l);
149
+ if (e && open.has(e[1]))
150
+ pairs.push([open.get(e[1]), i]);
151
+ });
152
+ if (!pairs.length)
153
+ return c;
154
+ // The last line each name is used on.
155
+ const lastUse = new Map();
156
+ const toks = lines.map((l) => cTokens(l));
157
+ toks.forEach((t, i) => {
158
+ for (const n of usedNames(t))
159
+ lastUse.set(n, i);
160
+ });
161
+ // The names every declaration of which, anywhere in the text, is a number or a struct: not a pointer or an array.
162
+ const kindsAll = declarationKinds(toks.flat());
163
+ const values = new Set([...kindsAll.all].filter(([, ks]) => ks.every((k) => k === "scalar" || k === "aggregate")).map(([n]) => n));
164
+ // The types of every declaration and parameter of the text.
165
+ const types = new Map(kindsAll.types);
166
+ for (const l of lines)
167
+ if (/^\S.*\)\s*\{$/.test(l) && l.includes("("))
168
+ for (const decl of parameterDecls(l.slice(0, l.lastIndexOf(")") + 1)).values()) {
169
+ const m = /(\w+)([\s*]*)(?:restrict\s+)?(\w+)$/.exec(decl.replace(/\bconst\b/g, " ").trim());
170
+ if (m)
171
+ types.set(m[3], (types.get(m[3]) ?? new Set()).add((SCALAR_C.test(m[1]) ? "int" : m[1]) + "*".repeat(m[2].split("*").length - 1)));
172
+ }
173
+ // 0: every declaration of `n` is a number or a struct with no pointer field; 1: a pointer to one; -1: anything else.
174
+ const pointerDepth = (n) => {
175
+ const ts_ = types.get(n);
176
+ if (!ts_)
177
+ return -1;
178
+ let depth = 0;
179
+ for (const x of ts_) {
180
+ const stars = x.length - x.replace(/\*+$/, "").length;
181
+ const base = x.slice(0, x.length - stars);
182
+ if (stars > 1 || !(base === "int" || POINTER_FREE_C.has(base) || pointerFree.has(base)))
183
+ return -1;
184
+ depth = Math.max(depth, stars);
185
+ }
186
+ return depth;
187
+ };
188
+ const remove = new Set();
189
+ const strip = new Set();
190
+ for (const [from, to] of pairs) {
191
+ const inner = toks.slice(from + 1, to).flat();
192
+ const declared = declaredNames(inner);
193
+ const decls = declarationKinds(inner);
194
+ const own = new Set([...declared, ...decls.kinds.keys()]);
195
+ let keep = ![...own].some((n) => (lastUse.get(n) ?? -1) > to);
196
+ if (keep) {
197
+ // Names that hold or decay to an address: arrays, pointers and every aggregate it declares.
198
+ const addressy = new Set();
199
+ for (let i = from + 1; i < to && keep; i++) {
200
+ const m = /^\s*(?:static\s+)?(?:const\s+)?(?:struct\s+)?(\w+)\s*(\*?)\s*(?:const\s+)?\*?\s*(\w+)\s*(\[)?/.exec(lines[i]);
201
+ if (m && declared.has(m[3]) && (m[2] || m[4] || !SCALAR_C.test(m[1])))
202
+ addressy.add(m[3]);
203
+ }
204
+ for (let i = from + 1; i < to && keep; i++)
205
+ if (storesAddress(toks[i], declared, addressy))
206
+ keep = false;
207
+ }
208
+ if (keep && leaksAddress(inner, own, decls, values, pointerDepth))
209
+ keep = false;
210
+ if (keep)
211
+ strip.add(from).add(to);
212
+ else
213
+ remove.add(from).add(to);
214
+ }
215
+ const out = [];
216
+ lines.forEach((l, i) => {
217
+ if (remove.has(i))
218
+ return;
219
+ out.push(strip.has(i) ? l.replace(/\/\*ts_scope_\d+[{}]\*\/ /, "") : l);
220
+ });
221
+ return out.join("\n");
222
+ }
223
+ /** `&` after a name, a number or an index is a bitwise and; after anything else (a cast's `)` included) an address. */
224
+ const operand = (x) => x !== undefined && (/^\w/.test(x) || x === "]");
225
+ /** The `=` at `eq` assigns (it is not `==`, `<=`, `>=` or `!=`; `+=` and the like are). */
226
+ const isAssignment = (t, eq) => t[eq] === "=" && t[eq + 1] !== "=" && !["=", "!", "<", ">"].includes(t[eq - 1] ?? "");
227
+ /** The index of the variable the left side of the `=` at `eq` names: the first name, going left, not read as a field (`(*d_h).a.tag`, `st.xs[i]`). */
228
+ function assignmentRoot(t, eq) {
229
+ for (let k = eq - 1; k >= 0; k--) {
230
+ const x = t[k];
231
+ if (x === ";" || x === "{" || x === "}")
232
+ return undefined;
233
+ if (x === "]") {
234
+ let depth = 0;
235
+ for (; k >= 0; k--) {
236
+ if (t[k] === "]")
237
+ depth++;
238
+ else if (t[k] === "[" && --depth === 0)
239
+ break;
240
+ }
241
+ continue;
242
+ }
243
+ if (/^[A-Za-z_]/.test(x) && t[k - 1] !== "." && t[k - 1] !== "->")
244
+ return k;
245
+ }
246
+ return undefined;
247
+ }
248
+ /** The end (exclusive) of the right side of the `=` at `eq`: a `;` or `,` outside brackets, or the bracket it is in closing. */
249
+ function assignmentEnd(t, eq) {
250
+ let end = eq + 1;
251
+ for (let depth = 0; end < t.length; end++) {
252
+ if (t[end] === "(" || t[end] === "[" || t[end] === "{")
253
+ depth++;
254
+ else if (t[end] === ")" || t[end] === "]" || t[end] === "}")
255
+ depth--;
256
+ if (depth < 0 || (depth === 0 && (t[end] === ";" || t[end] === ",")))
257
+ break;
258
+ }
259
+ return end;
260
+ }
261
+ /** The index of the bracket opening the one that closes at `close`. */
262
+ function opening(t, close) {
263
+ let depth = 0;
264
+ for (let k = close; k >= 0; k--) {
265
+ if (t[k] === ")" || t[k] === "]" || t[k] === "}")
266
+ depth++;
267
+ else if ((t[k] === "(" || t[k] === "[" || t[k] === "{") && --depth === 0)
268
+ return k;
269
+ }
270
+ return -1;
271
+ }
272
+ /** The index of the bracket closing the one at `open`. */
273
+ function closing(t, open) {
274
+ let depth = 0;
275
+ for (let k = open; k < t.length; k++) {
276
+ if (t[k] === "(" || t[k] === "[" || t[k] === "{")
277
+ depth++;
278
+ else if ((t[k] === ")" || t[k] === "]" || t[k] === "}") && --depth === 0)
279
+ return k;
280
+ }
281
+ return t.length;
282
+ }
283
+ /**
284
+ * Whether a line of C assigns, to a variable that is not one of `own`, an expression holding the address of one of
285
+ * `own`: `&x`, or a name of `addressy` (an array, a pointer, an aggregate) not read through a field or an index.
286
+ */
287
+ function storesAddress(t, own, addressy) {
288
+ for (let eq = 0; eq < t.length; eq++) {
289
+ if (!isAssignment(t, eq))
290
+ continue;
291
+ const at = assignmentRoot(t, eq);
292
+ if (at === undefined || own.has(t[at]))
293
+ continue;
294
+ const end = assignmentEnd(t, eq);
295
+ for (let k = eq + 1; k < end; k++) {
296
+ const x = t[k];
297
+ if (!own.has(x) || t[k - 1] === "." || t[k - 1] === "->")
298
+ continue;
299
+ if (t[k - 1] === "&" && !operand(t[k - 2]))
300
+ return true;
301
+ if (addressy.has(x) && t[k + 1] !== "." && t[k + 1] !== "->" && t[k + 1] !== "[")
302
+ return true;
303
+ }
304
+ }
305
+ return false;
306
+ }
307
+ /** C's own type words (KEYWORDS, which declaredNames does not take for a type). */
308
+ const C_TYPE_WORDS = new Set(["int", "char", "short", "long", "double", "float", "void", "_Bool"]);
309
+ const QUALIFIERS = new Set(["const", "static", "struct", "volatile", "register", "unsigned", "signed"]);
310
+ /** Runtime macros that declare their first argument: a CPI's meta list (an array, or a pointer to heap scratch). Its kind is an array's; writes into it count as writes through a pointer. */
311
+ const DECLARING_MACROS = new Set(["TS_METAS", "TS_METAS_ROOM"]);
312
+ /**
313
+ * Every declaration of `toks` (as declaredNames finds them, and also those of C's own types, `int k`, `unsigned char
314
+ * b[4]`, and the runtime's declaring macros): what each name is (`all`: every declaration of it; `kinds`: the most
315
+ * cautious of them, an array when they differ) and where each declared name stands (a declarator, not an assignment).
316
+ */
317
+ function declarationKinds(toks) {
318
+ const all = new Map();
319
+ const types = new Map();
320
+ const at = new Set();
321
+ const add = (name, k, i, type = "") => {
322
+ all.set(name, [...(all.get(name) ?? []), k]);
323
+ types.set(name, (types.get(name) ?? new Set()).add(type));
324
+ at.add(i);
325
+ };
326
+ for (let i = 0; i < toks.length; i++) {
327
+ const prev = toks[i - 1];
328
+ const start = i === 0 || prev === ";" || prev === "{" || prev === "}" || (prev === "(" && toks[i - 2] === "for");
329
+ if (!start || !isIdent(toks[i]))
330
+ continue;
331
+ if (DECLARING_MACROS.has(toks[i]) && toks[i + 1] === "(" && isIdent(toks[i + 2])) {
332
+ add(toks[i + 2], "array", i + 2, "SolAccountMeta");
333
+ continue;
334
+ }
335
+ let j = i;
336
+ let words = 0;
337
+ while (QUALIFIERS.has(toks[j]) || C_TYPE_WORDS.has(toks[j])) {
338
+ if (C_TYPE_WORDS.has(toks[j]) || toks[j] === "unsigned" || toks[j] === "signed")
339
+ words++;
340
+ j++;
341
+ }
342
+ let scalar = words > 0;
343
+ let type = "int";
344
+ // A type name of its own (`uint64_t`, `TS_Str`), unless C's words were the type (`unsigned k = …`).
345
+ if (isIdent(toks[j]) && !KEYWORDS.has(toks[j]) && !(words > 0 && ["=", ";", "[", ","].includes(toks[j + 1]))) {
346
+ type = toks[j];
347
+ scalar = SCALAR_C.test(type) || (words > 0 && /^__u?int128(?:_t)?$/.test(type));
348
+ j++;
349
+ }
350
+ else if (words === 0)
351
+ continue;
352
+ for (;;) {
353
+ let stars = 0;
354
+ while (toks[j] === "*" || toks[j] === "const" || toks[j] === "restrict")
355
+ stars += toks[j++] === "*" ? 1 : 0;
356
+ const name = toks[j];
357
+ const after = toks[j + 1];
358
+ if (!isIdent(name) || KEYWORDS.has(name) || !["=", ";", "[", ",", ")"].includes(after))
359
+ break;
360
+ // The type with its stars (an array of pointers counts as two: indexing it gives a pointer).
361
+ const base = scalar ? "int" : type;
362
+ add(name, stars ? "pointer" : after === "[" ? "array" : scalar ? "scalar" : "aggregate", j, base + "*".repeat(stars && after === "[" ? 2 : stars));
363
+ j++;
364
+ let depth = 0;
365
+ while (j < toks.length) {
366
+ const t = toks[j];
367
+ if (t === "(" || t === "[" || t === "{")
368
+ depth++;
369
+ else if (t === ")" || t === "]" || t === "}") {
370
+ if (depth === 0)
371
+ break;
372
+ depth--;
373
+ }
374
+ else if (depth === 0 && (t === "," || t === ";"))
375
+ break;
376
+ j++;
377
+ }
378
+ if (toks[j] !== ",")
379
+ break;
380
+ j++;
381
+ }
382
+ }
383
+ const kinds = new Map();
384
+ for (const [n, ks] of all)
385
+ kinds.set(n, ks.every((k) => k === ks[0]) ? ks[0] : "array");
386
+ return { kinds, all, types, at };
387
+ }
388
+ /**
389
+ * Functions and macros that keep nothing of what they are given: they read through their pointer arguments and write
390
+ * numbers, bytes, or pointers to new heap memory, constants or account data into the places those point to, and no
391
+ * pointer they are given or read through one survives the call (ts_invoke's account infos are scratch that every CPI
392
+ * writes again before the runtime reads it; ts_create_owned leaves a pointer to a local of its own in the seed list's
393
+ * spare slot, which nothing reads). The program's helpers and the loops moved out of a function are among them
394
+ * (KEEPS_NOTHING_NAMED): their source cannot keep a reference (a struct of the program has no pointer field, a string
395
+ * result is copied to the heap, and Inout<string> is refused), and Borsh encoders only write bytes.
396
+ */
397
+ const KEEPS_NOTHING = new Set(("TS_TRY TS_FAIL ts_fail_code " +
398
+ "ts_add_overflow_u64 ts_sub_overflow_u64 ts_mul_overflow_u64 ts_mul_overflow_u128 __builtin_add_overflow __builtin_sub_overflow " +
399
+ "__builtin_mul_overflow ts_mul_div ts_mul_div_u128 ts_u256_add ts_u256_sub ts_u256_mul ts_u256_muldiv ts_isqrt_u256 " +
400
+ "ts_check_writable ts_check_executable ts_check_signer ts_check_unaliased ts_check_program_account ts_key_eq ts_mem_eq " +
401
+ "ts_is_token_program ts_str_eq ts_claim_mut ts_claim_mut_rec ts_claim_mut_at ts_claim_mut_at_rec ts_release_mut " +
402
+ "TS_ZERO TS_ZERO_LOCAL ts_memzero ts_memzero_bulk ts_memzero_run sol_memset_ " +
403
+ "sol_log_ sol_log_64_ sol_log_data sol_log_pubkey sol_log_compute_units sol_set_return_data sol_get_return_data " +
404
+ "ts_return_data ts_return_data_exact sol_sha256 sol_keccak256 ts_log_base64 ts_secp256k1_verify ts_epoch_rewards " +
405
+ "ts_str_u64 ts_str_i64 ts_str_u128 ts_str_join ts_str_concat ts_str_copy ts_str_append ts_str_append_n ts_str_append_parts " +
406
+ "ts_base58_32 ts_fstr_set ts_alloc " +
407
+ "ts_invoke ts_cpi ts_cpi_named sol_invoke_signed ts_token_transfer ts_token_transfer_checked ts_token_mint_to ts_token_burn " +
408
+ "ts_token_close ts_system_transfer ts_system_transfer_signed ts_create_pda ts_create_pda_owned ts_create_pda_if_needed " +
409
+ "ts_create_owned ts_find_pda ts_find_pda_fit ts_create_pda_address ts_create_pda_address_fit ts_require_pda_fit ts_ata_address " +
410
+ "ts_now ts_clock_u64 ts_minimum_balance ts_epoch_schedule ts_stake_history ts_last_restart_slot ts_require_pda ts_metadata_address " +
411
+ "ts_master_edition_address ts_pyth_price ts_switchboard_value ts_token_cpi ts_token_account_space ts_t22_init_metadata " +
412
+ "ts_mpl_create_v3 ts_mpl_update_v2 ts_t22_layout ts_t22_key ts_t22_ext ts_t22_extensions_within ts_t22_transfer_fee " +
413
+ "ts_t22_transfer_fee_inverse ts_t22_epoch_fee ts_read_le ts_write_le ts_key_cmp ts_sibling_load ts_token_transfer_checked_hook").split(" "));
414
+ const KEEPS_NOTHING_NAMED = /^(?:fn_\w+|\w+__loop\d+|ts_pack_\w+|ts_benc_\w+)$/;
415
+ /**
416
+ * Functions that keep nothing either, but copy bytes from where one argument points to where another does, or hand
417
+ * back a pointer that the memory an argument points to holds (or one past it: a red-black tree's node in its buffer,
418
+ * an account's data, an instruction of the instructions sysvar), never one into that memory itself: what they move
419
+ * is an address of the block's storage only when that memory holds one.
420
+ */
421
+ const COPIES = new Set("TS_MEMCPY TS_COPY TS_COPY_LOCAL ts_memcpy ts_copy ts_copy_value ts_memmove sol_memmove_ sol_memcpy_ ts_memcpy_const ts_memcpy_bulk".split(" "));
422
+ const COPIES_NAMED = /^(?:ts_rbt\w*|TS_RBT_\w+|ts_ix_\w+|ts_sb_randomness_value)$/;
423
+ /** Functions whose result is made of their arguments (a string view of a pointer and a length, the bytes after a FixedString's length). */
424
+ const PASSES = new Set(["ts_str", "ts_fstr_view"]);
425
+ /** Built-in operators written as calls, which only look at their operand's type. */
426
+ const TYPE_ONLY = new Set(["sizeof", "_Alignof", "__builtin_offsetof", "__typeof__"]);
427
+ /**
428
+ * How much an expression may hold an address of the block's storage: not at all; only as an array that decays to
429
+ * one (a field or element of a local of the block that holds no address: a number or a struct cannot take it, only a
430
+ * pointer can); or as an address.
431
+ */
432
+ const Carry = { None: 0, Decay: 1, Address: 2 };
433
+ /**
434
+ * Whether the tokens `t` of a block (whose declarations are `decls`, all of them in `own`) may leave an address of
435
+ * the block's storage where the program reads it after the block (settleScopes, rule 3). `values`: the names declared
436
+ * only as numbers or structs (never a pointer or an array) anywhere in the function; `pointerDepth`: 0 when every
437
+ * declaration of a name (a parameter's included) is a number or a struct of a type with no pointer field, 1 when it
438
+ * may be a pointer to one, -1 otherwise.
439
+ */
440
+ function leaksAddress(t, own, decls, values, pointerDepth) {
441
+ const kind = (n) => decls.kinds.get(n) ?? "array";
442
+ // The lists the runtime's macros declare: an array of the block, or a pointer to heap scratch (TS_SCRATCH_ON_HEAP).
443
+ const scratch = new Set();
444
+ for (let k = 0; k + 2 < t.length; k++)
445
+ if (DECLARING_MACROS.has(t[k]) && t[k + 1] === "(" && (k === 0 || [";", "{", "}"].includes(t[k - 1])))
446
+ scratch.add(t[k + 2]);
447
+ // Locals of the block that may hold an address of its storage; `deep`: that may point to such a local.
448
+ const holders = new Set();
449
+ const deep = new Set();
450
+ let changed = true;
451
+ const hold = (n, isDeep) => {
452
+ if (!holders.has(n))
453
+ (holders.add(n), (changed = true));
454
+ if (isDeep && !deep.has(n))
455
+ (deep.add(n), (changed = true));
456
+ };
457
+ let leak = false;
458
+ /** Unary `*` or `&` at `k` (not multiplication or a bitwise and). */
459
+ const unary = (k, op) => t[k] === op && !operand(t[k - 1]);
460
+ /** Past parentheses and `++` / `--` going left from `k`. */
461
+ const skipLeft = (k) => {
462
+ for (;;) {
463
+ if (t[k] === "(")
464
+ k--;
465
+ else if ((t[k] === "-" || t[k] === "+") && t[k - 1] === t[k])
466
+ k -= 2;
467
+ else
468
+ return k;
469
+ }
470
+ };
471
+ /** The operator applied to the name at `k`: `&x`, `&(x)`, `*p`, `*--p`; `*(&x)` is `x`. */
472
+ const prefix = (k) => {
473
+ const b = skipLeft(k - 1);
474
+ if (!unary(b, "&"))
475
+ return { addr: false, deref: unary(b, "*") };
476
+ return unary(skipLeft(b - 1), "*") ? { addr: false, deref: false } : { addr: true, deref: false };
477
+ };
478
+ const isHolder = (k) => holders.has(t[k]) && t[k - 1] !== "." && t[k - 1] !== "->";
479
+ /** What the name of `own` at `k` (not a field name) carries. */
480
+ const occurrence = (k) => {
481
+ const n = t[k];
482
+ const next = t[k + 1];
483
+ const { addr, deref } = prefix(k);
484
+ const part = next === "." || next === "->" || next === "[";
485
+ const k_ = kind(n);
486
+ if (k_ === "pointer") {
487
+ // The pointer, or (through it) what it points to: the block's only when the block gave it an address.
488
+ if (addr)
489
+ return !part || holders.has(n) ? Carry.Address : Carry.None;
490
+ if (!holders.has(n))
491
+ return Carry.None;
492
+ return !part && !deref ? Carry.Address : deep.has(n) ? Carry.Address : Carry.Decay;
493
+ }
494
+ if (addr || holders.has(n))
495
+ return Carry.Address;
496
+ if (k_ === "array")
497
+ return part ? Carry.Decay : Carry.Address;
498
+ if (k_ === "aggregate")
499
+ return part ? Carry.Decay : Carry.None;
500
+ return Carry.None;
501
+ };
502
+ /** Whether bytes that a copy (COPIES) of the arguments `t[lo, hi)` moves may be an address of the block's storage. */
503
+ const reachesAddress = (lo, hi) => {
504
+ for (let k = lo; k < hi; k++) {
505
+ if (!isHolder(k))
506
+ continue;
507
+ const n = t[k];
508
+ const next = t[k + 1];
509
+ // The holder's own bytes (its address, an array decaying), or what it points to when that holds an address.
510
+ const own_ = (prefix(k).addr && (kind(n) !== "pointer" || (next !== "->" && next !== "["))) || (kind(n) === "array" && next !== "[");
511
+ if (own_ || deep.has(n) || kind(n) === "aggregate" || kind(n) === "scalar")
512
+ return true;
513
+ }
514
+ return false;
515
+ };
516
+ const mentionsHolder = (lo, hi) => {
517
+ for (let k = lo; k < hi; k++)
518
+ if (isHolder(k))
519
+ return true;
520
+ return false;
521
+ };
522
+ /** What the expression `t[lo, hi)` carries; a call that may keep what it is given sets `leak`. */
523
+ const carried = (lo, hi) => {
524
+ let c = Carry.None;
525
+ for (let k = lo; k < hi; k++) {
526
+ const x = t[k];
527
+ if (!isIdent(x))
528
+ continue;
529
+ const field = t[k - 1] === "." || t[k - 1] === "->";
530
+ if (t[k + 1] === "(" && (!KEYWORDS.has(x) || TYPE_ONLY.has(x))) {
531
+ const end = closing(t, k + 1);
532
+ // A runtime function by its name; a call through a field or a local (a function pointer) may keep anything.
533
+ const named = !field && !own.has(x);
534
+ if (named && DECLARING_MACROS.has(x)) {
535
+ // TS_METAS(m, {…}, …): the list it declares may be heap scratch, which outlives the block.
536
+ if (carried(assignmentEnd(t, k + 1) + 1, end) !== Carry.None)
537
+ leak = true;
538
+ }
539
+ else if (!TYPE_ONLY.has(x)) {
540
+ const args = carried(k + 2, end);
541
+ if (named && PASSES.has(x))
542
+ c = Math.max(c, args);
543
+ else if (named && (COPIES.has(x) || COPIES_NAMED.test(x)))
544
+ leak ||= reachesAddress(k + 2, end);
545
+ else if (!named || !(KEEPS_NOTHING.has(x) || KEEPS_NOTHING_NAMED.test(x)))
546
+ leak ||= args !== Carry.None;
547
+ }
548
+ k = end;
549
+ continue;
550
+ }
551
+ if (!field && own.has(x))
552
+ c = Math.max(c, occurrence(k));
553
+ }
554
+ return c;
555
+ };
556
+ /**
557
+ * Whether the left side of the `=` at `eq`, rooted at `at`, is a number or a part of a struct with no pointer field:
558
+ * the root, then fields, indexes and `(*root)` only (no cast, no call), a pointer root dereferenced once.
559
+ */
560
+ const noPointerPlace = (at, eq) => {
561
+ const depth = pointerDepth(t[at]);
562
+ if (depth < 0)
563
+ return false;
564
+ let b = skipLeft(at - 1);
565
+ let derefs = 0;
566
+ if (unary(b, "*"))
567
+ ((b = skipLeft(b - 1)), derefs++);
568
+ const boundary = b < 0 || [";", "{", "}", "else", ":"].includes(t[b]) || (t[b] === ")" && ["if", "while", "for", "switch"].includes(t[opening(t, b) - 1]));
569
+ if (!boundary)
570
+ return false;
571
+ let end = eq;
572
+ while (end - 1 > at && /^[-+*/%&|^<>]$/.test(t[end - 1]))
573
+ end--;
574
+ for (let i = at + 1; i < end; i++) {
575
+ if (t[i] === "[") {
576
+ if (i === at + 1 && depth === 1)
577
+ derefs++;
578
+ i = closing(t, i);
579
+ }
580
+ else if ((t[i] === "." || t[i] === "->") && isIdent(t[i + 1])) {
581
+ if (t[i] === "->" && i === at + 1)
582
+ derefs++;
583
+ i++;
584
+ }
585
+ else if (t[i] !== ")")
586
+ return false;
587
+ }
588
+ return derefs === depth;
589
+ };
590
+ while (changed) {
591
+ changed = false;
592
+ leak = false;
593
+ carried(0, t.length);
594
+ for (let eq = 0; eq < t.length; eq++) {
595
+ if (t[eq] === "return" && t[eq - 1] !== "." && t[eq - 1] !== "->") {
596
+ if (carried(eq + 1, assignmentEnd(t, eq)) !== Carry.None)
597
+ leak = true;
598
+ continue;
599
+ }
600
+ if (!isAssignment(t, eq))
601
+ continue;
602
+ const end = assignmentEnd(t, eq);
603
+ const rhs = carried(eq + 1, end);
604
+ if (rhs === Carry.None)
605
+ continue;
606
+ const at = assignmentRoot(t, eq);
607
+ if (at === undefined) {
608
+ // A designated initializer's `.f = …` inside braces: the `=` of the declaration or assignment takes it whole.
609
+ if (t[eq - 2] === "." && (t[eq - 3] === "{" || t[eq - 3] === ","))
610
+ continue;
611
+ leak = true;
612
+ continue;
613
+ }
614
+ const root = t[at];
615
+ const declared = decls.at.has(at);
616
+ // Through a pointer, a cast or a macro: `*p = …`, `(*p).f = …`, `p->f = …`, `p[i] = …`, `*(T *)(b + 8) = …`.
617
+ // A `)` before it closes a cast, unless it closes the condition of an `if`, `while` or `for` before the statement.
618
+ const b = skipLeft(at - 1);
619
+ const control = t[b] === ")" && ["if", "while", "for", "switch"].includes(t[opening(t, b) - 1]);
620
+ const between = t.slice(at + 1, eq);
621
+ const through = !declared &&
622
+ (scratch.has(root) ||
623
+ unary(b, "*") ||
624
+ (t[b] === ")" && !control) ||
625
+ between.some((x) => x === "->" || x === "(" || x === ")" || (x === "[" && kind(root) === "pointer")));
626
+ // The variable itself, with `=` or a compound assignment (`+=`, `<<=`), not a part of it.
627
+ const whole = !through && between.every((x) => /^[-+*/%&|^<>]$/.test(x)) && between.length <= 2;
628
+ if (own.has(root) && !through) {
629
+ // A decaying array stored whole in a number or a struct does not compile: it is no address there.
630
+ if (rhs === Carry.Decay && whole && kind(root) !== "pointer")
631
+ continue;
632
+ if (rhs === Carry.Decay && noPointerPlace(at, eq))
633
+ continue;
634
+ hold(root, mentionsHolder(eq + 1, end));
635
+ continue;
636
+ }
637
+ if (rhs === Carry.Decay && whole && !own.has(root) && values.has(root))
638
+ continue;
639
+ // A part of a struct with no pointer field (account data, a struct of the program), reached by fields, indexes
640
+ // and dereferences only: a number or a struct, which a decaying array is not.
641
+ if (rhs === Carry.Decay && noPointerPlace(at, eq))
642
+ continue;
643
+ leak = true;
644
+ }
645
+ }
646
+ return leak;
647
+ }
@@ -1,5 +1,5 @@
1
1
  import ts from "typescript";
2
- import { accountLimit, cBytes, scalarStorageC, optC, storageDecl, helperSignature, fieldC, fixedVecC, laterVecC } from "./shared.js";
2
+ import { accountLimit, cBytes, scalarStorageC, optC, storageDecl, helperSignature, fieldC, fixedVecC, laterVecC, SEEDS_CHECKED_MARK, } from "./shared.js";
3
3
  import { FunctionEmitter } from "./function.js";
4
4
  import { emitBorshCodecs, emitNativeBorshCodecs } from "./borsh.js";
5
5
  import { emitRbTrees } from "./rbtree.js";
@@ -81,12 +81,21 @@ export function emitProgram(analysis, opts = {}) {
81
81
  reporter.error(analysis.sourceFile, 'EVENT_AUTHORITY_CHECK must be "address" (the event authority checked as Anchor 1.x\'s `address = EVENT_AUTHORITY` constraint, 2012 among the constraints, and the program account left unchecked); leave it out for the default');
82
82
  // `const NATIVE_ACCOUNT_WRITES = true`: loadRawMut / storeBorsh / BigVec writes leave writability and aliasing to the
83
83
  // runtime, as a native program does (read by the emitter; nothing to define in C).
84
+ // `const STACK_AUTO = false`: a program that does not fit the stack fails to build instead of being laid out
85
+ // another way (read by the build, src/compiler/stack.ts; nothing to define in C).
86
+ const stackAuto = model.constants.get("STACK_AUTO");
87
+ if (stackAuto && typeof stackAuto.value !== "boolean")
88
+ reporter.error(analysis.sourceFile, "STACK_AUTO must be true or false");
84
89
  const nativeWrites = model.constants.get("NATIVE_ACCOUNT_WRITES");
85
90
  if (nativeWrites && typeof nativeWrites.value !== "boolean")
86
91
  reporter.error(analysis.sourceFile, "NATIVE_ACCOUNT_WRITES must be true or false");
87
92
  // resizeAccount on a remaining account: the entrypoint records every account's size when the instruction starts.
88
93
  if ([...helperBodies, ...ixBodies].some((b) => b.includes("ts_entry_len(")))
89
94
  out.push(`#define TS_RECORD_ENTRY_LEN 1`);
95
+ // The account-creating runtime helpers leave out the check of the seed limits when every seed list this program
96
+ // passes them was proven within those limits (see seedsCheckedMark).
97
+ if (![...helperBodies, ...ixBodies].some((b) => b.includes(SEEDS_CHECKED_MARK)))
98
+ out.push(`#define TS_PDA_SEEDS_FIT 1`);
90
99
  // Native account views share one owner-check cache (ts_owned), zeroed in the entry point.
91
100
  if (model.ownerCache)
92
101
  out.push(`#define TS_OWNER_CACHE 1`);
@@ -201,7 +210,7 @@ export function emitProgram(analysis, opts = {}) {
201
210
  out.push(...emitBorshCodecs(model), ...emitNativeBorshCodecs(model));
202
211
  const helpers = [...model.helpers.values()];
203
212
  for (const h of helpers)
204
- out.push(helperSignature(h) + ";");
213
+ out.push(helperSignature(h, opts.stack?.noinline) + ";");
205
214
  if (helpers.length)
206
215
  out.push("");
207
216
  // RedBlackTree instances: after the helper prototypes (a comparator is a helper), before the code that uses them.
@@ -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;