@typesol/cli 0.42.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 (44) hide show
  1. package/CHANGELOG.md +227 -0
  2. package/README.md +10 -7
  3. package/dist/compiler/analyze.js +443 -12
  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 +25 -0
  9. package/dist/compiler/emit/base.js +58 -7
  10. package/dist/compiler/emit/calls.d.ts +67 -0
  11. package/dist/compiler/emit/calls.js +521 -46
  12. package/dist/compiler/emit/cpi-core.d.ts +20 -3
  13. package/dist/compiler/emit/cpi-core.js +226 -5
  14. package/dist/compiler/emit/cpi.js +8 -2
  15. package/dist/compiler/emit/expressions.js +38 -7
  16. package/dist/compiler/emit/program.js +30 -1
  17. package/dist/compiler/emit/rbtree.d.ts +7 -0
  18. package/dist/compiler/emit/rbtree.js +142 -0
  19. package/dist/compiler/emit/shared.d.ts +8 -0
  20. package/dist/compiler/emit/shared.js +9 -1
  21. package/dist/compiler/emit/statements.d.ts +27 -1
  22. package/dist/compiler/emit/statements.js +288 -19
  23. package/dist/compiler/emit/storage.d.ts +23 -2
  24. package/dist/compiler/emit/storage.js +100 -56
  25. package/dist/compiler/emit/token.js +2 -2
  26. package/dist/compiler/emit/views.d.ts +60 -0
  27. package/dist/compiler/emit/views.js +523 -0
  28. package/dist/compiler/idl.js +2 -1
  29. package/dist/compiler/model.d.ts +65 -4
  30. package/dist/compiler/model.js +14 -0
  31. package/dist/compiler/toolchain.d.ts +15 -0
  32. package/dist/compiler/toolchain.js +146 -11
  33. package/docs/architecture.md +9 -2
  34. package/docs/case-study-phoenix.md +226 -0
  35. package/docs/language.md +139 -8
  36. package/docs/migrate-from-anchor.md +1 -0
  37. package/docs/runtime.md +1 -1
  38. package/docs/stability.md +21 -2
  39. package/docs/troubleshooting.md +5 -2
  40. package/lib/typesol.d.ts +221 -4
  41. package/llms-full.txt +169 -14
  42. package/llms.txt +1 -1
  43. package/package.json +2 -2
  44. package/runtime/typesol_rt.h +407 -0
@@ -1,9 +1,9 @@
1
1
  import ts from "typescript";
2
2
  import { type AccountParam, type IdlSeed } from "../model.js";
3
- import { type Value, type CpiAcct } from "./shared.js";
4
- import { CallEmitter } from "./calls.js";
3
+ import { type Value, type Ref, type CpiAcct } from "./shared.js";
4
+ import { ViewEmitter } from "./views.js";
5
5
  /** Seeds and signer seeds, the byte buffers and Borsh serialization every CPI builds on, remaining-account ranges. */
