@typesol/cli 0.49.0 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +541 -0
  2. package/NOTICE +9 -0
  3. package/README.md +34 -15
  4. package/SECURITY.md +6 -3
  5. package/dist/cli.js +36 -5
  6. package/dist/compiler/analyze.d.ts +10 -1
  7. package/dist/compiler/analyze.js +234 -20
  8. package/dist/compiler/diagnostics.d.ts +4 -0
  9. package/dist/compiler/diagnostics.js +5 -1
  10. package/dist/compiler/emit/base.d.ts +35 -4
  11. package/dist/compiler/emit/base.js +46 -4
  12. package/dist/compiler/emit/borsh.js +8 -8
  13. package/dist/compiler/emit/calls.d.ts +6 -0
  14. package/dist/compiler/emit/calls.js +98 -18
  15. package/dist/compiler/emit/cpi-core.d.ts +3 -0
  16. package/dist/compiler/emit/cpi-core.js +11 -5
  17. package/dist/compiler/emit/cpi.js +6 -4
  18. package/dist/compiler/emit/create.js +9 -9
  19. package/dist/compiler/emit/expressions.d.ts +9 -1
  20. package/dist/compiler/emit/expressions.js +77 -0
  21. package/dist/compiler/emit/function.d.ts +2 -0
  22. package/dist/compiler/emit/function.js +71 -15
  23. package/dist/compiler/emit/outline.d.ts +35 -0
  24. package/dist/compiler/emit/outline.js +547 -0
  25. package/dist/compiler/emit/program.js +19 -4
  26. package/dist/compiler/emit/rbtree.js +1 -1
  27. package/dist/compiler/emit/shared.d.ts +69 -4
  28. package/dist/compiler/emit/shared.js +44 -9
  29. package/dist/compiler/emit/statements.d.ts +36 -2
  30. package/dist/compiler/emit/statements.js +332 -29
  31. package/dist/compiler/emit/storage.d.ts +16 -0
  32. package/dist/compiler/emit/storage.js +134 -13
  33. package/dist/compiler/emit/views.js +1 -1
  34. package/dist/compiler/hints.d.ts +1 -1
  35. package/dist/compiler/hints.js +9 -1
  36. package/dist/compiler/idl.js +1 -1
  37. package/dist/compiler/index.d.ts +30 -2
  38. package/dist/compiler/index.js +94 -16
  39. package/dist/compiler/model.d.ts +13 -1
  40. package/dist/compiler/stack.d.ts +71 -0
  41. package/dist/compiler/stack.js +309 -0
  42. package/dist/compiler/toolchain.d.ts +87 -5
  43. package/dist/compiler/toolchain.js +384 -19
  44. package/dist/keys.d.ts +12 -1
  45. package/dist/keys.js +57 -7
  46. package/dist/workspace.d.ts +9 -0
  47. package/dist/workspace.js +91 -16
  48. package/docker/deps/0.50.0.lock.json +1206 -0
  49. package/docker/deps/0.51.0.lock.json +1206 -0
  50. package/docs/architecture.md +1 -1
  51. package/docs/audit.md +16 -13
  52. package/docs/case-study-escrow.md +1 -1
  53. package/docs/case-study-jito-mev.md +14 -14
  54. package/docs/case-study-marginfi.md +127 -127
  55. package/docs/case-study-multisig.md +16 -4
  56. package/docs/case-study-raydium-clmm.md +44 -28
  57. package/docs/case-study-raydium-cp-swap.md +18 -18
  58. package/docs/cli.md +5 -4
  59. package/docs/glossary.md +2 -1
  60. package/docs/language-accounts.md +16 -10
  61. package/docs/language-basics.md +29 -2
  62. package/docs/language-builtins.md +4 -2
  63. package/docs/language-cpi.md +34 -0
  64. package/docs/language-native.md +50 -4
  65. package/docs/language-pdas.md +6 -2
  66. package/docs/language-statements.md +103 -12
  67. package/docs/language-types.md +93 -8
  68. package/docs/runtime.md +20 -3
  69. package/docs/security-model.md +6 -3
  70. package/docs/stability.md +10 -5
  71. package/docs/testing.md +6 -2
  72. package/docs/troubleshooting.md +45 -1
  73. package/lib/typesol.d.ts +25 -3
  74. package/llms-full.txt +403 -54
  75. package/package.json +1 -1
  76. package/releases/0.49.0.json +857 -0
  77. package/releases/0.50.0.json +874 -0
  78. package/runtime/typesol_builtins.c +47 -2
  79. package/runtime/typesol_rt.h +254 -54
@@ -1,7 +1,7 @@
1
1
  import ts from "typescript";
2
2
  import { heapVecOf, resolveScalarType, structNameOf, typesolName } from "../analyze.js";
3
3
  import { INT_INFO, isScalar, isWritable, sameType, scalarSize, typeName } from "../model.js";
4
- import { U64, BOOL, PUBKEY, STRING, F64_TO_INT, optC, fieldC, fixedVecC, storageDecl, vecCount, vecPlace, emptySizeC } from "./shared.js";
4
+ import { U64, BOOL, PUBKEY, STRING, F64_TO_INT, optC, fieldC, fixedVecC, storageDecl, vecCount, vecPlace, emptySizeC, throughPointer, copyMacro, } from "./shared.js";
5
5
  import { AliasEmitter } from "./alias.js";
