@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
@@ -136,13 +136,16 @@ export class StorageEmitter extends AliasEmitter {
136
136
  }
137
137
  /**
138
138
  * A local list lives in the function's stack frame (4 KiB on SBPF v0, shared with every other local and the helpers
139
- * clang inlines): one list may take at most 2 KiB, so the failure is a clear compile error, not clang's frame error.
139
+ * clang inlines): one list's elements may take at most 2 KiB, so the failure is a clear compile error, not clang's
140
+ * frame error. A FixedVec's u32 length is not counted: `FixedVec<u32, 512>` (2,052 bytes) is 2 KiB of elements, and
141
+ * a frame that then overflows is reported by the frame check, which names the biggest locals.
140
142
  */
141
- checkLocalListSize(t, at, what = typeName(t)) {
143
+ checkLocalListSize(t, at, what = typeName(t), declared = false) {
142
144
  const bytes = this.fieldBytes(t);
145
+ const elements = t.kind === "vec" ? bytes - 4 : bytes;
143
146
  const smaller = t.kind === "vec" ? "FixedVec<T, N>" : "FixedArray<T, N>";
144
- if (bytes > 2048)
145
- this.fail(at, `${what} takes ${bytes} bytes; locals live on the 4 KiB stack, so keep it under 2 KiB (a smaller ${smaller})`);
147
+ if (elements > 2048)
148
+ this.fail(at, `${what} takes ${bytes} bytes; locals live on the 4 KiB stack, so keep it under 2 KiB of elements (${elements} here: a smaller ${smaller}${declared ? ", or /** @heap */ on the declaration to keep it on the heap" : ""})`);
146
149
  }
147
150
  /**
148
151
  * `FixedVec<T, N>` / `FixedArray<T, N>` written as a local's type: T an integer, boolean, Pubkey, enum,
@@ -220,6 +223,10 @@ export class StorageEmitter extends AliasEmitter {
220
223
  ref(node) {
221
224
  if (ts.isParenthesizedExpression(node))
222
225
  return this.ref(node.expression);
226
+ // A RawArray, a tree node's key / value, a narrowed tree result (views.ts).
227
+ const view = this.viewRef(node);
228
+ if (view)
229
+ return view;
223
230
  const unbanged = this.withoutBang(node);
224
231
  if (unbanged)
225
232
  return this.ref(unbanged);
@@ -437,6 +444,12 @@ export class StorageEmitter extends AliasEmitter {
437
444
  return `"${r.account.name}" is read-only; declare it Mut<...>`;
438
445
  if (r.lv.startsWith("(*arg_") || r.lv.startsWith("arg_"))
439
446
  return "instruction arguments are read-only; copy the value into a local first";
447
+ // An element of a Vec argument (or of a helper's Vec parameter): a view into the instruction data.
448
+ if (/^\(\([\w ]+\*\)(arg|p)_\w+\.ptr\)\[/.test(r.lv))
449
+ return "Vec arguments are read-only (a view of the instruction data); copy the element into a local first";
450
+ const param = /^\(\*p_(\w+)\)/.exec(r.lv)?.[1];
451
+ if (param && this.helper?.params.some((p) => p.name === param && !p.inout))
452
+ return `helper parameters are read-only: declare ${param} as Inout<T> to change the caller's value in place, or copy it into a local first`;
440
453
  return "this is read-only: it was loaded with loadAccount() (use loadAccountMut()) or comes from a read-only account";
441
454
  }
442
455
  /** Lower call arguments left to right, settling earlier ones when a later one runs statements. */
@@ -556,6 +569,49 @@ export class StorageEmitter extends AliasEmitter {
556
569
  this.assertUsable(a, node);
557
570
  return { lv: `(*d_${a.name})`, type: { kind: "struct", name: a.kind.struct.name }, writable: false };
558
571
  }
572
+ /**
573
+ * A data enum literal (`{ kind: "Variant", … }`), checked: its variant, and `writeFields(base)`, which evaluates the
574
+ * fields in source order (as JS does) into `${base}.<field>`, a `TSV_<Enum>__<Variant>` place (or, given a function,
575
+ * into the place it names for each field).
576
+ */
577
+ dataEnumLiteral(name, valueNode) {
578
+ const e = this.model.dataEnums.get(name);
579
+ const kindProp = valueNode.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "kind");
580
+ if (!kindProp)
581
+ this.fail(valueNode, `a ${e.name} literal needs kind: "Variant"`);
582
+ const vi = this.variantIndex(e.name, kindProp.initializer);
583
+ const variant = e.variants[vi];
584
+ const given = new Map();
585
+ for (const p of valueNode.properties) {
586
+ if (p === kindProp)
587
+ continue;
588
+ if (ts.isPropertyAssignment(p) && ts.isIdentifier(p.name))
589
+ given.set(p.name.text, p.initializer);
590
+ else if (ts.isShorthandPropertyAssignment(p))
591
+ given.set(p.name.text, p.name);
592
+ else
593
+ this.fail(p, "use plain `field: value` entries");
594
+ }
595
+ for (const k of given.keys())
596
+ if (!variant.fields.some((f) => f.name === k))
597
+ this.fail(valueNode, `${e.name}.${variant.name} has no field "${k}"`);
598
+ const writeFields = (base) => {
599
+ for (const f of variant.fields)
600
+ if (!given.has(f.name))
601
+ this.fail(valueNode, `missing field "${f.name}" of ${e.name}.${variant.name}`);
602
+ for (const [name, ex] of given) {
603
+ const f = variant.fields.find((x) => x.name === name);
604
+ const sub = { lv: typeof base === "string" ? `${base}.${f.name}` : base(f.name), type: f.type, writable: true };
605
+ const vt = this.storageValueType(f.type);
606
+ // A string kept in a variable enum holds its own copy of account text (the account may change later).
607
+ if (vt)
608
+ this.line(this.writeStorage(sub, this.ownedString(this.expect(this.expr(ex, vt), vt, ex)).c) + ";");
609
+ else
610
+ this.writeAggregate(sub, ex);
611
+ }
612
+ };
613
+ return { e, vi, variant, writeFields };
614
+ }
559
615
  /**
560
616
  * Write an aggregate value into `target`. `fresh`: the target is a value just declared (or a temporary), which no
561
617
  * expression can read yet, so a literal is built in it directly rather than in a temporary first.
@@ -592,45 +648,14 @@ export class StorageEmitter extends AliasEmitter {
592
648
  return;
593
649
  }
594
650
  if (target.type.kind === "dataEnum" && ts.isObjectLiteralExpression(valueNode)) {
595
- const e = this.model.dataEnums.get(target.type.name);
596
- const kindProp = valueNode.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "kind");
597
- if (!kindProp)
598
- this.fail(valueNode, `a ${e.name} literal needs kind: "Variant"`);
599
- const vi = this.variantIndex(e.name, kindProp.initializer);
600
- const variant = e.variants[vi];
601
- const given = new Map();
602
- for (const p of valueNode.properties) {
603
- if (p === kindProp)
604
- continue;
605
- if (ts.isPropertyAssignment(p) && ts.isIdentifier(p.name))
606
- given.set(p.name.text, p.initializer);
607
- else if (ts.isShorthandPropertyAssignment(p))
608
- given.set(p.name.text, p.name);
609
- else
610
- this.fail(p, "use plain `field: value` entries");
611
- }
612
- for (const k of given.keys())
613
- if (!variant.fields.some((f) => f.name === k))
614
- this.fail(valueNode, `${e.name}.${variant.name} has no field "${k}"`);
651
+ const lit = this.dataEnumLiteral(target.type.name, valueNode);
652
+ const { e, vi, variant } = lit;
615
653
  // Build the new value in a temporary: its fields may read the old value of the target.
616
654
  const tmp = this.tmp("de");
617
655
  this.line(`TSE_${e.name} ${tmp};`);
618
656
  this.line(`ts_memzero(&${tmp}, sizeof(${tmp}));`);
619
657
  this.line(`${tmp}.tag = ${vi};`);
620
- for (const f of variant.fields)
621
- if (!given.has(f.name))
622
- this.fail(valueNode, `missing field "${f.name}" of ${e.name}.${variant.name}`);
623
- // Fields are evaluated in source order, as in JS, straight into the temporary.
624
- for (const [name, ex] of given) {
625
- const f = variant.fields.find((x) => x.name === name);
626
- const sub = { lv: `${tmp}.v.${variant.name}.${f.name}`, type: f.type, writable: true };
627
- const vt = this.storageValueType(f.type);
628
- // A string kept in a variable enum holds its own copy of account text (the account may change later).
629
- if (vt)
630
- this.line(this.writeStorage(sub, this.ownedString(this.expect(this.expr(ex, vt), vt, ex)).c) + ";");
631
- else
632
- this.writeAggregate(sub, ex);
633
- }
658
+ lit.writeFields(`${tmp}.v.${variant.name}`);
634
659
  this.line(`ts_memcpy(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
635
660
  return;
636
661
  }
@@ -638,34 +663,43 @@ export class StorageEmitter extends AliasEmitter {
638
663
  const list = valueNode.arguments[0];
639
664
  if (valueNode.arguments.length !== 1 || !ts.isArrayLiteralExpression(list))
640
665
  this.fail(valueNode, "fixedVec([…]) takes an array literal");
641
- return this.writeAggregate(target, list);
666
+ return this.writeAggregate(target, list, fresh);
642
667
  }
643
668
  if (target.type.kind === "vec" && target.type.cap !== undefined && ts.isArrayLiteralExpression(valueNode)) {
644
- // `list = [a, b]`: built in a temporary (the elements may read the old list), the unused slots zeroed.
645
669
  const t = target.type;
646
670
  const els = valueNode.elements;
647
671
  if (els.length > t.cap)
648
672
  this.fail(valueNode, `${els.length} elements do not fit in ${typeName(t)}`);
649
- // Empty: nothing reads the old list, so it is cleared in place (length 0, every slot zero).
650
- if (els.length === 0) {
651
- this.line(`ts_memzero(&${target.lv}, sizeof(${target.lv}));`);
673
+ // The slots past the elements are zeroed (so the list's whole layout, copied into account data or an event, reads
674
+ // the same whatever ran before), large regions by the memset syscall: about constant compute units at any size.
675
+ const size = this.fieldBytes(t.elem);
676
+ const writeInto = (lv) => {
677
+ const free = (t.cap - els.length) * size;
678
+ if (free > 0)
679
+ this.line(`ts_memzero_bulk(${els.length ? `(uint8_t *)${lv}.items + ${els.length * size}` : `${lv}.items`}, ${free});`);
680
+ this.line(`${lv}.len = ${els.length};`);
681
+ els.forEach((e, i) => {
682
+ if (ts.isSpreadElement(e))
683
+ this.fail(e, "list the elements one by one");
684
+ const sub = { lv: `${lv}.items[${i}]`, type: t.elem, writable: true };
685
+ const vt = this.storageValueType(t.elem);
686
+ if (vt)
687
+ this.line(this.writeStorage(sub, this.ownedString(this.expect(this.expr(e, vt), vt, e)).c) + ";");
688
+ else
689
+ this.writeAggregate(sub, e, true);
690
+ });
691
+ };
692
+ // A fresh list (a declaration, a struct literal's field) is built in place: nothing can read it yet. So is an
693
+ // empty one, which reads nothing.
694
+ if (fresh || els.length === 0) {
695
+ writeInto(target.lv);
652
696
  return;
653
697
  }
698
+ // `list = [a, b]`: built in a temporary, since the elements may read the old list.
654
699
  const tmp = this.tmp("fv");
655
700
  this.line(`${fixedVecC(t)} ${tmp};`);
656
- this.line(`ts_memzero(&${tmp}, sizeof(${tmp}));`);
657
- this.line(`${tmp}.len = ${els.length};`);
658
- els.forEach((e, i) => {
659
- if (ts.isSpreadElement(e))
660
- this.fail(e, "list the elements one by one");
661
- const sub = { lv: `${tmp}.items[${i}]`, type: t.elem, writable: true };
662
- const vt = this.storageValueType(t.elem);
663
- if (vt)
664
- this.line(this.writeStorage(sub, this.ownedString(this.expect(this.expr(e, vt), vt, e)).c) + ";");
665
- else
666
- this.writeAggregate(sub, e);
667
- });
668
- this.line(`ts_memcpy(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
701
+ writeInto(tmp);
702
+ this.line(`ts_memcpy_const(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
669
703
  return;
670
704
  }
671
705
  // A struct holding a heap Vec is copied field by field: a whole copy would share one list between two places.
@@ -768,6 +802,12 @@ export class StorageEmitter extends AliasEmitter {
768
802
  // Same-typed places are either distinct or identical (`a.p = a.p`); ts_copy skips the latter.
769
803
  this.line(`ts_copy(&${target.lv}, &${src.lv}, sizeof(${target.lv}));`);
770
804
  }
805
+ /** `fixedVec([…])` or `[…]`: a list literal, which writeAggregate builds in a fresh target with its free slots zeroed. */
806
+ isListLiteral(node) {
807
+ while (ts.isParenthesizedExpression(node))
808
+ node = node.expression;
809
+ return ts.isArrayLiteralExpression(node) || (ts.isCallExpression(node) && this.exportName(node.expression) === "fixedVec");
810
+ }
771
811
  /** The Vec view of a FixedVec stored at `lv` (`{ len, items[cap] }`). */