6
- export declare abstract class CpiCoreEmitter extends CallEmitter {
6
+ export declare abstract class CpiCoreEmitter extends ViewEmitter {
7
7
  /**
8
8
  * Lower a seeds array literal into a `SolSignerSeed[]` with `extra` spare slots. Also describes
9
9
  * the seeds in Anchor IDL terms when every element is a constant, an argument or an account path.
@@ -81,4 +81,21 @@ export declare abstract class CpiCoreEmitter extends CallEmitter {
81
81
  protected nestedStructs(name: string): Set<string>;
82
82
  /** Structs whose IDL description is the fixed layout: account data, arguments, and everything nested in them. */
83
83
  protected fixedLayoutStructs(): Set<string>;
84
+ /**
85
+ * Byte builders on a `FixedVec<u8, N>` (a local list or one in account data), for a native program's hand-built byte
86
+ * strings (Phoenix's event batches: `[15] ‖ Borsh(header) ‖ events`, a u16 count patched in, truncated back to the
87
+ * header after each flush): `pushLE` (an integer at its width), `pushKey` (32 bytes), `pushBorsh` (a value's Borsh
88
+ * encoding, the codecs invoke, events and storeBorsh use), `setLE(offset, v)` (overwrite within the length) and
89
+ * `truncate(n)`. Every write is bounds-checked (5104) and the length moves only once all of it fit, so a failed call
90
+ * appends nothing.
91
+ */
92
+ protected byteListMethod(node: ts.CallExpression, method: string, v: Ref): Value | undefined;
93
+ /**
94
+ * `pushBorsh(value)`: lower the value now and return the writer of its Borsh bytes. Structs (a place, or an object
95
+ * literal given its type: `pushBorsh<Header>({ … })`) are their fixed layout when that is their Borsh form, else go
96
+ * through the struct's Borsh encoder (storeBorsh's); data enums are a tag and the variant's fields, FixedArrays their
97
+ * elements, lists a u32 count and their elements, and integers, booleans, Pubkeys, strings and Options as in invoke
98
+ * data.
99
+ */
100
+ private borshPiece;
84
101
  }
@@ -1,10 +1,11 @@
1
1
  import ts from "typescript";
2
- import { argIdlName, fieldIdlName, snakeCase } from "../analyze.js";
2
+ import { argIdlName, fieldIdlName, resolveScalarType, snakeCase } from "../analyze.js";
3
3
  import { INT_INFO, isScalar, scalarSize, typeName } from "../model.js";
4
- import { accountLimit, MAX_SEEDS, U64, isStable, cString, scalarStorageC, optC } from "./shared.js";
5
- import { CallEmitter } from "./calls.js";
4
+ import { accountLimit, MAX_SEEDS, PUBKEY, U64, isStable, cString, fieldC, scalarStorageC, optC, vecCount, } from "./shared.js";
5
+ import { borshIdentical, borshNativeStructUnsupported } from "./borsh.js";
6
+ import { ViewEmitter } from "./views.js";
6
7
  /** Seeds and signer seeds, the byte buffers and Borsh serialization every CPI builds on, remaining-account ranges. */
7
- export class CpiCoreEmitter extends CallEmitter {
8
+ export class CpiCoreEmitter extends ViewEmitter {
8
9
  /**
9
10
  * Lower a seeds array literal into a `SolSignerSeed[]` with `extra` spare slots. Also describes
10
11
  * the seeds in Anchor IDL terms when every element is a constant, an argument or an account path.
@@ -132,7 +133,7 @@ export class CpiCoreEmitter extends CallEmitter {
132
133
  const k = this.model.constants.get(el.text);
133
134
  if (k && typeof k.value === "string")
134
135
  return { kind: "const", value: [...Buffer.from(k.value, "utf8")] };
135
- if (k && typeof k.value === "object")
136
+ if (k && typeof k.value === "object" && k.value !== null)
136
137
  return { kind: "const", value: k.value.pubkey };
137
138
  if (k && typeof k.value === "bigint") {
138
139
  // Little-endian two's complement in the constant's width (16 bytes for u128/i128), as the program hashes it.
@@ -407,4 +408,224 @@ export class CpiCoreEmitter extends CallEmitter {
407
408
  visit({ kind: "struct", name });
408
409
  return out;
409
410
  }
411
+ /**
412
+ * Byte builders on a `FixedVec<u8, N>` (a local list or one in account data), for a native program's hand-built byte
413
+ * strings (Phoenix's event batches: `[15] ‖ Borsh(header) ‖ events`, a u16 count patched in, truncated back to the
414
+ * header after each flush): `pushLE` (an integer at its width), `pushKey` (32 bytes), `pushBorsh` (a value's Borsh
415
+ * encoding, the codecs invoke, events and storeBorsh use), `setLE(offset, v)` (overwrite within the length) and
416
+ * `truncate(n)`. Every write is bounds-checked (5104) and the length moves only once all of it fit, so a failed call
417
+ * appends nothing.
418
+ */
419
+ byteListMethod(node, method, v) {
420
+ const args = node.arguments;
421
+ const info = v.vec;
422
+ const vt = v.type;
423
+ if (info.cap === undefined || info.heap || info.big !== undefined || vt.elem.kind !== "int" || vt.elem.name !== "u8")
424
+ this.fail(node.expression, `${method}() builds bytes in a FixedVec<u8, N> (a local list, or one in account data)`);
425
+ if (!v.writable)
426
+ this.fail(node, this.readOnly(v));
427
+ const cap = info.cap;
428
+ const bytes = `((uint8_t *)${info.items})`;
429
+ const count = vecCount(info);
430
+ /** An integer at a width: the type argument's, or the value's own (a bare literal has none). */
431
+ const intValue = (valueNode, fn) => {
432
+ const targ = node.typeArguments?.[0];
433
+ const t = targ ? resolveScalarType(targ, this.scope) : undefined;
434
+ if (targ && (!t || t.kind !== "int"))
435
+ this.fail(targ, `${fn}<T>: T is an integer type (u8 … u128, i8 … i128)`);
436
+ const val = t ? this.expect(this.expr(valueNode, t), t, valueNode) : this.expr(valueNode);
437
+ if (val.literal !== undefined)
438
+ this.fail(valueNode, `${fn} needs the integer's width: ${fn}<u16>(…) or ${fn}(u16(…))`);
439
+ if (val.type.kind !== "int")
440
+ this.fail(valueNode, `${fn} takes an integer (u8 … u128, i8 … i128)${val.type.kind === "pubkey" ? "; a Pubkey is pushKey(key)" : ""}`);
441
+ if (val.type.name === "u256")
442
+ this.fail(valueNode, "u256 is for computation: convert to u128 (or smaller) first");
443
+ return val;
444
+ };
445
+ switch (method) {
446
+ case "truncate": {
447
+ // Vec::truncate, but a length past the current one fails (Rust's `drain(n..)` panics there) instead of doing nothing.
448
+ if (args.length !== 1)
449
+ this.fail(node, "truncate(length) takes the new length");
450
+ const k = this.expect(this.expr(args[0], U64), U64, args[0]);
451
+ const n = this.tmp("n");
452
+ this.line(`uint64_t ${n} = ${k.c};`);
453
+ this.line(`if (${n} > ${count}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: truncate() past the FixedVec's length");`);
454
+ this.line(`${info.len} = (uint32_t)${n};`);
455
+ return undefined;
456
+ }
457
+ case "setLE": {
458
+ // `data[off..off + size].copy_from_slice(&v.to_le_bytes())`: within the length, as Rust's slice indexing.
459
+ if (args.length !== 2)
460
+ this.fail(node, "setLE(offset, value) takes a byte offset and an integer");
461
+ const off = this.expect(this.expr(args[0], U64), U64, args[0]);
462
+ const o = this.tmp("off");
463
+ this.line(`uint64_t ${o} = ${off.c};`);
464
+ const val = intValue(args[1], "setLE");
465
+ const size = scalarSize(val.type);
466
+ const ct = scalarStorageC(val.type);
467
+ const w = this.tmp("le");
468
+ this.line(`${ct} ${w} = (${ct})(${val.c});`);
469
+ this.line(`if (${o} > ${count} || ${count} - ${o} < ${size}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: setLE() past the FixedVec's length");`);
470
+ this.line(`ts_memcpy(${bytes} + ${o}, &${w}, ${size});`);
471
+ return undefined;
472
+ }
473
+ }
474
+ if (args.length !== 1)
475
+ this.fail(node, `${method}(value) takes one value`);
476
+ const arg = args[0];
477
+ // The value first (as JS evaluates the argument before the call runs), then its bytes after the current length.
478
+ let write;
479
+ if (method === "pushLE") {
480
+ const val = intValue(arg, "pushLE");
481
+ const ct = scalarStorageC(val.type);
482
+ const w = this.tmp("le");
483
+ this.line(`${ct} ${w} = (${ct})(${val.c});`);
484
+ write = (put) => put(`&${w}`, String(scalarSize(val.type)));
485
+ }
486
+ else if (method === "pushKey") {
487
+ if (node.typeArguments?.length)
488
+ this.fail(node, "pushKey(key) takes no type argument");
489
+ const k = this.expect(this.expr(arg, PUBKEY), PUBKEY, arg);
490
+ const t = this.tmp("key");
491
+ this.line(`SolPubkey ${t} = *(${k.c});`);
492
+ write = (put) => put(`&${t}`, "32");
493
+ }
494
+ else
495
+ write = this.borshPiece(node, arg);
496
+ const at = this.tmp("at");
497
+ this.line(`uint64_t ${at} = ${count};`);
498
+ write((src, n) => {
499
+ this.line(`if (${n} > ${cap} - ${at}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: ${method}() past the FixedVec's room");`);
500
+ this.line(`ts_memcpy(${bytes} + ${at}, ${src}, ${n});`);
501
+ this.line(`${at} += ${n};`);
502
+ }, { dst: bytes, cap: String(cap), at });
503
+ this.line(`${info.len} = (uint32_t)${at};`);
504
+ return undefined;
505
+ }
506
+ /**
507
+ * `pushBorsh(value)`: lower the value now and return the writer of its Borsh bytes. Structs (a place, or an object
508
+ * literal given its type: `pushBorsh<Header>({ … })`) are their fixed layout when that is their Borsh form, else go
509
+ * through the struct's Borsh encoder (storeBorsh's); data enums are a tag and the variant's fields, FixedArrays their
510
+ * elements, lists a u32 count and their elements, and integers, booleans, Pubkeys, strings and Options as in invoke
511
+ * data.
512
+ */
513
+ borshPiece(node, arg) {
514
+ const targ = node.typeArguments?.[0];
515
+ let r;
516
+ if (ts.isObjectLiteralExpression(arg)) {
517
+ const name = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? targ.typeName.text : undefined;
518
+ const type = name && this.model.structs.get(name)?.size !== undefined
519
+ ? { kind: "struct", name }
520
+ : name && this.model.dataEnums.has(name)
521
+ ? { kind: "dataEnum", name }
522
+ : undefined;
523
+ if (!type)
524
+ this.fail(arg, "pushBorsh({ … }) needs the value's type: buf.pushBorsh<Header>({ … }) (a struct or data enum), or bind it to a typed const first");
525
+ // A data enum literal of a fixed-size variant: the tag and the variant's fields (packed, their Borsh form) in a
526
+ // temporary of exactly those bytes, then one room check and one copy. Not the whole enum zeroed, filled and
527
+ // copied, then written as a tag and a switch on it.
528
+ if (type.kind === "dataEnum") {
529
+ const lit = this.dataEnumLiteral(type.name, arg);
530
+ const size = 1 + lit.variant.fields.reduce((n, f) => n + this.fieldBytes(f.type), 0);
531
+ // Integers, booleans, enums and Pubkeys: each field's value in a local of its own (in source order), then one
532
+ // room check and a store of each at its offset, as pushLE would write them one by one.
533
+ if (lit.variant.fields.every((f) => isScalar(f.type))) {
534
+ const locals = new Map(lit.variant.fields.map((f) => [f.name, this.tmp("bf")]));
535
+ for (const f of lit.variant.fields)
536
+ this.line(`${fieldC(f.type)} ${locals.get(f.name)};`);
537
+ lit.writeFields((field) => locals.get(field));
538
+ return (_put, room) => {
539
+ this.line(`if (${size} > ${room.cap} - ${room.at}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: pushBorsh() past the FixedVec's room");`);
540
+ this.line(`${room.dst}[${room.at}] = ${lit.vi};`);
541
+ let off = 1;
542
+ for (const f of lit.variant.fields) {
543
+ const n = this.fieldBytes(f.type);
544
+ this.line(`ts_memcpy(${room.dst} + ${room.at} + ${off}, &${locals.get(f.name)}, ${n});`);
545
+ off += n;
546
+ }
547
+ this.line(`${room.at} += ${size};`);
548
+ };
549
+ }
550
+ if (lit.variant.fields.every((f) => borshIdentical(f.type, this.model))) {
551
+ const t = this.tmp("bv");
552
+ this.line(`struct __attribute__((packed)) { uint8_t tag; TSV_${lit.e.name}__${lit.variant.name} v; } ${t};`);
553
+ this.line(`${t}.tag = ${lit.vi};`);
554
+ lit.writeFields(`${t}.v`);
555
+ return (put) => put(`&${t}`, String(size));
556
+ }
557
+ }
558
+ const t = this.tmp("bv");
559
+ this.line(`${fieldC(type)} ${t};`);
560
+ if (type.kind === "struct")
561
+ this.line(`ts_memzero(&${t}, sizeof(${t}));`);
562
+ this.writeAggregate({ lv: t, type, writable: true }, arg, true);
563
+ r = { lv: t, type, writable: true };
564
+ }
565
+ else if (targ)
566
+ this.fail(targ, "pushBorsh<T> takes a type only for an object literal; the value's own type is used otherwise");
567
+ const kind = r?.type.kind ?? this.peekKind(arg);
568
+ if (kind === "struct" || kind === "array" || kind === "dataEnum") {
569
+ r ??= this.ref(arg);
570
+ const place = r;
571
+ if (place.type.kind === "dataEnum") {
572
+ const name = place.type.name;
573
+ const e = this.model.dataEnums.get(name);
574
+ // Fixed-size payloads are packed in the variant's C struct as Borsh lays them out: the tag, then one copy.
575
+ if (e.variants.every((v) => v.fields.every((f) => borshIdentical(f.type, this.model))))
576
+ return (put) => {
577
+ put(`&${place.lv}.tag`, "1");
578
+ if (e.variants.every((v) => !v.fields.length))
579
+ return;
580
+ this.line(`switch (${place.lv}.tag) {`);
581
+ e.variants.forEach((v, i) => {
582
+ const size = v.fields.reduce((n, f) => n + this.fieldBytes(f.type), 0);
583
+ if (!size)
584
+ return;
585
+ this.line(`case ${i}: {`);
586
+ put(`&${place.lv}.v.${v.name}`, String(size));
587
+ this.line(`break; }`);
588
+ });
589
+ this.line(`}`);
590
+ };
591
+ return (put) => this.serializeDataEnumLv(place.lv, name, (src, n) => put(src, n));
592
+ }
593
+ if (borshIdentical(place.type, this.model)) {
594
+ const n = this.fieldBytes(place.type);
595
+ return (put) => put(`&${place.lv}`, String(n));
596
+ }
597
+ if (place.type.kind === "array")
598
+ this.fail(arg, `${typeName(place.type)} has no Borsh form of its own here (its elements hold Options, data enums or text)`);
599
+ const s = this.model.structs.get(place.type.name);
600
+ const why = borshNativeStructUnsupported(s, this.model);
601
+ if (why)
602
+ this.fail(arg, `pushBorsh cannot encode ${s.name}: ${why}`);
603
+ this.model.borshNative.add(s.name);
604
+ return (_put, room) => {
605
+ // The encoder writes into the room left and reports how much it wrote; the length moves only afterwards.
606
+ const w = this.tmp("bw");
607
+ this.line(`uint64_t ${w} = 0;`);
608
+ this.line(`if (ts_benc_${s.name}(&${place.lv}, ${room.dst} + ${room.at}, ${room.cap} - ${room.at}, &${w})) TS_FAIL(TS_ERR_INDEX, "TypeSOL: pushBorsh() past the FixedVec's room");`);
609
+ this.line(`${room.at} += ${w};`);
610
+ };
611
+ }
612
+ const list = kind === "vec" ? this.listSpan(arg) : undefined;
613
+ if (list) {
614
+ // A Borsh Vec: the count as u32, then the elements (their fixed layout is their Borsh form).
615
+ if (!borshIdentical(list.elem, this.model))
616
+ this.fail(arg, `a list of ${typeName(list.elem)} has no Borsh form of its own here`);
617
+ const size = this.fieldBytes(list.elem);
618
+ const c = this.tmp("vn");
619
+ this.line(`uint32_t ${c} = (uint32_t)${list.count};`);
620
+ return (put) => {
621
+ put(`&${c}`, "4");
622
+ put(`(const uint8_t *)${list.items}`, `(uint64_t)${c} * ${size}`);
623
+ };
624
+ }
625
+ const val = this.expr(arg);
626
+ if (val.literal !== undefined)
627
+ this.fail(arg, "pushBorsh needs the integer's width: pushLE<u16>(…), pushBorsh(u16(…))");
628
+ // serialize() emits its temporaries between the pieces; collect them and replay into the writer.
629
+ return (put) => this.serialize(val, arg, (src, n) => put(src, n));
630
+ }
410
631
  }
@@ -235,6 +235,7 @@ export class CpiEmitter extends MetaplexEmitter {
235
235
  this.line(`for (uint64_t ${i}b = ${base} + ${range.from}; ${i}b < ${base} + ${range.to}; ${i}b++) ts_info(params->ka[${i}b], &params->infos[${k}++]);`);
236
236
  const ixName = this.tmp("cpi");
237
237
  this.line(`SolInstruction ${ixName} = {&${programKey}, ${m}, ${n}, (uint8_t *)${data.items}, ${data.count}};`);
238
+ this.forgetOwners();
238
239
  if (multi)
239
240
  this.line(`TS_TRY(sol_invoke_signed(&${ixName}, params->infos, ${k}, ${multi.ptr}, ${multi.count}));`);
240
241
  else if (seeds) {
@@ -325,8 +326,13 @@ export class CpiEmitter extends MetaplexEmitter {
325
326
  const ft = f.type;
326
327
  const t = this.tmp("evv");
327
328
  this.line(`${fixedVecC(ft)} ${t};`);
328
- this.line(`ts_memzero(&${t}, sizeof(${t}));`);
329
- this.writeAggregate({ lv: t, type: ft, writable: true }, e);
329
+ // A literal is built in place, its free slots zeroed; anything else may fill only the first ones.
330
+ if (this.isListLiteral(e))
331
+ this.writeAggregate({ lv: t, type: ft, writable: true }, e, true);
332
+ else {
333
+ this.line(`ts_memzero_bulk(&${t}, sizeof(${t}));`);
334
+ this.writeAggregate({ lv: t, type: ft, writable: true }, e);
335
+ }
330
336
  const n = this.fieldBytes(ft);
331
337
  return (put) => put(`&${t}`, String(n), n);
332
338
  }
@@ -260,8 +260,10 @@ export class ExpressionEmitter extends StorageEmitter {
260
260
  this.fail(node, `"${node.text}" is a function: call it (${node.text}(…)), bind it with const, or pass it to a helper or list method; it cannot be stored or returned as a value`);
261
261
  if (l.type.kind === "array")
262
262
  this.fail(node, `"${node.text}" is an array; use .get(i)`);
263
- if (l.type.kind === "vec")
263
+ if (l.type.kind === "vec" || l.type.kind === "rawArray")
264
264
  this.fail(node, `"${node.text}" is a list; use .get(i) and .length`);
265
+ if (l.type.kind === "rbTree")
266
+ this.fail(node, `"${node.text}" is a RedBlackTree; use its methods (get, insert, remove, min, max, for … of)`);
265
267
  if (l.type.kind === "remaining")
266
268
  return { c: l.c, type: l.type };
267
269
  return l.type.kind === "pubkey" && !l.ptr ? { c: `(&${l.c})`, type: l.type } : { c: l.c, type: l.type };
@@ -270,6 +272,8 @@ export class ExpressionEmitter extends StorageEmitter {
270
272
  if (k) {
271
273
  if (typeof k.value === "boolean")
272
274
  return { c: k.value ? "true" : "false", type: BOOL };
275
+ if (k.value === null)
276
+ this.fail(node, `${k.name} = null only tells failures to log nothing; it is not a value`);
273
277
  if (typeof k.value === "object")
274
278
  return { c: `(&TSK_${k.name})`, type: PUBKEY };
275
279
  if (typeof k.value === "string") {
@@ -350,6 +354,9 @@ export class ExpressionEmitter extends StorageEmitter {
350
354
  }
351
355
  property(node) {
352
356
  const field = node.name.text;
357
+ const view = this.viewProperty(node);
358
+ if (view)
359
+ return view;
353
360
  // A BigVec's room: the elements the account holds past the struct.
354
361
  if (field === "capacity" && this.peekKind(node.expression) === "vec") {
355
362
  const r = this.ref(node.expression);
@@ -690,7 +697,7 @@ export class ExpressionEmitter extends StorageEmitter {
690
697
  const k = this.model.constants.get(e.text);
691
698
  if (k && typeof k.value === "string")
692
699
  return k.value;
693
- if (k && typeof k.value === "object")
700
+ if (k && typeof k.value === "object" && k.value !== null)
694
701
  return base58(Uint8Array.from(k.value.pubkey));
695
702
  }
696
703
  return undefined;
@@ -954,6 +961,11 @@ export class ExpressionEmitter extends StorageEmitter {
954
961
  // An Option<Vec<T>> argument: None leaves its view's pointer NULL (a Some, empty or not, points into the data).
955
962
  if (v.type.kind === "vecArg" && v.type.optional)
956
963
  return { c: `((${v.c}).ptr ${neg ? "!=" : "=="} NULL)`, type: BOOL };
964
+ // A RedBlackTree's get / remove of a struct value (a reference, NULL when absent) and its min / max node.
965
+ if (v.type.kind === "structRef" && v.type.nullable)
966
+ return { c: `(${v.c} ${neg ? "!=" : "=="} NULL)`, type: BOOL };
967
+ if (v.type.kind === "rbEntry")
968
+ return { c: `((${v.c}).index ${neg ? "!=" : "=="} 0)`, type: BOOL };
957
969
  if (v.type.kind !== "option" && v.type.kind !== "optionArg")
958
970
  this.fail(other, "only Option values can be compared with null");
959
971
  return { c: neg ? `((${v.c}).some != 0)` : `((${v.c}).some == 0)`, type: BOOL };
@@ -1066,9 +1078,24 @@ export class ExpressionEmitter extends StorageEmitter {
1066
1078
  const t = this.tmp();
1067
1079
  const K = ts.SyntaxKind;
1068
1080
  this.line(`${ct} ${t};`);
1069
- const overflow = `TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: arithmetic overflow")`;
1081
+ const failOverflow = `TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: arithmetic overflow")`;
1070
1082
  if (type.name === "u256")
1071
- return this.arith256(op, left, right, node, t, overflow);
1083
+ return this.arith256(op, left, right, node, t, failOverflow);
1084
+ // Inside panicsAt(location, …): Rust's panic, with the message its overflow checks give this operator.
1085
+ const at = this.panicAt;
1086
+ const rust = (message) => `{ ${this.panicC(message, at).join(" ")} }`;
1087
+ const negate = ts.isPrefixUnaryExpression(node) && node.operator === K.MinusToken;
1088
+ const rustOverflow = {
1089
+ [K.PlusToken]: "attempt to add with overflow",
1090
+ [K.MinusToken]: negate ? "attempt to negate with overflow" : "attempt to subtract with overflow",
1091
+ [K.AsteriskToken]: "attempt to multiply with overflow",
1092
+ [K.SlashToken]: "attempt to divide with overflow",
1093
+ [K.PercentToken]: "attempt to calculate the remainder with overflow",
1094
+ };
1095
+ const overflow = at && rustOverflow[op] ? rust(rustOverflow[op]) : failOverflow;
1096
+ const divZero = at && (op === K.SlashToken || op === K.PercentToken)
1097
+ ? rust(op === K.SlashToken ? "attempt to divide by zero" : "attempt to calculate the remainder with a divisor of zero")
1098
+ : `TS_FAIL(TS_ERR_DIV_ZERO, "TypeSOL: division by zero")`;
1072
1099
  switch (op) {
1073
1100
  case K.PlusToken:
1074
1101
  // u64 through the runtime helpers: one compare instead of a materialized carry flag on SBF.
@@ -1084,7 +1111,7 @@ export class ExpressionEmitter extends StorageEmitter {
1084
1111
  break;
1085
1112
  case K.SlashToken:
1086
1113
  case K.PercentToken: {
1087
- this.line(`if (${right.c} == 0) TS_FAIL(TS_ERR_DIV_ZERO, "TypeSOL: division by zero");`);
1114
+ this.line(`if (${right.c} == 0) ${divZero};`);
1088
1115
  if (INT_INFO[type.name].signed)
1089
1116
  this.line(`if (${left.c} == ${intLiteral(INT_INFO[type.name].min, type.name)} && ${right.c} == -1) ${overflow};`);
1090
1117
  if (type.name === "u128")
@@ -1107,13 +1134,17 @@ export class ExpressionEmitter extends StorageEmitter {
1107
1134
  const bits = INT_INFO[type.name].bytes * 8;
1108
1135
  const sh = this.tmp("sh");
1109
1136
  const rinfo = INT_INFO[right.type.name];
1110
- this.line(`if (${rinfo.signed ? `${right.c} < 0 || ` : ""}${right.c} >= ${bits}) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: shift amount out of range");`);
1137
+ // Rust's shift check is the amount only; the bits `<<` loses below stay TypeSOL's failure (JS's bigint keeps them).
1138
+ const range = at !== undefined
1139
+ ? rust(op === K.LessThanLessThanToken ? "attempt to shift left with overflow" : "attempt to shift right with overflow")
1140
+ : `TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: shift amount out of range")`;
1141
+ this.line(`if (${rinfo.signed ? `${right.c} < 0 || ` : ""}${right.c} >= ${bits}) ${range};`);
1111
1142
  this.line(`uint64_t ${sh} = (uint64_t)(${right.c});`);
1112
1143
  if (op === K.GreaterThanGreaterThanToken)
1113
1144
  this.line(`${t} = (${ct})(${left.c} >> ${sh});`);
1114
1145
  else {
1115
1146
  this.line(`${t} = (${ct})((${unsignedC(type.name)})${left.c} << ${sh});`);
1116
- this.line(`if ((${ct})(${t} >> ${sh}) != ${left.c}) ${overflow};`);
1147
+ this.line(`if ((${ct})(${t} >> ${sh}) != ${left.c}) ${failOverflow};`);
1117
1148
  }
1118
1149
  break;
1119
1150
  }
@@ -1,12 +1,15 @@
1
+ import ts from "typescript";
1
2
  import { accountLimit, cBytes, scalarStorageC, optC, storageDecl, helperSignature, fieldC, fixedVecC, laterVecC } from "./shared.js";
2
3
  import { FunctionEmitter } from "./function.js";
3
4
  import { emitBorshCodecs, emitNativeBorshCodecs } from "./borsh.js";
5
+ import { emitRbTrees } from "./rbtree.js";
4
6
  /**
5
7
  * The whole C translation unit: type declarations (structs, options, enums, events), every helper and instruction
6
8
  * (lowered by FunctionEmitter), and the entry point that dispatches on the instruction discriminator.
7
9
  */
8
10
  export function emitProgram(analysis, opts = {}) {
9
11
  const { model, reporter } = analysis;
12
+ model.ownerCache = makesNativeViews(model);
10
13
  // Bodies first: they register events, string-literal errors and PDA descriptions.
11
14
  const helperBodies = [];
12
15
  const emittedHelpers = new Set();
@@ -56,11 +59,26 @@ export function emitProgram(analysis, opts = {}) {
56
59
  else if (panicFlag.value)
57
60
  out.push(`#define TS_PANIC_ON_OVERFLOW 1`);
58
61
  }
62
+ // `const PANIC_STYLE = "solana-1.14"`: panics log as solana_program 1.14's panic handler does and abort (read by the
63
+ // emitter); PANIC_ON_OVERFLOW's panics abort too instead of calling sol_panic_.
64
+ const panicStyle = model.constants.get("PANIC_STYLE");
65
+ if (panicStyle) {
66
+ if (panicStyle.value !== "solana-1.14")
67
+ reporter.error(analysis.sourceFile, "PANIC_STYLE must be \"solana-1.14\" (panics log `panicked at '<message>', <file>:<line>:<col>` and abort, as programs built with solana-program 1.14 to 1.17 do); leave it out for the default");
68
+ else if (panicFlag?.value === true)
69
+ out.push(`#define TS_PANIC_ABORT 1`);
70
+ }
59
71
  // `const NATIVE_ACCOUNT_WRITES = true`: loadRawMut / storeBorsh / BigVec writes leave writability and aliasing to the
60
72
  // runtime, as a native program does (read by the emitter; nothing to define in C).
61
73
  const nativeWrites = model.constants.get("NATIVE_ACCOUNT_WRITES");
62
74
  if (nativeWrites && typeof nativeWrites.value !== "boolean")
63
75
  reporter.error(analysis.sourceFile, "NATIVE_ACCOUNT_WRITES must be true or false");
76
+ // resizeAccount on a remaining account: the entrypoint records every account's size when the instruction starts.
77
+ if ([...helperBodies, ...ixBodies].some((b) => b.includes("ts_entry_len(")))
78
+ out.push(`#define TS_RECORD_ENTRY_LEN 1`);
79
+ // Native account views share one owner-check cache (ts_owned), zeroed in the entry point.
80
+ if (model.ownerCache)
81
+ out.push(`#define TS_OWNER_CACHE 1`);
64
82
  // An error with code 0 must not return 0 (success): see ts_fail.
65
83
  if ([...model.errorEnums.values()].some((m) => [...m.values()].some((e) => e.code === 0)))
66
84
  out.push(`#define TS_CUSTOM_ZERO 1`);
@@ -167,7 +185,7 @@ export function emitProgram(analysis, opts = {}) {
167
185
  for (const t of model.localVecs.values())
168
186
  deps(t);
169
187
  for (const k of model.constants.values())
170
- if (typeof k.value === "object")
188
+ if (typeof k.value === "object" && k.value !== null)
171
189
  out.push(`static const SolPubkey TSK_${k.name} = {${cBytes(k.value.pubkey)}};`);
172
190
  out.push(...emitBorshCodecs(model), ...emitNativeBorshCodecs(model));
173
191
  const helpers = [...model.helpers.values()];
@@ -175,6 +193,8 @@ export function emitProgram(analysis, opts = {}) {
175
193
  out.push(helperSignature(h) + ";");
176
194
  if (helpers.length)
177
195
  out.push("");
196
+ // RedBlackTree instances: after the helper prototypes (a comparator is a helper), before the code that uses them.
197
+ out.push(...emitRbTrees(model));
178
198
  out.push(...helperBodies, ...ixBodies);
179
199
  const limit = accountLimit(model);
180
200
  out.push(`_Static_assert(TS_MAX_ACCOUNTS == ${limit}, "TS_MAX_ACCOUNTS");`);
@@ -188,6 +208,8 @@ export function emitProgram(analysis, opts = {}) {
188
208
  // Above 32 accounts the CPI scratch lists are taken from the heap when first needed.
189
209
  if (limit > 32)
190
210
  out.push(` params.infos_cap = 0;`, ` params.metas = NULL;`);
211
+ if (model.ownerCache)
212
+ out.push(` params.owned = NULL;`);
191
213
  if ([...helperBodies, ...ixBodies].some((b) => /ts_claim_mut(_at)?(_rec)?\(/.test(b)))
192
214
  out.push(limit > 64 ? ` ts_memzero(params.loaded_mut, sizeof(params.loaded_mut));` : ` params.loaded_mut = 0;`);
193
215
  const fallback = model.instructions.find((ix) => ix.fallback);
@@ -216,3 +238,10 @@ export function emitProgram(analysis, opts = {}) {
216
238
  out.push(`}`);
217
239
  return out.join("\n") + "\n";
218
240
  }
241
+ /** The views whose owner checks share the cache (see ProgramModel.ownerCache). */
242
+ const NATIVE_VIEWS = new Set(["loadRaw", "loadRawMut", "loadRawAt", "loadRawMutAt", "rawArrayAt", "rawArrayMutAt", "rbTreeAt", "rbTreeMutAt"]);
243
+ /** Whether any function of the program calls one of the native views (by name: a false positive only costs a store). */
244
+ function makesNativeViews(model) {
245
+ const calls = (n) => (ts.isCallExpression(n) && ts.isIdentifier(n.expression) && NATIVE_VIEWS.has(n.expression.text)) || !!ts.forEachChild(n, calls);
246
+ return [...model.instructions, ...model.helpers.values(), ...model.generics.values()].some((f) => calls(f.node));
247
+ }
@@ -0,0 +1,7 @@
1
+ import { type ProgramModel } from "../model.js";
2
+ /**
3
+ * The C functions of each RedBlackTree instance (`rbTreeAt<K, V>(…, compare?)`): its key order, and lib-sokoban 0.3's
4
+ * get_addr, _insert and _remove over runtime/typesol_rt.h's structural functions (ts_rbt_*), with the node stride a
5
+ * constant. Each returns SUCCESS or the error a comparator helper failed with; results go through `out`.
6
+ */
7
+ export declare function emitRbTrees(model: ProgramModel): string[];
@@ -0,0 +1,142 @@
1
+ import { fieldC, scalarC } from "./shared.js";
2
+ /**
3
+ * The C functions of each RedBlackTree instance (`rbTreeAt<K, V>(…, compare?)`): its key order, and lib-sokoban 0.3's
4
+ * get_addr, _insert and _remove over runtime/typesol_rt.h's structural functions (ts_rbt_*), with the node stride a
5
+ * constant. Each returns SUCCESS or the error a comparator helper failed with; results go through `out`.
6
+ */
7
+ export function emitRbTrees(model) {
8
+ const out = [];
9
+ for (const t of model.rbTrees.values())
10
+ out.push(...emitTree(model, t));
11
+ return out;
12
+ }
13
+ function emitTree(model, t) {
14
+ const K = fieldC(t.keyType);
15
+ const V = fieldC(t.valueType);
16
+ const S = t.stride;
17
+ const ks = t.keySize;
18
+ const vs = t.valueSize;
19
+ const p = t.c;
20
+ const cmp = t.compare ? helperCompare(t) : defaultCompare(model, t.keyType);
21
+ return [
22
+ `/* RedBlackTree<${t.key.split("|").slice(0, 2).join(", ")}>: lib-sokoban 0.3, stride ${S}${t.compare ? `, ordered by ${t.compare.display}` : ""} */`,
23
+ `static inline __attribute__((always_inline)) uint64_t ${p}_cmp(TsParams *params, const ${K} *a, const ${K} *b, int *out) {`,
24
+ ` (void)params;`,
25
+ ...cmp.map((l) => ` ${l}`),
26
+ `}`,
27
+ `/* get_addr: the node holding \`key\`, or 0. */`,
28
+ `static __attribute__((noinline, unused)) uint64_t ${p}_find(TsParams *params, const TsRbt *t, const ${K} *key, uint32_t *out) {`,
29
+ ` uint32_t i = TS_RBT_ROOT(t->base);`,
30
+ ` while (i != 0) {`,
31
+ ` int c;`,
32
+ ` TS_TRY(${p}_cmp(params, key, (const ${K} *)(ts_rbt_node(t, ${S}, i) + 16), &c));`,
33
+ ` if (c == 0) break;`,
34
+ ` i = ts_rbt_reg(t, ${S}, i, c < 0 ? TS_RBT_LEFT : TS_RBT_RIGHT);`,
35
+ ` }`,
36
+ ` *out = i;`,
37
+ ` return SUCCESS;`,
38
+ `}`,
39
+ `/* _insert: the node now holding \`key\` (an equal key keeps its node and takes the value), or 0 when a new key finds the tree full. */`,
40
+ `static __attribute__((noinline, unused)) uint64_t ${p}_insert(TsParams *params, const TsRbt *t, const ${K} *key, const ${V} *value, uint32_t *out) {`,
41
+ ` uint32_t parent = TS_RBT_ROOT(t->base);`,
42
+ ` if (parent == 0) {`,
43
+ ` uint32_t i = ts_rbt_add_node(t, ${S}, key, ${ks}, value, ${vs});`,
44
+ ` TS_RBT_ROOT(t->base) = i;`,
45
+ ` *out = i;`,
46
+ ` return SUCCESS;`,
47
+ ` }`,
48
+ ` for (;;) {`,
49
+ ` int c;`,
50
+ ` TS_TRY(${p}_cmp(params, key, (const ${K} *)(ts_rbt_node(t, ${S}, parent) + 16), &c));`,
51
+ ` if (c == 0) {`,
52
+ ` ts_memcpy(ts_rbt_node(t, ${S}, parent) + ${16 + ks}, value, ${vs});`,
53
+ ` *out = parent;`,
54
+ ` return SUCCESS;`,
55
+ ` }`,
56
+ ` uint32_t dir = c < 0 ? TS_RBT_LEFT : TS_RBT_RIGHT;`,
57
+ ` uint32_t target = ts_rbt_reg(t, ${S}, parent, dir);`,
58
+ ` if (target == 0) {`,
59
+ ` if (TS_RBT_SIZE(t->base) >= t->cap) {`,
60
+ ` *out = 0;`,
61
+ ` return SUCCESS;`,
62
+ ` }`,
63
+ ` uint32_t i = ts_rbt_add_node(t, ${S}, key, ${ks}, value, ${vs});`,
64
+ ` ts_rbt_link_leaf(t, ${S}, parent, i, dir);`,
65
+ ` *out = i;`,
66
+ ` return SUCCESS;`,
67
+ ` }`,
68
+ ` parent = target;`,
69
+ ` }`,
70
+ `}`,
71
+ `/* _remove: the node that held \`key\` (now free, its key and value bytes as they were), or 0. */`,
72
+ `static __attribute__((noinline, unused)) uint64_t ${p}_remove(TsParams *params, const TsRbt *t, const ${K} *key, uint32_t *out) {`,
73
+ ` uint32_t i;`,
74
+ ` TS_TRY(${p}_find(params, t, key, &i));`,
75
+ ` if (i != 0) ts_rbt_remove_node(t, ${S}, i);`,
76
+ ` *out = i;`,
77
+ ` return SUCCESS;`,
78
+ `}`,
79
+ `/* removeAt: node \`i\` unlinked and freed as _remove frees the node it finds; 0 (nothing written) for index 0 or a node`,
80
+ ` in no tree (not the root, no parent: a freed or never used one). Past the capacity panics as get_node does. */`,
81
+ `static __attribute__((noinline, unused)) uint32_t ${p}_remove_at(const TsRbt *t, uint32_t i) {`,
82
+ ` if (i == 0 || (TS_RBT_ROOT(t->base) != i && ts_rbt_reg(t, ${S}, i, TS_RBT_PARENT) == 0)) return 0;`,
83
+ ` ts_rbt_remove_node(t, ${S}, i);`,
84
+ ` return i;`,
85
+ `}`,
86
+ ``,
87
+ ];
88
+ }
89
+ /** A comparator helper `(a: K, b: K) => int`: called as compare(searched, nodeKey), its sign the order. */
90
+ function helperCompare(t) {
91
+ const h = t.compare;
92
+ const arg = (side) => {
93
+ const pt = h.params[0].type;
94
+ if (pt.kind === "structRef")
95
+ return `(TSS_${pt.struct} *)${side}`;
96
+ if (pt.kind === "pubkey")
97
+ return `*${side}`;
98
+ if (pt.kind === "bool")
99
+ return `(*${side} != 0)`;
100
+ return `*${side}`;
101
+ };
102
+ const ret = h.returns;
103
+ return [
104
+ `${scalarC(ret)} r;`,
105
+ `TS_TRY(fn_${h.name}(params, ${arg("a")}, ${arg("b")}, &r));`,
106
+ // Signed: an unsigned result is refused where the tree is made (views.ts), as it could never say "less".
107
+ `*out = r < 0 ? -1 : r > 0 ? 1 : 0;`,
108
+ `return SUCCESS;`,
109
+ ];
110
+ }
111
+ /** The default order: Rust's derived Ord, field by field in declaration order (integers by value, Pubkeys bytewise). */
112
+ function defaultCompare(model, key) {
113
+ const lines = [];
114
+ let n = 0;
115
+ const walk = (t, a, b) => {
116
+ switch (t.kind) {
117
+ case "int":
118
+ case "bool":
119
+ case "enum":
120
+ lines.push(`if (${a} != ${b}) {`, ` *out = ${a} < ${b} ? -1 : 1;`, ` return SUCCESS;`, `}`);
121
+ return;
122
+ case "pubkey": {
123
+ const c = `k${n++}`;
124
+ lines.push(`int64_t ${c} = ts_key_cmp(&${a}, &${b});`, `if (${c} != 0) {`, ` *out = (int)${c};`, ` return SUCCESS;`, `}`);
125
+ return;
126
+ }
127
+ case "struct":
128
+ for (const f of model.structs.get(t.name).fields)
129
+ walk(f.type, `${a}.${f.name}`, `${b}.${f.name}`);
130
+ return;
131
+ case "array":
132
+ for (let i = 0; i < t.len; i++)
133
+ walk(t.elem, `${a}[${i}]`, `${b}[${i}]`);
134
+ return;
135
+ default:
136
+ throw new Error(`unreachable: no default order for ${t.kind}`);
137
+ }
138
+ };
139
+ walk(key, "(*a)", "(*b)");
140
+ lines.push(`*out = 0;`, `return SUCCESS;`);
141
+ return lines;
142
+ }