6
6
  /**
7
7
  * Places in account data and locals: references, reads and writes, Vec/array indexing, aliasing rules and
@@ -209,14 +209,14 @@ export class StorageEmitter extends AliasEmitter {
209
209
  this.checkLocalListSize(type, init);
210
210
  const one = this.tmp("fill");
211
211
  this.line(`${storageDecl(elem, one)};`);
212
- this.line(`ts_memzero(&${one}, sizeof(${one}));`);
212
+ this.line(`TS_ZERO_LOCAL(&${one}, sizeof(${one}));`);
213
213
  const vt = this.storageValueType(elem);
214
214
  if (vt)
215
215
  this.line(this.writeStorage({ lv: one, type: elem, writable: true }, this.expect(this.expr(init.arguments[0], vt), vt, init.arguments[0]).c) + ";");
216
216
  else
217
217
  this.writeAggregate({ lv: one, type: elem, writable: true }, init.arguments[0], true);
218
218
  this.line(`${storageDecl(type, c)};`);
219
- this.line(`for (uint64_t ${i} = 0; ${i} < ${len}; ${i}++) ts_memcpy(&${c}[${i}], &${one}, sizeof(${one}));`);
219
+ this.line(`for (uint64_t ${i} = 0; ${i} < ${len}; ${i}++) TS_MEMCPY(&${c}[${i}], &${one}, sizeof(${one}));`);
220
220
  return type;
221
221
  }
222
222
  /** Resolve an expression to a storage location, if it names one. */
@@ -558,6 +558,23 @@ export class StorageEmitter extends AliasEmitter {
558
558
  throw new Error("unreachable: aggregate writes go through memcpy");
559
559
  }
560
560
  }