772
812
  fixedVec(lv, elem, cap) {
773
813
  return { len: `${lv}.len`, items: `${lv}.items`, fixed: "", elemSize: this.fieldBytes(elem), resizable: false, cap };
@@ -819,6 +859,10 @@ export class StorageEmitter extends AliasEmitter {
819
859
  peekKind(node) {
820
860
  return this.probe(() => this.ref(node))?.type.kind;
821
861
  }
862
+ /** The type of the storage an expression names, without emitting code or failing. */
863
+ peekType(node) {
864
+ return this.probe(() => this.ref(node))?.type;
865
+ }
822
866
  place(node) {
823
867
  if (ts.isIdentifier(node)) {
824
868
  const l = this.lookup(node.text);
@@ -1,6 +1,6 @@
1
1
  import ts from "typescript";
2
2
  import { isWritable } from "../model.js";
3
- import { U64, U8, I64, BOOL, PUBKEY, STRING, cBytes, cString, optC } from "./shared.js";
3
+ import { U64, U8, I64, BOOL, PUBKEY, STRING, cBytes, optC } from "./shared.js";
4
4
  import { CreateEmitter } from "./create.js";
5
5
  /** SPL Token and Token-2022 instructions (`tokenProgram.transfer(…)` and the rest) and the ATA program's. */
6
6
  export class TokenEmitter extends CreateEmitter {
@@ -819,7 +819,7 @@ export class TokenEmitter extends CreateEmitter {
819
819
  const from = this.tmp("from");
820
820
  const n = this.tmp("n");
821
821
  const pre = this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value;
822
- const fail = (code, name, why) => `TS_FAIL(((uint64_t)${code}) << 32, ${cString(typeof pre === "string" ? `${pre}${name}` : `TypeSOL: ${why}`)})`;
822
+ const fail = (code, name, why) => this.programFail(`((uint64_t)${code}) << 32`, typeof pre === "string" ? `${pre}${name}` : `TypeSOL: ${why}`);
823
823
  this.line(`uint32_t ${t} = 13;`);
824
824
  this.line(`TS_TRY(ts_cpi(params, ${program.c}, (uint8_t *)&${t}, 4, NULL, 0, NULL, 0));`);
825
825
  this.line(`uint64_t ${out} = 0;`);
@@ -0,0 +1,60 @@
1
+ import ts from "typescript";
2
+ import { type RbTreeInst, type ValueType } from "../model.js";
3
+ import { CallEmitter } from "./calls.js";
4
+ import { type Local, type Ref, type Value } from "./shared.js";
5
+ /**
6
+ * Views of native account data at offsets known only at run time (Phoenix's market at byte 576, its trees sized by
7
+ * the market header, Serum's slabs): `loadRawAt` / `loadRawMutAt` (a fixed-layout struct), `rawArrayAt` /
8
+ * `rawArrayMutAt` (a run-time number of elements in place) and `rbTreeAt` / `rbTreeMutAt`, lib-sokoban 0.3's
9
+ * RedBlackTree<K, V, N> byte for byte. Each checks its bounds once, when it is made (ProgramError::AccountDataTooSmall),
10
+ * with the owner, writability and claim checks of loadRaw / loadRawMut.
11
+ */
12
+ export declare abstract class ViewEmitter extends CallEmitter {
13
+ /** The view function a call names (loadRawAt …), or undefined. */
14
+ protected viewFn(node: ts.Expression): string | undefined;
15
+ /** The tree a name holds (`const book = rbTreeMutAt<…>(…)`), with its instance. */
16
+ protected treeOf(node: ts.Expression): {
17
+ local: Local;
18
+ inst: RbTreeInst;
19
+ writable: boolean;
20
+ } | undefined;
21
+ /**
22
+ * `const x = loadRawAt<T>(…)` and the other views, or `const o = tree.get(k)` / `remove` / `min` / `max` / `nodeAt`
23
+ * when it hands out a reference into a node: declared here (true), else left to the general binding (false).
24
+ */
25
+ protected bindView(d: ts.VariableDeclaration, init: ts.Expression, name: string, c: string, mutable: boolean): boolean;
26
+ /** The struct type argument of loadRawAt<T>: a fixed-size struct without a BigVec. */
27
+ private rawAtStruct;
28
+ /** A u64 argument evaluated into a temporary, in argument order. */
29
+ private u64Arg;
30
+ /** The view's account and offset (and capacity), evaluated left to right, then the owner check (3007). */
31
+ private viewStart;
32
+ /** `loadRawAt<T>(acct, offset)` / `loadRawMutAt`: a fixed-layout struct at a run-time byte offset. */
33
+ protected loadRawAt(node: ts.CallExpression, mut: boolean): Value;
34
+ /** `rawArrayAt<T>(acct, offset, capacity)` / `rawArrayMutAt`: `capacity` elements in place, bound to `c` (and `c__n`). */
35
+ protected rawArrayAt(node: ts.CallExpression, mut: boolean, c: string): ValueType;
36
+ /** The place a RawArray local names: a list of `n` elements with no stored length (see Ref.vec). */
37
+ private rawArrayRef;
38
+ /** Rust's alignment of a field type (repr(C), as on SBF): for the node layout check. */
39
+ private alignOf;
40
+ /** Why the default order cannot compare this key type, or undefined. */
41
+ private unordered;
42
+ /**
43
+ * `rbTreeAt<K, V>(acct, offset, capacity, compare?)` / `rbTreeMutAt`: lib-sokoban 0.3's RedBlackTree<K, V, capacity>
44
+ * at a run-time offset (32 + capacity × (16 + size(K) + size(V)) bytes), bound to `c` (a TsRbt).
45
+ */
46
+ protected rbTreeAt(node: ts.CallExpression, mut: boolean, c: string): ValueType;
47
+ /** A pointer to a key or value given to a tree method: a struct place as it is, anything else in a temporary. */
48
+ private treeOperand;
49
+ /** The value stored in node `idx` (0: none) as an expression result: a nullable reference, or an Option copy. */
50
+ private nodeValue;
51
+ protected treeCall(node: ts.CallExpression): {
52
+ value: Value | undefined;
53
+ } | undefined;
54
+ /** A tree node a property is read on: an entry local, or `e!` / `tree.min()!` (checked), as a TsRbtEntry. */
55
+ private entryOf;
56
+ protected viewRef(node: ts.Expression): Ref | undefined;
57
+ /** `rbTreeMutAt(…).min()`, `rawArrayAt(…).get(i)`: a view used without binding it. */
58
+ private unbound;
59
+ protected viewProperty(node: ts.PropertyAccessExpression): Value | undefined;
60
+ }