@typesol/cli 0.41.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 (62) hide show
  1. package/CHANGELOG.md +319 -0
  2. package/README.md +11 -7
  3. package/dist/compiler/analyze.js +484 -13
  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 +65 -7
  9. package/dist/compiler/emit/base.js +91 -7
  10. package/dist/compiler/emit/borsh.d.ts +7 -0
  11. package/dist/compiler/emit/borsh.js +86 -1
  12. package/dist/compiler/emit/calls.d.ts +169 -2
  13. package/dist/compiler/emit/calls.js +1170 -81
  14. package/dist/compiler/emit/cpi-core.d.ts +28 -5
  15. package/dist/compiler/emit/cpi-core.js +238 -12
  16. package/dist/compiler/emit/cpi.js +16 -16
  17. package/dist/compiler/emit/create.d.ts +3 -3
  18. package/dist/compiler/emit/create.js +33 -25
  19. package/dist/compiler/emit/expressions.js +89 -9
  20. package/dist/compiler/emit/function.js +2 -2
  21. package/dist/compiler/emit/outline.d.ts +24 -0
  22. package/dist/compiler/emit/outline.js +100 -0
  23. package/dist/compiler/emit/program.js +37 -3
  24. package/dist/compiler/emit/rbtree.d.ts +7 -0
  25. package/dist/compiler/emit/rbtree.js +142 -0
  26. package/dist/compiler/emit/shared.d.ts +43 -1
  27. package/dist/compiler/emit/shared.js +18 -2
  28. package/dist/compiler/emit/statements.d.ts +58 -1
  29. package/dist/compiler/emit/statements.js +549 -22
  30. package/dist/compiler/emit/storage.d.ts +48 -1
  31. package/dist/compiler/emit/storage.js +220 -63
  32. package/dist/compiler/emit/token.d.ts +11 -8
  33. package/dist/compiler/emit/token.js +233 -104
  34. package/dist/compiler/emit/views.d.ts +60 -0
  35. package/dist/compiler/emit/views.js +523 -0
  36. package/dist/compiler/hints.js +6 -0
  37. package/dist/compiler/idl.js +2 -1
  38. package/dist/compiler/model.d.ts +84 -4
  39. package/dist/compiler/model.js +19 -0
  40. package/dist/compiler/toolchain.d.ts +15 -0
  41. package/dist/compiler/toolchain.js +146 -11
  42. package/dist/testing-stake.d.ts +216 -0
  43. package/dist/testing-stake.js +526 -0
  44. package/dist/testing.d.ts +1 -0
  45. package/dist/testing.js +1 -0
  46. package/docs/architecture.md +9 -2
  47. package/docs/case-study-phoenix.md +226 -0
  48. package/docs/case-study-spl-stake-pool.md +122 -0
  49. package/docs/errors.md +1 -1
  50. package/docs/language.md +244 -20
  51. package/docs/migrate-from-anchor.md +1 -0
  52. package/docs/runtime.md +1 -1
  53. package/docs/security-model.md +4 -0
  54. package/docs/stability.md +33 -1
  55. package/docs/test-your-program.md +47 -0
  56. package/docs/testing.md +19 -0
  57. package/docs/troubleshooting.md +5 -2
  58. package/lib/typesol.d.ts +462 -44
  59. package/llms-full.txt +338 -26
  60. package/llms.txt +1 -1
  61. package/package.json +2 -2
  62. package/runtime/typesol_rt.h +476 -0