561
+ /**
562
+ * Why a struct value cannot stand for another struct type it extends (`interface Child extends Base`, a Child passed
563
+ * as a Base): JavaScript passes the same object, which TypeSOL would copy (or cut to the parent's fields). Empty when
564
+ * the types are not related.
565
+ */
566
+ parentNote(from, want, node) {
567
+ if (!from && node) {
568
+ const a = this.accountAt(node);
569
+ if (a && "struct" in a.kind && a.kind.struct)
570
+ from = { kind: "struct", name: a.kind.struct.name };
571
+ }
572
+ if (from?.kind !== "struct" || want.kind !== "struct")
573
+ return "";
574
+ if (!this.model.structs.get(from.name)?.ancestors?.includes(want.name))
575
+ return "";
576
+ return `; a ${from.name} is not used as its parent ${want.name} (TypeSOL copies structs where JavaScript shares the object): build a ${want.name} from its fields with { ...value } or { field: value.field, … }`;
577
+ }
561
578
  storageValueType(t) {
562
579
  if (isScalar(t))
563
580
  return t;
@@ -602,7 +619,9 @@ export class StorageEmitter extends AliasEmitter {
602
619
  else if (ts.isShorthandPropertyAssignment(p))
603
620
  given.set(p.name.text, p.name);
604
621
  else
605
- this.fail(p, "use plain `field: value` entries");
622
+ this.fail(p, ts.isSpreadAssignment(p)
623
+ ? 'spread (...) is not supported in a data enum literal: write kind: "Variant" and each field'
624
+ : "use plain `field: value` entries");
606
625
  }
607
626
  for (const k of given.keys())
608
627
  if (!variant.fields.some((f) => f.name === k))
@@ -646,13 +665,13 @@ export class StorageEmitter extends AliasEmitter {
646
665
  if (target.type.kind === "option" && target.type.inner.kind === "struct") {
647
666
  if (valueNode.kind === ts.SyntaxKind.NullKeyword) {
648
667
  this.line(`${target.lv}.some = 0;`);
649
- this.line(`ts_memzero(&${target.lv}.v, sizeof(${target.lv}.v));`);
668
+ this.line(`${throughPointer(target.lv) ? "TS_ZERO" : "TS_ZERO_LOCAL"}(&${target.lv}.v, sizeof(${target.lv}.v));`);
650
669
  return;
651
670
  }
652
671
  // Another Option<same struct>: copy it whole (tag and value).
653
672
  const whole = ts.isObjectLiteralExpression(valueNode) ? undefined : this.ref(valueNode);
654
673
  if (whole && sameType(whole.type, target.type)) {
655
- this.line(`ts_copy(&${target.lv}, &${whole.lv}, sizeof(${target.lv}));`);
674
+ this.line(`${copyMacro(target.lv, whole.lv)}(&${target.lv}, &${whole.lv}, sizeof(${target.lv}));`);
656
675
  return;
657
676
  }
658
677
  this.writeAggregate({ ...target, lv: `${target.lv}.v`, type: target.type.inner }, valueNode);
@@ -665,10 +684,10 @@ export class StorageEmitter extends AliasEmitter {
665
684
  // Build the new value in a temporary: its fields may read the old value of the target.
666
685
  const tmp = this.tmp("de");
667
686
  this.line(`TSE_${e.name} ${tmp};`);
668
- this.line(`ts_memzero(&${tmp}, sizeof(${tmp}));`);
687
+ this.line(`TS_ZERO_LOCAL(&${tmp}, sizeof(${tmp}));`);
669
688
  this.line(`${tmp}.tag = ${vi};`);
670
689
  lit.writeFields(`${tmp}.v.${variant.name}`);
671
- this.line(`ts_memcpy(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
690
+ this.line(`TS_MEMCPY(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
672
691
  return;
673
692
  }
674
693
  if (target.type.kind === "vec" && target.type.cap !== undefined && ts.isCallExpression(valueNode) && this.exportName(valueNode.expression) === "fixedVec") {
@@ -692,7 +711,7 @@ export class StorageEmitter extends AliasEmitter {
692
711
  this.line(`${lv}.len = ${els.length};`);
693
712
  els.forEach((e, i) => {
694
713
  if (ts.isSpreadElement(e))
695
- this.fail(e, "list the elements one by one");
714
+ this.fail(e, "spread (...) in a list literal is not supported: list the elements one by one, or add a whole list with pushAll(…)");
696
715
  const sub = { lv: `${lv}.items[${i}]`, type: t.elem, writable: true };
697
716
  const vt = this.storageValueType(t.elem);
698
717
  if (vt)
@@ -721,6 +740,8 @@ export class StorageEmitter extends AliasEmitter {
721
740
  if (target.type.kind !== "struct")
722
741
  this.fail(valueNode, `expected a ${typeName(target.type)}, not an object literal`);
723
742
  const s = this.model.structs.get(target.type.name);
743
+ if (valueNode.properties.some((p) => ts.isSpreadAssignment(p)))
744
+ return this.spreadLiteral(target, s, valueNode, fresh);
724
745
  const given = new Map();
725
746
  for (const p of valueNode.properties) {
726
747
  if (ts.isPropertyAssignment(p) && ts.isIdentifier(p.name))
@@ -752,7 +773,7 @@ export class StorageEmitter extends AliasEmitter {
752
773
  this.writeAggregate(sub, e, true);
753
774
  }
754
775
  if (tmp)
755
- this.line(`ts_memcpy(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
776
+ this.line(`TS_MEMCPY(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
756
777
  return;
757
778
  }
758
779
  if (ts.isConditionalExpression(valueNode)) {
@@ -810,9 +831,109 @@ export class StorageEmitter extends AliasEmitter {
810
831
  sameType(src.type.inner, target.type))
811
832
  src = this.someValue(src);
812
833
  if (!src || !sameType(src.type, target.type))
813
- this.fail(valueNode, `expected a ${typeName(target.type)}: an object literal, another ${typeName(target.type)}${target.type.kind === "vec" && target.type.cap !== undefined ? " or a Vec of the same elements" : ""}`);
814
- // Same-typed places are either distinct or identical (`a.p = a.p`); ts_copy skips the latter.
815
- this.line(`ts_copy(&${target.lv}, &${src.lv}, sizeof(${target.lv}));`);
834
+ this.fail(valueNode, `expected a ${typeName(target.type)}: an object literal, another ${typeName(target.type)}${target.type.kind === "vec" && target.type.cap !== undefined ? " or a Vec of the same elements" : ""}${this.parentNote(src?.type, target.type, valueNode)}`);
835
+ // Same-typed places are either distinct, identical (`a.p = a.p`) or, through native views of one account at
836
+ // different offsets, overlapping: TS_COPY leaves the source's old bytes either way (below the threshold every byte
837
+ // is loaded before any is stored, from it the memmove syscall copies them as copy_within does).
838
+ this.line(`${copyMacro(target.lv, src.lv)}(&${target.lv}, &${src.lv}, sizeof(${target.lv}));`);
839
+ }
840
+ /**
841
+ * `{ ...p, x: 1n }` / `{ x: 1n, ...p }`: entries in source order, each evaluated once, a later one overwriting an
842
+ * earlier one, as in JS. `...p` copies p's fields at that point, as `field: p.field` would (a struct field is copied
843
+ * whole, as assignment copies). p is a struct of the literal's type, one it extends (its fields are copied), or one
844
+ * extending it (the literal's fields are copied from it); a struct account is one too. The value is built in a
845
+ * temporary unless the target is fresh, so `acct.p = { ...acct.p, x: acct.p.y }` reads the old fields.
846
+ */
847
+ spreadLiteral(target, s, valueNode, fresh) {
848
+ if (s.size === undefined || s.vec)
849
+ this.fail(valueNode, `${s.name} has variable-size fields: spread (...) copies fixed-size structs; write each field`);
850
+ const entries = [];
851
+ const covered = new Set();
852
+ for (const p of valueNode.properties) {
853
+ if (ts.isPropertyAssignment(p) && ts.isIdentifier(p.name))
854
+ entries.push({ name: p.name.text, e: p.initializer, node: p });
855
+ else if (ts.isShorthandPropertyAssignment(p))
856
+ entries.push({ name: p.name.text, e: p.name, node: p });
857
+ else if (ts.isSpreadAssignment(p)) {
858
+ // The source's type, found without emitting anything: its C is emitted in order below.
859
+ const src = this.probe(() => this.spreadSource(p.expression));
860
+ if (!src) {
861
+ this.spreadSource(p.expression); // reports why
862
+ this.fail(p.expression, "...value takes a struct: a local, a field, a struct account or a helper's struct parameter");
863
+ }
864
+ const from = this.model.structs.get(src.name);
865
+ const related = from.name === s.name || s.ancestors?.includes(from.name) || from.ancestors?.includes(s.name);
866
+ if (!related)
867
+ this.fail(p.expression, `...${p.expression.getText()} is a ${from.name}, not a ${s.name}: spread a ${s.name}, a struct ${s.name} extends, or one that extends ${s.name}`);
868
+ if (from.size === undefined || from.vec)
869
+ this.fail(p.expression, `${from.name} has variable-size fields: spread (...) copies fixed-size structs`);
870
+ // A parent copies its own fields; a child, the literal's (it has them all).
871
+ const fields = (s.ancestors?.includes(from.name) ? from : s).fields.map((f) => f.name);
872
+ for (const f of fields)
873
+ covered.add(f);
874
+ entries.push({ spread: p.expression, fields, whole: from.name === s.name });
875
+ }
876
+ else
877
+ this.fail(p, "use plain `field: value` entries or ...value");
878
+ }
879
+ for (const en of entries)
880
+ if ("name" in en && !s.fields.some((f) => f.name === en.name))
881
+ this.fail(en.node, `${s.name} has no field "${en.name}"`);
882
+ // A nested struct, list or enum value is an object JavaScript would share between the spread value and the new one,
883
+ // where TypeSOL copies it: such a field is given after the spread (`pos: { ...p.pos }` is a copy in JS too).
884
+ entries.forEach((en, i) => {
885
+ if (!("spread" in en))
886
+ return;
887
+ for (const name of en.fields) {
888
+ const t = s.fields.find((f) => f.name === name).type;
889
+ const shared = t.kind === "struct" ||
890
+ t.kind === "array" ||
891
+ t.kind === "vec" ||
892
+ t.kind === "dataEnum" ||
893
+ (t.kind === "option" && t.inner.kind !== "int" && t.inner.kind !== "bool" && t.inner.kind !== "pubkey" && t.inner.kind !== "enum");
894
+ if (shared && !entries.slice(i + 1).some((later) => "name" in later && later.name === name))
895
+ this.fail(en.spread, `...${en.spread.getText()} would copy ${name}, a ${typeName(t)}: JavaScript shares that object between the two values, TypeSOL copies it; give ${name} after the spread${t.kind === "struct" ? ` (${name}: { ...${en.spread.getText()}.${name} } copies it in JavaScript too)` : ""}`);
896
+ }
897
+ });
898
+ for (const en of entries)
899
+ if ("name" in en)
900
+ covered.add(en.name);
901
+ for (const f of s.fields)
902
+ if (!covered.has(f.name))
903
+ this.fail(valueNode, `missing field "${f.name}" of ${s.name}`);
904
+ const tmp = fresh ? undefined : this.tmp("st");
905
+ if (tmp)
906
+ this.line(`TSS_${s.name} ${tmp};`);
907
+ const into = tmp ?? target.lv;
908
+ for (const en of entries) {
909
+ if ("spread" in en) {
910
+ const src = this.spreadSource(en.spread);
911
+ if (en.whole)
912
+ this.line(`${copyMacro(into, src.lv)}(&${into}, &${src.lv}, sizeof(${into}));`);
913
+ else
914
+ for (const f of en.fields)
915
+ this.line(`${copyMacro(into, src.lv)}(&${into}.${f}, &${src.lv}.${f}, sizeof(${into}.${f}));`);
916
+ continue;
917
+ }
918
+ const f = s.fields.find((x) => x.name === en.name);
919
+ const sub = { lv: `${into}.${f.name}`, type: f.type, writable: true };
920
+ const vt = this.storageValueType(f.type);
921
+ if (vt)
922
+ this.line(this.writeStorage(sub, this.expect(this.expr(en.e, vt), vt, en.e).c) + ";");
923
+ else
924
+ this.writeAggregate(sub, en.e, true);
925
+ }
926
+ if (tmp)
927
+ this.line(`TS_MEMCPY(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
928
+ }
929
+ /** The struct place `...value` copies from: a struct place, or a whole struct account. */
930
+ spreadSource(node) {
931
+ let src = this.ref(node) ?? this.wholeAccount(node);
932
+ if (src && src.type.kind === "option" && src.type.inner.kind === "struct")
933
+ src = this.someValue(src);
934
+ if (!src || src.type.kind !== "struct")
935
+ return undefined;
936
+ return { ...src, name: src.type.name };
816
937
  }
817
938
  /** `fixedVec([…])` or `[…]`: a list literal, which writeAggregate builds in a fresh target with its free slots zeroed. */
818
939
  isListLiteral(node) {
@@ -308,7 +308,7 @@ export class ViewEmitter extends CallEmitter {
308
308
  const o = this.tmp("rbopt");
309
309
  this.line(`${optC(scalar)} ${o};`);
310
310
  this.line(`${o}.some = ${idx} != 0;`);
311
- this.line(`if (${idx}) ts_memcpy(&${o}.v, ${at}, ${inst.valueSize}); else ts_memzero(&${o}.v, ${inst.valueSize});`);
311
+ this.line(`if (${idx}) TS_MEMCPY(&${o}.v, ${at}, ${inst.valueSize}); else TS_ZERO_LOCAL(&${o}.v, ${inst.valueSize});`);
312
312
  return { c: o, type: { kind: "option", inner: scalar } };
313
313
  }
314
314
  treeCall(node) {
@@ -9,4 +9,4 @@ export declare function fieldTypeHint(node: ts.Node): string | undefined;
9
9
  /** A sentence to add to a TypeScript diagnostic, or undefined when TypeScript's own message says enough. */
10
10
  export declare function hintForTypeScript(d: ts.Diagnostic, message: string, libPath: string): string | undefined;
11
11
  /** "ClassDeclaration is not supported …" in words a TypeScript developer recognizes. */
12
- export declare function unsupportedSyntax(kind: ts.SyntaxKind, where: "top level" | "expression"): string;
12
+ export declare function unsupportedSyntax(kind: ts.SyntaxKind, where: "top level" | "expression", node?: ts.Node): string;
@@ -98,6 +98,8 @@ export function hintForTypeScript(d, message, libPath) {
98
98
  return CLOCK_HINT;
99
99
  if (/\bMath\.\w+\(/.test(line))
100
100
  return MINMAX_HINT;
101
+ if (/'number'/.test(message) && /\.length\b/.test(line))
102
+ return "a string's .length is a JavaScript number: byteLength(s) gives its size in bytes as a u64 (lists have .length as a u64)";
101
103
  if (/\bbigint\b/.test(message) && (/\bnumber\b/.test(message) || /'-?\d+'/.test(message)))
102
104
  return BIGINT_HINT;
103
105
  return undefined;
@@ -136,10 +138,16 @@ const SYNTAX = {
136
138
  [ts.SyntaxKind.ModuleDeclaration]: "namespaces are not supported: use separate files and import from them",
137
139
  };
138
140
  /** "ClassDeclaration is not supported …" in words a TypeScript developer recognizes. */
139
- export function unsupportedSyntax(kind, where) {
141
+ export function unsupportedSyntax(kind, where, node) {
140
142
  const known = SYNTAX[kind];
141
143
  if (known)
142
144
  return known;
145
+ if (node && ts.isExportDeclaration(node))
146
+ return node.moduleSpecifier
147
+ ? `re-exports (${node.getText().replace(/;$/, "")}) are not supported: import the name from the file that declares it`
148
+ : "export lists (export { a, b }) are not supported: write export on each declaration (export function a(…))";
149
+ if (node && ts.isExportAssignment(node))
150
+ return "export default is not supported: write export on the declaration (export function name(…))";
143
151
  return where === "top level"
144
152
  ? `this kind of statement (${ts.SyntaxKind[kind]}) is not supported at the top level of a TypeSOL file`
145
153
  : `this syntax (${ts.SyntaxKind[kind]}) is not supported in TypeSOL expressions`;
@@ -243,7 +243,7 @@ export function buildIdl(model, address, version = "0.1.0") {
243
243
  // An event lists its fields as it sends them (declared order); account data as it stores them.
244
244
  fields: (s.declared && !model.accountStructs.has(s.name) ? s.declared.map((n) => s.fields.find((f) => f.name === n)) : s.fields).map((f) => ({
245
245
  name: f.idlName ?? fieldIdlName(f.name),
246
- ...docsOf(s.node.members.find((m) => m.name && ts.isIdentifier(m.name) && m.name.text === f.name)),
246
+ ...docsOf(s.members.get(f.name)),
247
247
  type: f.idlBytes
248
248
  ? f.type.kind === "array"
249
249
  ? { array: [{ array: ["u8", f.idlBytes] }, f.type.len] }
@@ -2,10 +2,12 @@ import ts from "typescript";
2
2
  import { type EmitOptions } from "./emit/index.js";
3
3
  import { buildIdl } from "./idl.js";
4
4
  import { type Sbpf } from "./toolchain.js";
5
+ import { type StackReport } from "./stack.js";
5
6
  import type { ProgramModel } from "./model.js";
6
7
  export { CompileError, formatDiagnostic, type Diagnostic } from "./diagnostics.js";
7
8
  export type { ProgramModel } from "./model.js";
8
- export { SBPF_VERSIONS, TESTED_TOOLCHAIN, type Sbpf } from "./toolchain.js";
9
+ export { SBPF_VERSIONS, TESTED_TOOLCHAIN, StackLimitError, type Sbpf } from "./toolchain.js";
10
+ export { describeAction, stackNotes, type StackAction, type StackReport } from "./stack.js";
9
11
  /** The hint the CLI adds under a TypeScript error (what to write instead in a TypeSOL program), for the editor plugin. */
10
12
  export declare function typescriptHint(d: ts.Diagnostic): string | undefined;
11
13
  /**
@@ -18,6 +20,8 @@ export interface Generated {
18
20
  c: string;
19
21
  /** The TypeSOL source files of the program (entry and relative imports). */
20
22
  files: string[];
23
+ /** Each source file's text as the compiler read it. */
24
+ texts: Map<string, string>;
21
25
  }
22
26
  /** Typecheck, enforce the TypeSOL subset, and generate C. Throws CompileError with every diagnostic. */
23
27
  export declare function generate(entry: string, opts?: EmitOptions): Generated;
@@ -44,6 +48,11 @@ export interface BuildManifest {
44
48
  binary: string;
45
49
  /** Set when the build ran in the pinned container (`typesol build --docker`, after 0.44.0): what that environment is. */
46
50
  container?: ContainerIdentity;
51
+ /**
52
+ * Set when the program did not fit the stack as it is and the build laid it out another way (src/compiler/stack.ts):
53
+ * what it did, in order, and the frames of the functions that did not fit, before and after.
54
+ */
55
+ stack?: StackReport;
47
56
  }
48
57
  /**
49
58
  * The build container of `--docker` (docker/Dockerfile): everything that decides what is inside it, so that another
@@ -98,11 +107,30 @@ export interface BuildResult extends Generated {
98
107
  cPath: string;
99
108
  idlPath: string;
100
109
  idl: ReturnType<typeof buildIdl>;
110
+ /** What the build did to fit the stack (also in the manifest); undefined when the program fitted as it is. */
111
+ stack?: StackReport;
101
112
  }
102
- /** Full build: `<outDir>/<name>.c`, `<name>.so`, `<name>.json` (Anchor IDL). */
113
+ /** A step of `build`, for `onStep`: the C generated (the sources read), the C compiled and linked. */
114
+ export type BuildStep = "generated" | "compiled";
115
+ /**
116
+ * Full build: `<outDir>/<name>.c`, `<name>.so`, `<name>.json` (Anchor IDL) and `<name>.build.json`, the manifest.
117
+ *
118
+ * The manifest binds the binary to the exact inputs that made it: each source's sha256 is that of the bytes the
119
+ * compiler parsed (read once, checked against the text the TypeScript program holds), the runtime files are hashed
120
+ * before clang reads them, and every input is hashed again once the binary is linked. An input that changed in between
121
+ * (an editor saving a file mid-build) fails the build with no manifest: a previous build's manifest is removed before
122
+ * anything is written, so a reused build (buildForTest) never pairs a binary with sources that did not make it.
123
+ * `onStep` is called after each step (tests use it to change a file at that point).
124
+ */
103
125
  export declare function build(entry: string, outDir: string, programAddress: string, opts?: {
104
126
  sbpf?: Sbpf;
105
127
  profile?: boolean;
128
+ onStep?: (step: BuildStep) => void;
129
+ /**
130
+ * False: a program that does not fit the stack fails to build (`--stack-auto off`), as with `const STACK_AUTO =
131
+ * false` in the program; otherwise the build lays it out another way when it can (src/compiler/stack.ts).
132
+ */
133
+ stackAuto?: boolean;
106
134
  }): BuildResult;
107
135
  /** The package version (one source: package.json), recorded in build manifests and shown by the CLI. */
108
136
  export declare const COMPILER_VERSION: string;
@@ -1,16 +1,18 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { createRequire } from "node:module";
3
3
  import ts from "typescript";
4
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
5
  import path from "node:path";
6
6
  import { analyze, LIB_PATH } from "./analyze.js";
7
7
  import { hintForTypeScript, messageForTypeScript } from "./hints.js";
8
8
  import { emitProgram } from "./emit/index.js";
9
9
  import { buildIdl } from "./idl.js";
10
- import { buildSharedObject, checkToolchain, shortClang, TESTED_TOOLCHAIN } from "./toolchain.js";
10
+ import { buildSharedObject, checkToolchain, measureFrames, shortClang, TESTED_TOOLCHAIN } from "./toolchain.js";
11
+ import { buildWithStackLayout } from "./stack.js";
11
12
  import { BUILTINS_SOURCE, RUNTIME_DIR } from "./toolchain.js";
12
13
  export { CompileError, formatDiagnostic } from "./diagnostics.js";
13
- export { SBPF_VERSIONS, TESTED_TOOLCHAIN } from "./toolchain.js";
14
+ export { SBPF_VERSIONS, TESTED_TOOLCHAIN, StackLimitError } from "./toolchain.js";
15
+ export { describeAction, stackNotes } from "./stack.js";
14
16
  /** The hint the CLI adds under a TypeScript error (what to write instead in a TypeSOL program), for the editor plugin. */
15
17
  export function typescriptHint(d) {
16
18
  return hintForTypeScript(d, ts.flattenDiagnosticMessageText(d.messageText, "\n"), LIB_PATH);
@@ -30,29 +32,92 @@ export function generate(entry, opts = {}) {
30
32
  analysis.reporter.throwIfAny();
31
33
  const c = emitProgram(analysis, opts);
32
34
  analysis.reporter.throwIfAny();
33
- return { model: analysis.model, c, files: analysis.files };
35
+ return { model: analysis.model, c, files: analysis.files, texts: analysis.texts };
34
36
  }
35
37
  const sha256 = (data) => createHash("sha256").update(data).digest("hex");
36
- /** Full build: `<outDir>/<name>.c`, `<name>.so`, `<name>.json` (Anchor IDL). */
38
+ /**
39
+ * Full build: `<outDir>/<name>.c`, `<name>.so`, `<name>.json` (Anchor IDL) and `<name>.build.json`, the manifest.
40
+ *
41
+ * The manifest binds the binary to the exact inputs that made it: each source's sha256 is that of the bytes the
42
+ * compiler parsed (read once, checked against the text the TypeScript program holds), the runtime files are hashed
43
+ * before clang reads them, and every input is hashed again once the binary is linked. An input that changed in between
44
+ * (an editor saving a file mid-build) fails the build with no manifest: a previous build's manifest is removed before
45
+ * anything is written, so a reused build (buildForTest) never pairs a binary with sources that did not make it.
46
+ * `onStep` is called after each step (tests use it to change a file at that point).
47
+ */
37
48
  export function build(entry, outDir, programAddress, opts = {}) {
38
- const gen = generate(entry, { profile: opts.profile });
49
+ const runtime = {
50
+ "<runtime>/typesol_rt.h": path.join(RUNTIME_DIR, "typesol_rt.h"),
51
+ "<runtime>/typesol_builtins.c": BUILTINS_SOURCE,
52
+ };
53
+ const runtimeHashes = Object.fromEntries(Object.entries(runtime).map(([k, f]) => [k, sha256(readFileSync(f))]));
54
+ const first = generate(entry, { profile: opts.profile });
55
+ opts.onStep?.("generated");
56
+ const root = path.dirname(path.resolve(entry));
57
+ const changed = (rel) => new Error(`${rel} changed while it was being built, so the binary may not be what it holds now: no manifest was written; build again`);
58
+ const sources = {};
59
+ for (const f of first.files) {
60
+ const bytes = readFileSync(f);
61
+ if (decodeSource(bytes) !== first.texts.get(f))
62
+ throw changed(path.relative(root, f));
63
+ sources[path.relative(root, f)] = sha256(bytes);
64
+ }
39
65
  mkdirSync(outDir, { recursive: true });
40
- const base = path.join(outDir, gen.model.name);
66
+ const base = path.join(outDir, first.model.name);
41
67
  const cPath = `${base}.c`;
42
68
  const soPath = `${base}.so`;
43
69
  const idlPath = `${base}.json`;
44
- writeFileSync(cPath, gen.c);
70
+ const manifestPath = `${base}.build.json`;
71
+ rmSync(manifestPath, { force: true });
72
+ writeFileSync(cPath, first.c);
45
73
  // Before clang runs: an untested toolchain is a warning (once), or an error in strict mode.
46
74
  const toolchain = checkToolchain();
47
- buildSharedObject(cPath, soPath, opts.sbpf);
75
+ const sbpf = opts.sbpf ?? "v0";
76
+ const layoutC = `${base}.layout.c`;
77
+ let built;
78
+ try {
79
+ built = buildWithStackLayout({
80
+ // Another layout is generated from the same sources, read again: they must not have changed since.
81
+ generate: (plan) => {
82
+ const g = generate(entry, { profile: opts.profile, stack: plan });
83
+ for (const f of g.files)
84
+ if (g.texts.get(f) !== first.texts.get(f))
85
+ throw changed(path.relative(root, f));
86
+ return g;
87
+ },
88
+ compile: (c, brief) => {
89
+ writeFileSync(cPath, c);
90
+ buildSharedObject(cPath, soPath, opts.sbpf, undefined, { brief });
91
+ },
92
+ measure: (c) => {
93
+ writeFileSync(layoutC, c);
94
+ try {
95
+ return measureFrames(layoutC, sbpf);
96
+ }
97
+ finally {
98
+ rmSync(layoutC, { force: true });
99
+ }
100
+ },
101
+ }, first, { auto: opts.stackAuto !== false && first.model.constants.get("STACK_AUTO")?.value !== false, sbpf });
102
+ }
103
+ catch (e) {
104
+ // The C left next to a failed build is the program as it is, not a layout tried for it.
105
+ if (existsSync(cPath))
106
+ writeFileSync(cPath, first.c);
107
+ throw e;
108
+ }
109
+ const gen = built.gen;
110
+ opts.onStep?.("compiled");
48
111
  const idl = buildIdl(gen.model, programAddress);
49
112
  writeFileSync(idlPath, JSON.stringify(idl, null, 2) + "\n");
50
- const root = path.dirname(path.resolve(entry));
51
- const sources = {};
52
113
  for (const f of gen.files)
53
- sources[path.relative(root, f)] = sha256(readFileSync(f));
54
- sources["<runtime>/typesol_rt.h"] = sha256(readFileSync(path.join(RUNTIME_DIR, "typesol_rt.h")));
55
- sources["<runtime>/typesol_builtins.c"] = sha256(readFileSync(BUILTINS_SOURCE));
114
+ if (sha256(readFileSync(f)) !== sources[path.relative(root, f)])
115
+ throw changed(path.relative(root, f));
116
+ for (const [k, f] of Object.entries(runtime)) {
117
+ if (sha256(readFileSync(f)) !== runtimeHashes[k])
118
+ throw changed(f);
119
+ sources[k] = runtimeHashes[k];
120
+ }
56
121
  const manifest = {
57
122
  program: gen.model.name,
58
123
  compiler: COMPILER_VERSION,
@@ -64,10 +129,23 @@ export function build(entry, outDir, programAddress, opts = {}) {
64
129
  profile: !!opts.profile,
65
130
  sources,
66
131
  binary: sha256(readFileSync(soPath)),
132
+ ...(built.report ? { stack: built.report } : {}),
67
133
  };
68
- const manifestPath = `${base}.build.json`;
69
134
  writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + "\n");
70
- return { ...gen, cPath, soPath, idlPath, idl, manifest, manifestPath };
135
+ return { ...gen, cPath, soPath, idlPath, idl, manifest, manifestPath, ...(built.report ? { stack: built.report } : {}) };
136
+ }
137
+ /** A source file's bytes as TypeScript reads them (ts.sys.readFile): UTF-8, or UTF-16 with its byte-order mark, no BOM. */
138
+ function decodeSource(b) {
139
+ if (b.length >= 2 && b[0] === 0xfe && b[1] === 0xff) {
140
+ const swapped = Buffer.from(b.subarray(2, 2 + ((b.length - 2) & ~1)));
141
+ swapped.swap16();
142
+ return swapped.toString("utf16le");
143
+ }
144
+ if (b.length >= 2 && b[0] === 0xff && b[1] === 0xfe)
145
+ return b.toString("utf16le", 2);
146
+ if (b.length >= 3 && b[0] === 0xef && b[1] === 0xbb && b[2] === 0xbf)
147
+ return b.toString("utf8", 3);
148
+ return b.toString("utf8");
71
149
  }
72
150
  /** The package version (one source: package.json), recorded in build manifests and shown by the CLI. */
73
151
  export const COMPILER_VERSION = createRequire(import.meta.url)("../../package.json").version;
@@ -179,6 +179,8 @@ export interface StructField {
179
179
  /** The declaration, while the struct is being analyzed (for messages). */
180
180
  node?: ts.Node;
181
181
  }
182
+ /** A struct's declaration: an interface, or an object type alias (`type Point = { x: u64; y: u64 }`). */
183
+ export type StructDecl = ts.InterfaceDeclaration | ts.TypeAliasDeclaration;
182
184
  /** Every exported interface. Used as account data, nested in other structs, or emitted as an event. */
183
185
  export interface StructDef {
184
186
  name: string;
@@ -211,7 +213,15 @@ export interface StructDef {
211
213
  };
212
214
  accountDiscriminator: number[];
213
215
  eventDiscriminator: number[];
214
- node: ts.InterfaceDeclaration;
216
+ /** `interface X { … }` or `type X = { … }`. */
217
+ node: StructDecl;
218
+ /**
219
+ * The member declaring each field, by name: the struct's own, and for the fields it inherits (`interface B extends
220
+ * A`), the parent's (for doc comments and messages).
221
+ */
222
+ members: Map<string, ts.TypeElement>;
223
+ /** The structs it extends, directly or through them (`interface B extends A`), nearest first. */
224
+ ancestors?: string[];
215
225
  /** Not exported (`interface Pair { … }`): its file's own, for helpers and locals, and left out of the IDL. */
216
226
  local?: true;
217
227
  /**
@@ -508,6 +518,8 @@ export interface Helper {
508
518
  imports: Map<string, string>;
509
519
  /** `/** @noinline *\/`: a C function of its own that clang never inlines, so its locals get a stack frame of their own. */
510
520
  noinline?: boolean;
521
+ /** `/** @inline *\/`: never made noinline by the build to fit the stack (clang still decides whether to inline it). */
522
+ inline?: boolean;
511
523
  }
512
524
  /** A top-level compile-time constant. `type` is set when annotated (`const FEE: u16 = 30n`). */
513
525
  export interface ConstDef {
@@ -0,0 +1,71 @@
1
+ import type { ProgramModel } from "./model.js";
2
+ import type { StackPlan } from "./emit/shared.js";
3
+ import { type Sbpf } from "./toolchain.js";
4
+ /** What the build did to make a program fit, recorded in `<name>.build.json` as `stack.actions` and printed as notes. */
5
+ export type StackAction = {
6
+ action: "scope";
7
+ function: string;
8
+ for: string;
9
+ } | {
10
+ action: "noinline";
11
+ helper: string;
12
+ for: string;
13
+ calls: "in a loop" | "outside loops";
14
+ } | {
15
+ action: "heap";
16
+ local: string;
17
+ at: string;
18
+ bytes: number;
19
+ for: string;
20
+ };
21
+ export interface StackReport {
22
+ actions: StackAction[];
23
+ /** The frames (bytes, measured by clang) of the functions that did not fit, before and after. */
24
+ frames: Record<string, {
25
+ before?: number;
26
+ after?: number;
27
+ }>;
28
+ }
29
+ /** The build steps the ladder runs, so that it can be tested without clang. */
30
+ export interface StackSteps<G extends {
31
+ c: string;
32
+ model: ProgramModel;
33
+ }> {
34
+ /** Generate the program's C with a layout (candidates is set: the emitter lists the heap candidates in it). */
35
+ generate(plan: StackPlan): G;
36
+ /** Compile and link `c` (throwing as the build does); `brief`: no second compile to explain a frame error. */
37
+ compile(c: string, brief: boolean): void;
38
+ /** The frame of every function clang keeps in the object of `c`. */
39
+ measure(c: string): Map<string, number>;
40
+ }
41
+ /** How the program names a C function: "instruction f", "helper g()", "a loop of instruction f". */
42
+ export declare function describeFunction(fn: string): string;
43
+ /** The generated C's functions: body lines, whether declared noinline, and the helpers and loops each calls. */
44
+ export declare function cFunctionsOf(c: string): Map<string, {
45
+ body: string[];
46
+ noinline: boolean;
47
+ }>;
48
+ /**
49
+ * The helpers whose bodies clang may inline into `fn`, directly or through other such helpers, each with whether a
50
+ * call on the way is inside a loop. Helpers declared noinline (and loops moved out) have frames of their own.
51
+ */
52
+ export declare function inlinedInto(fns: ReturnType<typeof cFunctionsOf>, fn: string): Map<string, boolean>;
53
+ /**
54
+ * Build `steps`, laying the program out another way when it does not fit the stack (see the module comment). Returns
55
+ * the generated program that built, and what was done (undefined when it built as it is). Throws the first build's
56
+ * error when nothing made it fit, with a line saying what was tried, and that error alone when `auto` is false.
57
+ */
58
+ export declare function buildWithStackLayout<G extends {
59
+ c: string;
60
+ model: ProgramModel;
61
+ }>(steps: StackSteps<G>, first: G, opts: {
62
+ auto: boolean;
63
+ sbpf: Sbpf;
64
+ }): {
65
+ gen: G;
66
+ report?: StackReport;
67
+ };
68
+ /** One action as a note's text. */
69
+ export declare function describeAction(a: StackAction): string;
70
+ /** The notes a build prints for what it did: one per action, then the frames before and after. */
71
+ export declare function stackNotes(report: StackReport, sbpf: Sbpf): string[];