@@ -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") {
@@ -331,7 +335,7 @@ export class ExpressionEmitter extends StorageEmitter {
331
335
  if (ts.isArrayLiteralExpression(node))
332
336
  this.fail(node, "arrays are only allowed inline as seeds/CPI lists; declare local arrays with fixedArray<T, N>(fill)");
333
337
  if (ts.isObjectLiteralExpression(node))
334
- this.fail(node, "object literals are only allowed as the argument of emit<T>(...)");
338
+ this.fail(node, "an object literal needs a struct type here: give it one (const p: Point = { … }), or pass it where one is known (emit<T>(…), a helper's struct parameter, a struct field, storeBorsh<T>(…))");
335
339
  if (ts.isCallExpression(node)) {
336
340
  const h = this.handle(node);
337
341
  if (h)
@@ -350,6 +354,15 @@ 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;
360
+ // A BigVec's room: the elements the account holds past the struct.
361
+ if (field === "capacity" && this.peekKind(node.expression) === "vec") {
362
+ const r = this.ref(node.expression);
363
+ if (r?.vec?.big !== undefined && !r.vec.slice)
364
+ return { c: r.vec.big, type: U64 };
365
+ }
353
366
  if (field === "length") {
354
367
  if (this.isRemaining(node.expression))
355
368
  return { c: `((uint64_t)(params->ka_num - ${this.remainingBase(node.expression)}))`, type: U64 };
@@ -378,6 +391,9 @@ export class ExpressionEmitter extends StorageEmitter {
378
391
  if (l?.type.kind === "vecArg")
379
392
  return { c: `((uint64_t)${l.c}.len)`, type: U64 };
380
393
  }
394
+ // A slice of a Vec argument or the instruction data.
395
+ if (this.isVecArgView(node.expression))
396
+ return { c: `((uint64_t)${this.vecArgView(node.expression).c}.len)`, type: U64 };
381
397
  let what = "this value";
382
398
  try {
383
399
  what = this.checker.typeToString(this.checker.getTypeAtLocation(node.expression));
@@ -389,6 +405,22 @@ export class ExpressionEmitter extends StorageEmitter {
389
405
  this.fail(node, "use byteLength(s) for strings; .length is available on arrays, Vecs and remainingAccounts()");
390
406
  this.fail(node, `.length is available on arrays, Vecs, map / filter chains and remainingAccounts(), not on ${what}`);
391
407
  }
408
+ if (this.isEpochRewards(node.expression)) {
409
+ const er = this.expr(node.expression).c;
410
+ const fields = {
411
+ distributionStartingBlockHeight: { c: `(${er}.distribution_starting_block_height)`, type: U64 },
412
+ numPartitions: { c: `(${er}.num_partitions)`, type: U64 },
413
+ parentBlockhash: { c: `(&${er}.parent_blockhash)`, type: HASH },
414
+ totalPoints: { c: `(${er}.total_points)`, type: { kind: "int", name: "u128" } },
415
+ totalRewards: { c: `(${er}.total_rewards)`, type: U64 },
416
+ distributedRewards: { c: `(${er}.distributed_rewards)`, type: U64 },
417
+ active: { c: `(${er}.active != 0)`, type: BOOL },
418
+ };
419
+ const v = Object.hasOwn(fields, field) ? fields[field] : undefined;
420
+ if (!v)
421
+ this.fail(node.name, `EpochRewards has ${Object.keys(fields).join(", ")}, not ${field}`);
422
+ return v;
423
+ }
392
424
  if (this.isTxIx(node.expression)) {
393
425
  const ix = this.expr(node.expression);
394
426
  if (field === "programId")
@@ -400,6 +432,14 @@ export class ExpressionEmitter extends StorageEmitter {
400
432
  this.fail(node.name, `a TransactionInstruction has programId, accountsLength and dataLength, not ${field}`);
401
433
  }
402
434
  const h = this.handle(node.expression);
435
+ // `sysvarAt<StakeHistorySysvar>(acct)`: its count and newest epoch, as on a StakeHistorySysvar parameter.
436
+ const sysvar = h && ts.isIdentifier(node.expression) ? this.lookup(node.expression.text)?.type : undefined;
437
+ if (h && sysvar?.kind === "account" && sysvar.program?.kind === "stakeHistory") {
438
+ if (field === "count")
439
+ return { c: `ts_read_le(${h}->data, 8)`, type: U64 };
440
+ if (field === "latestEpoch")
441
+ return { c: `(${h}->data_len >= 16 && ts_read_le(${h}->data, 8) ? ts_read_le(${h}->data + 8, 8) : 0)`, type: U64 };
442
+ }
403
443
  if (h) {
404
444
  switch (field) {
405
445
  case "key":
@@ -657,7 +697,7 @@ export class ExpressionEmitter extends StorageEmitter {
657
697
  const k = this.model.constants.get(e.text);
658
698
  if (k && typeof k.value === "string")
659
699
  return k.value;
660
- if (k && typeof k.value === "object")
700
+ if (k && typeof k.value === "object" && k.value !== null)
661
701
  return base58(Uint8Array.from(k.value.pubkey));
662
702
  }
663
703
  return undefined;
@@ -669,6 +709,15 @@ export class ExpressionEmitter extends StorageEmitter {
669
709
  return v.c;
670
710
  if (converted)
671
711
  converted.yes = true;
712
+ if (v.type.kind === "option" && v.type.inner.kind === "pubkey") {
713
+ // `${key}` of an Option<Pubkey> (or Hash), narrowed or not: its base58, or "null" like JS.
714
+ const o = this.tmp("o");
715
+ const t = this.tmp("txt");
716
+ this.line(`${optC(v.type.inner)} ${o} = ${v.c};`);
717
+ this.line(`TS_Str ${t} = ts_str((const uint8_t *)"null", 4);`);
718
+ this.line(`if (${o}.some) TS_TRY(ts_base58_32((const uint8_t *)&${o}.v, &${t}));`);
719
+ return t;
720
+ }
672
721
  if (v.type.kind === "option" && (v.type.inner.kind === "int" || v.type.inner.kind === "bool")) {
673
722
  // `${opt}`: the value, or "null" like JS.
674
723
  const inner = v.type.inner;
@@ -716,6 +765,11 @@ export class ExpressionEmitter extends StorageEmitter {
716
765
  }
717
766
  /** `c ? a : b` on values: only the chosen branch runs (its checks and side effects included). */
718
767
  conditional(node, hint) {
768
+ // One of two accounts: `ephemeral ? rest.get(5n) : reserve`.
769
+ if (this.looksLikeAccountHandle(node))
770
+ return this.accountChoice(node);
771
+ if (this.looksLikeAccountHandle(node.whenTrue) || this.looksLikeAccountHandle(node.whenFalse))
772
+ this.fail(node, "choose between accounts of one kind: remaining accounts (rest.get(i), a local or RemainingAccount parameter bound to one) or AccountInfo parameters");
719
773
  if (this.looksLikeStructPlace(node.whenTrue))
720
774
  this.fail(node, "bind a choice between structs to a const: const o = c ? a.get(i) : b.get(i)");
721
775
  const cond = this.expect(this.expr(node.condition, BOOL), BOOL, node.condition);
@@ -750,7 +804,9 @@ export class ExpressionEmitter extends StorageEmitter {
750
804
  });
751
805
  this.line(`}`);
752
806
  const vt = type;
753
- if (vt.kind === "account" || vt.kind === "remaining" || vt.kind === "structRef" || vt.kind === "vecArg")
807
+ if (vt.kind === "account")
808
+ this.fail(node, "choose between accounts of one kind: remaining accounts (rest.get(i), a local or RemainingAccount parameter bound to one) or AccountInfo parameters");
809
+ if (vt.kind === "remaining" || vt.kind === "structRef" || vt.kind === "vecArg")
754
810
  this.fail(node, "choose between plain values (integers, booleans, Pubkeys, strings, options)");
755
811
  this.lines[declAt] = this.lines[declAt].replace(`/* ${t} */`, `${vt.kind === "pubkey" ? "SolPubkey" : valueC(vt)} ${t};`);
756
812
  return vt.kind === "pubkey" ? { c: `(&${t})`, type: vt } : { c: t, type: vt };
@@ -905,6 +961,11 @@ export class ExpressionEmitter extends StorageEmitter {
905
961
  // An Option<Vec<T>> argument: None leaves its view's pointer NULL (a Some, empty or not, points into the data).
906
962
  if (v.type.kind === "vecArg" && v.type.optional)
907
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 };
908
969
  if (v.type.kind !== "option" && v.type.kind !== "optionArg")
909
970
  this.fail(other, "only Option values can be compared with null");
910
971
  return { c: neg ? `((${v.c}).some != 0)` : `((${v.c}).some == 0)`, type: BOOL };
@@ -1017,9 +1078,24 @@ export class ExpressionEmitter extends StorageEmitter {
1017
1078
  const t = this.tmp();
1018
1079
  const K = ts.SyntaxKind;
1019
1080
  this.line(`${ct} ${t};`);
1020
- const overflow = `TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: arithmetic overflow")`;
1081
+ const failOverflow = `TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: arithmetic overflow")`;
1021
1082
  if (type.name === "u256")
1022
- 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")`;
1023
1099
  switch (op) {
1024
1100
  case K.PlusToken:
1025
1101
  // u64 through the runtime helpers: one compare instead of a materialized carry flag on SBF.
@@ -1035,7 +1111,7 @@ export class ExpressionEmitter extends StorageEmitter {
1035
1111
  break;
1036
1112
  case K.SlashToken:
1037
1113
  case K.PercentToken: {
1038
- this.line(`if (${right.c} == 0) TS_FAIL(TS_ERR_DIV_ZERO, "TypeSOL: division by zero");`);
1114
+ this.line(`if (${right.c} == 0) ${divZero};`);
1039
1115
  if (INT_INFO[type.name].signed)
1040
1116
  this.line(`if (${left.c} == ${intLiteral(INT_INFO[type.name].min, type.name)} && ${right.c} == -1) ${overflow};`);
1041
1117
  if (type.name === "u128")
@@ -1058,13 +1134,17 @@ export class ExpressionEmitter extends StorageEmitter {
1058
1134
  const bits = INT_INFO[type.name].bytes * 8;
1059
1135
  const sh = this.tmp("sh");
1060
1136
  const rinfo = INT_INFO[right.type.name];
1061
- 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};`);
1062
1142
  this.line(`uint64_t ${sh} = (uint64_t)(${right.c});`);
1063
1143
  if (op === K.GreaterThanGreaterThanToken)
1064
1144
  this.line(`${t} = (${ct})(${left.c} >> ${sh});`);
1065
1145
  else {
1066
1146
  this.line(`${t} = (${ct})((${unsignedC(type.name)})${left.c} << ${sh});`);
1067
- this.line(`if ((${ct})(${t} >> ${sh}) != ${left.c}) ${overflow};`);
1147
+ this.line(`if ((${ct})(${t} >> ${sh}) != ${left.c}) ${failOverflow};`);
1068
1148
  }
1069
1149
  break;
1070
1150
  }
@@ -21,7 +21,7 @@ export class FunctionEmitter extends StatementEmitter {
21
21
  this.reporter.guard(() => this.statement(stmt));
22
22
  // A helper with a result must return one; falling off the end would leave it unset.
23
23
  const end = h.returns ? ` TS_FAIL(TS_ERR_NO_RETURN, "TypeSOL: ${h.display} ended without returning a value");` : ` return SUCCESS;`;
24
- return [`${helperSignature(h)} {`, ...this.hoisted, ...this.lines, end, `}`].join("\n");
24
+ return [...this.outlinedLoops, `${helperSignature(h)} {`, ...this.hoisted, ...this.lines, end, `}`].join("\n");
25
25
  }
26
26
  emitInstruction() {
27
27
  const ix = this.ix;
@@ -483,7 +483,7 @@ export class FunctionEmitter extends StatementEmitter {
483
483
  // The Clock cache is declared first: a constraint (in the head) may read the Clock before the body does.
484
484
  const clock = this.hoisted.filter((l) => l.includes("ts_clk_ok"));
485
485
  const hoisted = this.hoisted.filter((l) => !clock.includes(l));
486
- return [head[0], ...clock, ...head.slice(1), ...hoisted, ...this.lines, ...end, `}`].join("\n");
486
+ return [...this.outlinedLoops, head[0], ...clock, ...head.slice(1), ...hoisted, ...this.lines, ...end, `}`].join("\n");
487
487
  }
488
488
  /**
489
489
  * How many statements at the start of `body` create this instruction's Init / InitIfNeeded accounts
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Reading generated C, for moving a loop into a function of its own (StatementEmitter.outlinedLoop): which names a
3
+ * piece of C uses, which it declares itself, and which are the runtime's, so that every other name it uses is one
4
+ * of the caller's variables the new function has to be given.
5
+ */
6
+ /** Identifiers, numbers and punctuation of `c`, without comments, string and character literals. */
7
+ export declare function cTokens(c: string): string[];
8
+ /** The names the C uses as variables or functions (not the fields after `.` or `->`). */
9
+ export declare function usedNames(toks: string[]): Set<string>;
10
+ /**
11
+ * The variables and labels the C declares: `T x = …;`, `T *x, *y = …;`, `T x[n];`, a `for (T i = …;` and `label:`.
12
+ * A declaration starts a statement, so a name it misses is only taken for one of the caller's (and the loop then
13
+ * stays where it is).
14
+ */
15
+ export declare function declaredNames(toks: string[]): Set<string>;
16
+ /**
17
+ * Names that are the runtime's or the SDK's, never one of a function's variables: runtime functions and macros,
18
+ * generated types and constants, helpers (`fn_…`), syscalls, other loops' functions. The emitter's own temporaries
19
+ * with a `ts_` prefix are labels (`ts_continue_12`, `ts_next_3`, `ts_ret_7`), which a loop declares itself; runtime
20
+ * functions whose names end in a number (`ts_base58_32`) are global.
21
+ */
22
+ export declare function isGlobalName(n: string): boolean;
23
+ /** A C parameter list (`TsParams *params, uint64_t p_rest`) as name → declaration. */
24
+ export declare function parameterDecls(signature: string): Map<string, string>;
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Reading generated C, for moving a loop into a function of its own (StatementEmitter.outlinedLoop): which names a
3
+ * piece of C uses, which it declares itself, and which are the runtime's, so that every other name it uses is one
4
+ * of the caller's variables the new function has to be given.
5
+ */
6
+ /** Identifiers, numbers and punctuation of `c`, without comments, string and character literals. */
7
+ export function cTokens(c) {
8
+ const bare = c.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*|"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'/g, " 0 ");
9
+ return bare.match(/[A-Za-z_]\w*|\d\w*|->|\S/g) ?? [];
10
+ }
11
+ const isIdent = (t) => t !== undefined && /^[A-Za-z_]/.test(t);
12
+ /** C keywords (and the type words of declarations, which never name a variable). */
13
+ const KEYWORDS = new Set(("auto break case char const continue default do double else enum extern float for goto if inline int long register restrict return short " +
14
+ "signed sizeof static struct switch typedef union unsigned void volatile while _Bool _Static_assert __attribute__ __asm__ __typeof__").split(" "));
15
+ /** The names the C uses as variables or functions (not the fields after `.` or `->`). */
16
+ export function usedNames(toks) {
17
+ const out = new Set();
18
+ toks.forEach((t, i) => {
19
+ if (isIdent(t) && !KEYWORDS.has(t) && toks[i - 1] !== "." && toks[i - 1] !== "->")
20
+ out.add(t);
21
+ });
22
+ return out;
23
+ }
24
+ /**
25
+ * The variables and labels the C declares: `T x = …;`, `T *x, *y = …;`, `T x[n];`, a `for (T i = …;` and `label:`.
26
+ * A declaration starts a statement, so a name it misses is only taken for one of the caller's (and the loop then
27
+ * stays where it is).
28
+ */
29
+ export function declaredNames(toks) {
30
+ const out = new Set();
31
+ for (let i = 0; i < toks.length; i++) {
32
+ const prev = toks[i - 1];
33
+ const start = i === 0 || prev === ";" || prev === "{" || prev === "}" || (prev === "(" && toks[i - 2] === "for");
34
+ if (!start || !isIdent(toks[i]))
35
+ continue;
36
+ if (toks[i + 1] === ":" && !KEYWORDS.has(toks[i])) {
37
+ out.add(toks[i]);
38
+ continue;
39
+ }
40
+ let j = i;
41
+ while (toks[j] === "const" || toks[j] === "static" || toks[j] === "struct" || toks[j] === "unsigned")
42
+ j++;
43
+ if (!isIdent(toks[j]) || KEYWORDS.has(toks[j]))
44
+ continue;
45
+ j++; // the type
46
+ for (;;) {
47
+ while (toks[j] === "*" || toks[j] === "const")
48
+ j++;
49
+ const name = toks[j];
50
+ const after = toks[j + 1];
51
+ if (!isIdent(name) || KEYWORDS.has(name) || !["=", ";", "[", ",", ")"].includes(after))
52
+ break;
53
+ out.add(name);
54
+ // Past this declarator's initializer, to the next one (a comma at depth 0) or the statement's end.
55
+ j++;
56
+ let depth = 0;
57
+ while (j < toks.length) {
58
+ const t = toks[j];
59
+ if (t === "(" || t === "[" || t === "{")
60
+ depth++;
61
+ else if (t === ")" || t === "]" || t === "}") {
62
+ if (depth === 0)
63
+ break;
64
+ depth--;
65
+ }
66
+ else if (depth === 0 && (t === "," || t === ";"))
67
+ break;
68
+ j++;
69
+ }
70
+ if (toks[j] !== ",")
71
+ break;
72
+ j++;
73
+ }
74
+ }
75
+ return out;
76
+ }
77
+ /**
78
+ * Names that are the runtime's or the SDK's, never one of a function's variables: runtime functions and macros,
79
+ * generated types and constants, helpers (`fn_…`), syscalls, other loops' functions. The emitter's own temporaries
80
+ * with a `ts_` prefix are labels (`ts_continue_12`, `ts_next_3`, `ts_ret_7`), which a loop declares itself; runtime
81
+ * functions whose names end in a number (`ts_base58_32`) are global.
82
+ */
83
+ export function isGlobalName(n) {
84
+ return (/^(?:ts_(?!(?:continue|next|ret)_\d+$)|TS_|TSS_|TSE_|TSV_|TSK_|TSF_|TSW_|Ts[A-Z]|fn_|sol_|Sol[A-Z]|SOL_|__builtin_)/.test(n) ||
85
+ /^(?:SUCCESS|NULL|true|false|abort|bool|u?int(?:8|16|32|64)_t|__u?int128_t|size_t)$/.test(n) ||
86
+ /^(?:fn|ix)_\w+__loop\d+$/.test(n) // a loop inside the loop, moved out first
87
+ );
88
+ }
89
+ /** A C parameter list (`TsParams *params, uint64_t p_rest`) as name → declaration. */
90
+ export function parameterDecls(signature) {
91
+ const inner = signature.slice(signature.indexOf("(") + 1, signature.lastIndexOf(")"));
92
+ const out = new Map();
93
+ for (const p of inner.split(",")) {
94
+ const decl = p.trim();
95
+ const name = decl.match(/(\w+)\s*$/)?.[1];
96
+ if (name)
97
+ out.set(name, decl);
98
+ }
99
+ return out;
100
+ }
@@ -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
- import { emitBorshCodecs } from "./borsh.js";
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,6 +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
+ }
71
+ // `const NATIVE_ACCOUNT_WRITES = true`: loadRawMut / storeBorsh / BigVec writes leave writability and aliasing to the
72
+ // runtime, as a native program does (read by the emitter; nothing to define in C).
73
+ const nativeWrites = model.constants.get("NATIVE_ACCOUNT_WRITES");
74
+ if (nativeWrites && typeof nativeWrites.value !== "boolean")
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`);
59
82
  // An error with code 0 must not return 0 (success): see ts_fail.
60
83
  if ([...model.errorEnums.values()].some((m) => [...m.values()].some((e) => e.code === 0)))
61
84
  out.push(`#define TS_CUSTOM_ZERO 1`);
@@ -162,14 +185,16 @@ export function emitProgram(analysis, opts = {}) {
162
185
  for (const t of model.localVecs.values())
163
186
  deps(t);
164
187
  for (const k of model.constants.values())
165
- if (typeof k.value === "object")
188
+ if (typeof k.value === "object" && k.value !== null)
166
189
  out.push(`static const SolPubkey TSK_${k.name} = {${cBytes(k.value.pubkey)}};`);
167
- out.push(...emitBorshCodecs(model));
190
+ out.push(...emitBorshCodecs(model), ...emitNativeBorshCodecs(model));
168
191
  const helpers = [...model.helpers.values()];
169
192
  for (const h of helpers)
170
193
  out.push(helperSignature(h) + ";");
171
194
  if (helpers.length)
172
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));
173
198
  out.push(...helperBodies, ...ixBodies);
174
199
  const limit = accountLimit(model);
175
200
  out.push(`_Static_assert(TS_MAX_ACCOUNTS == ${limit}, "TS_MAX_ACCOUNTS");`);
@@ -183,6 +208,8 @@ export function emitProgram(analysis, opts = {}) {
183
208
  // Above 32 accounts the CPI scratch lists are taken from the heap when first needed.
184
209
  if (limit > 32)
185
210
  out.push(` params.infos_cap = 0;`, ` params.metas = NULL;`);
211
+ if (model.ownerCache)
212
+ out.push(` params.owned = NULL;`);
186
213
  if ([...helperBodies, ...ixBodies].some((b) => /ts_claim_mut(_at)?(_rec)?\(/.test(b)))
187
214
  out.push(limit > 64 ? ` ts_memzero(params.loaded_mut, sizeof(params.loaded_mut));` : ` params.loaded_mut = 0;`);
188
215
  const fallback = model.instructions.find((ix) => ix.fallback);
@@ -211,3 +238,10 @@ export function emitProgram(analysis, opts = {}) {
211
238
  out.push(`}`);
212
239
  return out.join("\n") + "\n";
213
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
+ }