@typesol/cli 0.38.0 → 0.40.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 (61) hide show
  1. package/CHANGELOG.md +373 -2
  2. package/README.md +43 -26
  3. package/SECURITY.md +1 -1
  4. package/dist/cli.js +37 -3
  5. package/dist/compiler/analyze.d.ts +6 -11
  6. package/dist/compiler/analyze.js +331 -34
  7. package/dist/compiler/emit/alias.js +3 -2
  8. package/dist/compiler/emit/base.d.ts +7 -1
  9. package/dist/compiler/emit/base.js +2 -0
  10. package/dist/compiler/emit/borsh.js +63 -2
  11. package/dist/compiler/emit/calls.d.ts +14 -1
  12. package/dist/compiler/emit/calls.js +311 -21
  13. package/dist/compiler/emit/cpi-core.js +17 -5
  14. package/dist/compiler/emit/cpi.js +81 -27
  15. package/dist/compiler/emit/create.d.ts +7 -0
  16. package/dist/compiler/emit/create.js +27 -0
  17. package/dist/compiler/emit/expressions.d.ts +6 -0
  18. package/dist/compiler/emit/expressions.js +102 -6
  19. package/dist/compiler/emit/function.d.ts +7 -0
  20. package/dist/compiler/emit/function.js +164 -29
  21. package/dist/compiler/emit/program.js +27 -2
  22. package/dist/compiler/emit/shared.d.ts +15 -5
  23. package/dist/compiler/emit/shared.js +5 -0
  24. package/dist/compiler/emit/statements.d.ts +28 -1
  25. package/dist/compiler/emit/statements.js +270 -13
  26. package/dist/compiler/emit/storage.d.ts +10 -1
  27. package/dist/compiler/emit/storage.js +50 -11
  28. package/dist/compiler/hints.d.ts +5 -0
  29. package/dist/compiler/hints.js +88 -0
  30. package/dist/compiler/idl.d.ts +1 -1
  31. package/dist/compiler/idl.js +42 -11
  32. package/dist/compiler/index.d.ts +3 -0
  33. package/dist/compiler/index.js +6 -1
  34. package/dist/compiler/model.d.ts +47 -10
  35. package/dist/compiler/model.js +14 -4
  36. package/dist/testing.js +8 -0
  37. package/dist/tools/clientgen.js +10 -1
  38. package/dist/tools/portgen.d.ts +6 -0
  39. package/dist/tools/portgen.js +68 -17
  40. package/docs/architecture.md +5 -4
  41. package/docs/audit.md +31 -19
  42. package/docs/case-study-escrow.md +5 -5
  43. package/docs/case-study-jito-mev.md +9 -5
  44. package/docs/case-study-marginfi.md +797 -0
  45. package/docs/case-study-multisig.md +3 -3
  46. package/docs/case-study-raydium-amm.md +80 -0
  47. package/docs/case-study-raydium-clmm.md +44 -33
  48. package/docs/case-study-raydium-cp-swap.md +3 -3
  49. package/docs/cli.md +5 -5
  50. package/docs/client.md +1 -1
  51. package/docs/errors.md +13 -5
  52. package/docs/language.md +65 -32
  53. package/docs/migrate-from-anchor.md +4 -1
  54. package/docs/runtime.md +1 -1
  55. package/docs/security-model.md +2 -1
  56. package/docs/testing.md +34 -1
  57. package/docs/troubleshooting.md +6 -0
  58. package/lib/typesol.d.ts +118 -10
  59. package/package.json +9 -7
  60. package/runtime/typesol_rt.h +158 -17
  61. package/ts-plugin/index.js +24 -1
@@ -1,7 +1,7 @@
1
1
  import ts from "typescript";
2
2
  import { MAX_RETURN_DATA, calleeName, resolveScalarType, resolveValueType, structNameOf, typesolName } from "../analyze.js";
3
3
  import { INT_INFO, isScalar, optionKey, scalarSize, typeName } from "../model.js";
4
- import { U64, BOOL, cString, fixedVecC, optC, scalarC, scalarStorageC, valueC } from "./shared.js";
4
+ import { U64, BOOL, cString, fixedVecC, optC, scalarC, scalarStorageC, valueC, } from "./shared.js";
5
5
  import { CpiEmitter } from "./cpi.js";
6
6
  /**
7
7
  * Statements: variables, assignment, control flow and return.
@@ -255,6 +255,8 @@ export class StatementEmitter extends CpiEmitter {
255
255
  this.fail(stmt.initializer, "write for (const x of list): one const name, no type annotation");
256
256
  if (this.isRemaining(stmt.expression))
257
257
  this.fail(stmt.expression, "iterate remaining accounts with for (let i = 0n; i < rest.length; i++) and rest.get(i)");
258
+ if (ts.isArrayLiteralExpression(stmt.expression) && this.functionList(stmt.expression))
259
+ return this.forOfFunctions(stmt, d.name);
258
260
  // Synthetic `list.length` / `list.get(i)` nodes placed at the loop, so errors and checks point at the source.
259
261
  const f = ts.factory;
260
262
  const index = `__of${this.temp++}`;
@@ -266,7 +268,8 @@ export class StatementEmitter extends CpiEmitter {
266
268
  void place;
267
269
  const ci = this.tmp("of_i");
268
270
  const label = this.tmp("ts_continue_");
269
- this.eachElement(stmt.expression, stmt, { index, ci, next: label, alwaysNext: true }, (element) => {
271
+ const release = this.iterationClaims(stmt.statement);
272
+ this.eachElement(stmt.expression, stmt, { index, ci, next: label, alwaysNext: true, atNext: release }, (element) => {
270
273
  // The element's declaration: the source's own name (so aliasing checks find its uses) bound to the element.
271
274
  const decl = f.createVariableDeclaration(d.name, undefined, undefined, element);
272
275
  ts.setTextRange(decl, d);
@@ -280,6 +283,140 @@ export class StatementEmitter extends CpiEmitter {
280
283
  this.loops.pop();
281
284
  });
282
285
  }
286
+ /** The functions a list literal names (`[f, g]`: closures, helpers or choices), or undefined when it holds anything else. */
287
+ functionList(list) {
288
+ if (!list.elements.length)
289
+ return undefined;
290
+ const fns = [];
291
+ for (const el of list.elements) {
292
+ if (!ts.isIdentifier(el))
293
+ return undefined;
294
+ const l = this.lookup(el.text);
295
+ const f = l?.choice ?? this.functionNamed(el);
296
+ if (!f)
297
+ return undefined;
298
+ fns.push(f);
299
+ }
300
+ return fns;
301
+ }
302
+ /**
303
+ * `for (const f of [g, h]) …`: unrolled, the body once per function with f bound to it, in order. `continue` goes to
304
+ * the next function, `break` past the last (the copies sit in a do { } while (0)).
305
+ */
306
+ forOfFunctions(stmt, name) {
307
+ const fns = this.functionList(stmt.expression);
308
+ this.line(`do {`);
309
+ this.block(() => {
310
+ for (const f of fns) {
311
+ const next = this.tmp("ts_continue_");
312
+ this.line(`{`);
313
+ this.block(() => {
314
+ this.scopes.at(-1).set(name.text, "sel" in f ? { c: "", type: BOOL, mutable: false, choice: f } : { c: "", type: BOOL, mutable: false, closure: f });
315
+ this.loops.push(next);
316
+ try {
317
+ this.body(stmt.statement);
318
+ }
319
+ finally {
320
+ this.loops.pop();
321
+ }
322
+ });
323
+ this.line(`}`);
324
+ this.line(`${next}:;`);
325
+ }
326
+ });
327
+ this.line(`} while (0);`);
328
+ }
329
+ /**
330
+ * `c ? f : h` where both sides name functions (or other choices): the condition is evaluated here, once, into a C bool,
331
+ * and a call later expands only the chosen function. Undefined when the expression is not such a choice.
332
+ */
333
+ functionChoice(init, name) {
334
+ const strip = (x) => (ts.isParenthesizedExpression(x) ? strip(x.expression) : x);
335
+ const e = strip(init);
336
+ if (!ts.isConditionalExpression(e))
337
+ return undefined;
338
+ const inline = (x) => ts.isArrowFunction(strip(x)) || ts.isFunctionExpression(strip(x));
339
+ // What a side names, decided from the names alone (nothing is evaluated): a function, a choice, or neither.
340
+ const named = (x) => {
341
+ const y = strip(x);
342
+ if (ts.isIdentifier(y))
343
+ return !!(this.lookup(y.text)?.choice ?? this.functionNamed(y));
344
+ return ts.isConditionalExpression(y) && named(y.whenTrue) && named(y.whenFalse);
345
+ };
346
+ const fnSide = (x) => {
347
+ const y = strip(x);
348
+ return named(y) || (ts.isConditionalExpression(y) && (fnSide(y.whenTrue) || fnSide(y.whenFalse)));
349
+ };
350
+ if (!fnSide(e.whenTrue) && !fnSide(e.whenFalse)) {
351
+ if (inline(e.whenTrue) && inline(e.whenFalse))
352
+ this.fail(e, "declare each function with const first, then choose between them: const g = c ? f : h");
353
+ return undefined; // a choice between values: an ordinary conditional
354
+ }
355
+ if (inline(e.whenTrue) || inline(e.whenFalse))
356
+ this.fail(e, "declare each function with const first, then choose between them: const g = c ? f : h");
357
+ if (!named(e))
358
+ this.fail(e, "choose between functions on both sides: const g = c ? f : h");
359
+ return this.bindChoice(e, name);
360
+ }
361
+ /**
362
+ * Evaluate a function choice's conditions into C bools, as JS does: the outer one first, an inner one only when its
363
+ * side is taken (`a ? f : b ? g : h` reads b only when a is false). Its sides are known to name functions.
364
+ */
365
+ bindChoice(e, name, guard) {
366
+ const strip = (x) => (ts.isParenthesizedExpression(x) ? strip(x.expression) : x);
367
+ const sel = `l_${name}_sel_${this.temp++}`;
368
+ if (guard === undefined) {
369
+ const cond = this.expect(this.expr(e.condition, BOOL), BOOL, e.condition);
370
+ this.line(`bool ${sel} = ${cond.c};`);
371
+ }
372
+ else {
373
+ this.line(`bool ${sel} = false;`);
374
+ this.line(`if (${guard}) {`);
375
+ this.block(() => {
376
+ const cond = this.expect(this.expr(e.condition, BOOL), BOOL, e.condition);
377
+ this.line(`${sel} = ${cond.c};`);
378
+ });
379
+ this.line(`}`);
380
+ }
381
+ const within = (taken) => (guard === undefined ? taken : `(${guard}) && ${taken}`);
382
+ const side = (x, taken) => {
383
+ const y = strip(x);
384
+ if (ts.isIdentifier(y))
385
+ return (this.lookup(y.text)?.choice ?? this.functionNamed(y));
386
+ return this.bindChoice(y, name, within(taken));
387
+ };
388
+ return { sel, whenTrue: side(e.whenTrue, sel), whenFalse: side(e.whenFalse, `!${sel}`) };
389
+ }
390
+ /** A call of a function chosen at run time: an if / else, each side expanding its function with the same arguments. */
391
+ callChoice(choice, args, node) {
392
+ const t = this.tmp("chosen");
393
+ const declAt = this.lines.length;
394
+ this.line(`/* ${t} */`);
395
+ let type;
396
+ let anyValue = false;
397
+ const branch = (f) => {
398
+ const v = "sel" in f ? this.callChoice(f, args, node) : this.expandClosure(f, args, node);
399
+ if (!v)
400
+ return;
401
+ anyValue = true;
402
+ if (!type)
403
+ type = v.type;
404
+ const w = this.ownedString(this.expect(v, type, node));
405
+ this.line(w.type.kind === "pubkey" ? `${t} = *(${w.c});` : `${t} = ${w.c};`);
406
+ };
407
+ this.line(`if (${choice.sel}) {`);
408
+ this.block(() => branch(choice.whenTrue));
409
+ this.line(`} else {`);
410
+ this.block(() => branch(choice.whenFalse));
411
+ this.line(`}`);
412
+ if (!anyValue || !type)
413
+ return undefined;
414
+ const vt = type;
415
+ if (vt.kind === "account" || vt.kind === "remaining" || vt.kind === "structRef" || vt.kind === "vecArg")
416
+ this.fail(node, "functions chosen at run time return plain values (integers, booleans, Pubkeys, strings, options)");
417
+ this.lines[declAt] = this.lines[declAt].replace(`/* ${t} */`, `${vt.kind === "pubkey" ? "SolPubkey" : valueC(vt)} ${t};`);
418
+ return vt.kind === "pubkey" ? { c: `(&${t})`, type: vt } : { c: t, type: vt };
419
+ }
283
420
  /** The function an identifier names (a closure, a local function or a helper), as something to expand; else undefined. */
284
421
  functionNamed(id) {
285
422
  const l = this.lookup(id.text);
@@ -359,8 +496,31 @@ export class StatementEmitter extends CpiEmitter {
359
496
  if (st.kind === "map") {
360
497
  const ret = st.fn.body && !ts.isBlock(st.fn.body) ? st.fn.body : undefined;
361
498
  const bare = ret && ts.isParenthesizedExpression(ret) ? ret.expression : ret;
362
- if (bare && ts.isObjectLiteralExpression(bare))
363
- this.fail(st.fn, "a map to structs is stored, with the struct type: const ys: FixedVec<MyStruct, N> = xs.map((x) => ({ … }))");
499
+ if (bare && ts.isObjectLiteralExpression(bare)) {
500
+ // A map to structs inside a chain: each element built in a struct of its own, which the next stage reads.
501
+ const sname = st.fn.type ? structNameOf(st.fn.type, this.scope) : undefined;
502
+ const S = sname ? this.model.structs.get(sname) : undefined;
503
+ if (!S)
504
+ this.fail(st.fn, "name the struct the callback builds: xs.map((x): MyStruct => ({ … })) (or store the list: const ys: FixedVec<MyStruct, N> = xs.map(…))");
505
+ if (S.size === undefined || S.vec)
506
+ this.fail(st.fn, `${S.name} has variable-size fields and cannot be built in a chain`);
507
+ const closure = { node: st.fn, name: "map's callback", scopes: [...this.scopes], env: this.envNow(), imports: this.scope.imports };
508
+ const sc = this.tmp("lm_s");
509
+ this.line(`TSS_${S.name} ${sc}__v;`);
510
+ this.line(`ts_memzero(&${sc}__v, sizeof(${sc}__v));`);
511
+ this.expandClosure(closure, [element, idx].slice(0, st.fn.parameters.length), st.fn, {
512
+ lv: `${sc}__v`,
513
+ type: { kind: "struct", name: S.name },
514
+ writable: true,
515
+ });
516
+ this.line(`TSS_${S.name} *${sc} = &${sc}__v;`);
517
+ const id = `__ls${this.temp++}`;
518
+ this.scopes
519
+ .at(-1)
520
+ .set(id, { c: sc, type: { kind: "structRef", struct: S.name, writable: true }, mutable: false, paths: [`@${sc}`], owned: true });
521
+ element = place(f.createIdentifier(id));
522
+ continue;
523
+ }
364
524
  }
365
525
  const closure = { node: st.fn, name: `${st.kind}'s callback`, scopes: [...this.scopes], env: this.envNow(), imports: this.scope.imports };
366
526
  const v = this.expandClosure(closure, [element, idx].slice(0, st.fn.parameters.length), st.fn);
@@ -391,6 +551,7 @@ export class StatementEmitter extends CpiEmitter {
391
551
  body(element, idx);
392
552
  if (next && (names.alwaysNext || counters.length))
393
553
  this.line(`${next}:;`);
554
+ names.atNext?.();
394
555
  this.line(`${ci}++;`);
395
556
  });
396
557
  this.line(`}`);
@@ -509,12 +670,14 @@ export class StatementEmitter extends CpiEmitter {
509
670
  const c = this.expect(this.expr(cond, BOOL), BOOL, cond);
510
671
  this.line(`if (!${c.c}) break;`);
511
672
  }
673
+ const release = this.iterationClaims(body);
512
674
  this.loops.push(label);
513
675
  this.line(`{`);
514
676
  this.block(() => this.body(body));
515
677
  this.line(`}`);
516
678
  this.loops.pop();
517
679
  this.line(`${label}:;`);
680
+ release();
518
681
  if (step)
519
682
  this.expressionStatement(step, false);
520
683
  });
@@ -580,7 +743,7 @@ export class StatementEmitter extends CpiEmitter {
580
743
  params.set(name, { c: c2, type, mutable: true });
581
744
  });
582
745
  const declared = fn.type && fn.type.kind !== ts.SyntaxKind.VoidKeyword ? resolveValueType(fn.type, calleeScope) : undefined;
583
- if (fn.type && fn.type.kind !== ts.SyntaxKind.VoidKeyword && !declared)
746
+ if (fn.type && fn.type.kind !== ts.SyntaxKind.VoidKeyword && !declared && !into)
584
747
  this.fail(fn.type, "closures return integers, booleans, Pubkeys, strings, enums or Options");
585
748
  const frame = {
586
749
  label: this.tmp("ts_ret_"),
@@ -840,17 +1003,93 @@ export class StatementEmitter extends CpiEmitter {
840
1003
  const label = this.tmp("ts_continue_");
841
1004
  this.line(`while (1) {`);
842
1005
  this.block(() => {
1006
+ const release = this.iterationClaims(stmt.statement);
843
1007
  this.loops.push(label);
844
1008
  this.line(`{`);
845
1009
  this.block(() => this.body(stmt.statement));
846
1010
  this.line(`}`);
847
1011
  this.loops.pop();
848
1012
  this.line(`${label}:;`);
1013
+ release();
849
1014
  const c = this.expect(this.expr(stmt.expression, BOOL), BOOL, stmt.expression);
850
1015
  this.line(`if (!${c.c}) break;`);
851
1016
  });
852
1017
  this.line(`}`);
853
1018
  }
1019
+ /**
1020
+ * The loadAccountMut calls of a loop body whose views end with the iteration: `const v = loadAccountMut<T>(…)` in the
1021
+ * body (not in a loop nested in it, which handles its own), with `v` never assigned or copied to a name, returned, put in
1022
+ * an object, or used in a function written in the body (other than a const closure of the body that stays in it). Their claims are recorded (declared here) and dropped at each iteration's end, so a
1023
+ * later iteration may load the same account again: the earlier view is out of scope by then. Returns the release.
1024
+ */
1025
+ iterationClaims(body) {
1026
+ const sites = [];
1027
+ const isLoop = (n) => ts.isForStatement(n) || ts.isForOfStatement(n) || ts.isForInStatement(n) || ts.isWhileStatement(n) || ts.isDoStatement(n);
1028
+ const isFunction = (n) => ts.isArrowFunction(n) || ts.isFunctionExpression(n) || ts.isFunctionDeclaration(n);
1029
+ // A function written in the body may use the view when it is a const of the body that does not escape either (a
1030
+ // closure TypeSOL expands where it is called, within the iteration).
1031
+ const localFunction = (n, seen) => {
1032
+ const d = n.parent;
1033
+ if (!d || !ts.isVariableDeclaration(d) || d.initializer !== n || !ts.isIdentifier(d.name))
1034
+ return false;
1035
+ const list = d.parent;
1036
+ if (!ts.isVariableDeclarationList(list) || !(list.flags & ts.NodeFlags.Const))
1037
+ return false;
1038
+ return !seen.has(d.name.text) && !escapes(d.name.text, new Set([...seen, d.name.text]));
1039
+ };
1040
+ const escapes = (name, seen = new Set([name])) => {
1041
+ let found = false;
1042
+ const scan = (n, inFunction) => {
1043
+ if (found)
1044
+ return;
1045
+ if (ts.isIdentifier(n) && n.text === name) {
1046
+ const p = n.parent;
1047
+ if (inFunction)
1048
+ found = true;
1049
+ else if (p && ts.isBinaryExpression(p) && p.right === n && p.operatorToken.kind === ts.SyntaxKind.EqualsToken)
1050
+ found = true;
1051
+ else if (p && ts.isReturnStatement(p))
1052
+ found = true;
1053
+ else if (p && ts.isVariableDeclaration(p) && p.initializer === n)
1054
+ found = true;
1055
+ else if (p && (ts.isShorthandPropertyAssignment(p) || (ts.isPropertyAssignment(p) && p.initializer === n)))
1056
+ found = true;
1057
+ }
1058
+ ts.forEachChild(n, (c) => scan(c, inFunction || (isFunction(n) && !localFunction(n, seen))));
1059
+ };
1060
+ scan(body, false);
1061
+ return found;
1062
+ };
1063
+ const visit = (n) => {
1064
+ if (n !== body && (isLoop(n) || isFunction(n)))
1065
+ return;
1066
+ if (ts.isVariableDeclarationList(n) && n.flags & ts.NodeFlags.Const)
1067
+ for (const d of n.declarations) {
1068
+ let init = d.initializer;
1069
+ while (init && ts.isParenthesizedExpression(init))
1070
+ init = init.expression;
1071
+ if (ts.isIdentifier(d.name) &&
1072
+ init &&
1073
+ ts.isCallExpression(init) &&
1074
+ ts.isIdentifier(init.expression) &&
1075
+ init.expression.text === "loadAccountMut" &&
1076
+ !escapes(d.name.text))
1077
+ sites.push(init);
1078
+ }
1079
+ ts.forEachChild(n, visit);
1080
+ };
1081
+ visit(body);
1082
+ const slots = sites.map((call) => {
1083
+ const slot = this.tmp("claim");
1084
+ this.line(`uint64_t ${slot} = (uint64_t)-1;`);
1085
+ this.claimSlots.set(call, slot);
1086
+ return slot;
1087
+ });
1088
+ return () => {
1089
+ for (const slot of slots)
1090
+ this.line(`ts_release_mut(params, &${slot});`);
1091
+ };
1092
+ }
854
1093
  body(stmt) {
855
1094
  if (ts.isBlock(stmt))
856
1095
  stmt.statements.forEach((s) => this.reporter.guard(() => this.statement(s)));
@@ -895,6 +1134,13 @@ export class StatementEmitter extends CpiEmitter {
895
1134
  // A function as a value: another name for one (`const h = g`), or the one a function returns (`adder(5n)`).
896
1135
  const made = ts.isCallExpression(init) ? this.madeFunction(init) : undefined;
897
1136
  const alias = ts.isIdentifier(init) ? this.functionNamed(init) : undefined;
1137
+ const choice = this.functionChoice(init, name);
1138
+ if (choice) {
1139
+ if (mutable)
1140
+ this.fail(d, "bind functions with const");
1141
+ this.scopes.at(-1).set(name, { c: "", type: BOOL, mutable: false, choice });
1142
+ continue;
1143
+ }
898
1144
  if (made || alias) {
899
1145
  if (mutable)
900
1146
  this.fail(d, "bind functions with const");
@@ -949,14 +1195,18 @@ export class StatementEmitter extends CpiEmitter {
949
1195
  this.scopes.at(-1).set(name, { c, type: t, mutable });
950
1196
  continue;
951
1197
  }
952
- if (fn === "loadAccount" || fn === "loadAccountMut" || fn === "loadForeign") {
1198
+ if (fn === "loadAccount" || fn === "loadAccountMut" || fn === "loadForeign" || fn === "loadRaw" || fn === "loadRawMut") {
953
1199
  if (mutable)
954
1200
  this.fail(d, "bind loaded accounts with const");
955
- const t = fn === "loadForeign" ? this.loadForeign(init) : this.loadAccount(init, fn === "loadAccountMut");
1201
+ const t = fn === "loadForeign"
1202
+ ? this.loadForeign(init)
1203
+ : fn === "loadRaw" || fn === "loadRawMut"
1204
+ ? this.loadRaw(init, fn === "loadRawMut")
1205
+ : this.loadAccount(init, fn === "loadAccountMut");
956
1206
  this.line(`${valueC(t.type)}${c} = ${t.c};`);
957
1207
  // The account it views, kept to pass the struct on to a helper that takes Account<T> / Mut<T>.
958
1208
  let loaded;
959
- if (fn !== "loadForeign" && t.type.kind === "structRef") {
1209
+ if ((fn === "loadAccount" || fn === "loadAccountMut") && t.type.kind === "structRef") {
960
1210
  // The view is `((TSS_T *)(h->data + 8))` over a `TsAccount *h` that stays in scope with it.
961
1211
  const h = /^\(\(TSS_\w+ \*\)\((\w+)->data \+ 8\)\)$/.exec(t.c)?.[1];
962
1212
  if (h)
@@ -1007,9 +1257,11 @@ export class StatementEmitter extends CpiEmitter {
1007
1257
  if (structType.size === undefined || structType.vec)
1008
1258
  this.fail(d.type, `${structType.name} has variable-size fields and cannot be a local`);
1009
1259
  this.line(`TSS_${structType.name} ${c}__v;`);
1010
- this.writeAggregate({ lv: `${c}__v`, type: { kind: "struct", name: structType.name }, writable: true }, init);
1260
+ this.writeAggregate({ lv: `${c}__v`, type: { kind: "struct", name: structType.name }, writable: true }, init, true);
1011
1261
  this.line(`TSS_${structType.name} *${c} = &${c}__v;`);
1012
- this.scopes.at(-1).set(name, { c, type: { kind: "structRef", struct: structType.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d });
1262
+ this.scopes
1263
+ .at(-1)
1264
+ .set(name, { c, type: { kind: "structRef", struct: structType.name, writable: true }, mutable: false, paths: [`@${c}`], decl: d, owned: true });
1013
1265
  continue;
1014
1266
  }
1015
1267
  // Data enums: `const a: Action = { kind: "X", ... }` builds a local; `const a = acct.action` aliases storage.
@@ -1046,12 +1298,15 @@ export class StatementEmitter extends CpiEmitter {
1046
1298
  if (mutable)
1047
1299
  this.fail(d, "bind struct references with const");
1048
1300
  this.line(`TSS_${target.struct} *${c} = ${target.ptr};`);
1301
+ // A struct a helper returned lives in a local this function owns, not in account data.
1302
+ const owned = ts.isCallExpression(init) && !!this.helperOf(init);
1049
1303
  this.scopes.at(-1).set(name, {
1050
1304
  c,
1051
1305
  type: { kind: "structRef", struct: target.struct, writable: target.writable },
1052
1306
  mutable: false,
1053
- paths: this.pathsOf(init),
1307
+ paths: owned ? [`@${c}`] : this.pathsOf(init),
1054
1308
  decl: d,
1309
+ ...(owned ? { owned } : {}),
1055
1310
  });
1056
1311
  continue;
1057
1312
  }
@@ -1069,7 +1324,7 @@ export class StatementEmitter extends CpiEmitter {
1069
1324
  if (type.kind === "remaining") {
1070
1325
  if (mutable)
1071
1326
  this.fail(d, "bind remainingAccounts() with const");
1072
- this.scopes.at(-1).set(name, { c: "", type, mutable: false });
1327
+ this.scopes.at(-1).set(name, { c: v.c, type, mutable: false });
1073
1328
  continue;
1074
1329
  }
1075
1330
  if ((type.kind === "account" || type.kind === "structRef") && mutable)
@@ -1078,7 +1333,9 @@ export class StatementEmitter extends CpiEmitter {
1078
1333
  this.line(`SolPubkey ${c} = *(${v.c});`);
1079
1334
  else
1080
1335
  this.line(`${valueC(type)}${type.kind === "account" ? "" : " "}${c} = ${this.ownedString(v).c};`);
1081
- this.scopes.at(-1).set(name, { c, type, mutable });
1336
+ // A struct a helper returned lives in a local this function owns, not in account data.
1337
+ const owned = type.kind === "structRef" && ts.isCallExpression(init) && !!this.helperOf(init);
1338
+ this.scopes.at(-1).set(name, { c, type, mutable, ...(owned ? { paths: [`@${c}`], owned } : {}) });
1082
1339
  }
1083
1340
  }
1084
1341
  /**
@@ -33,6 +33,11 @@ export declare abstract class StorageEmitter extends AliasEmitter {
33
33
  };
34
34
  /** Resolve an expression to a storage location, if it names one. */
35
35
  protected ref(node: ts.Expression): Ref | undefined;
36
+ /**
37
+ * The value of an Option<FixedArray> / Option<Struct> place TypeScript has narrowed to Some: the place inside it.
38
+ * An empty option aborts (5108), the backstop of the narrowing.
39
+ */
40
+ protected someValue(r: Ref): Ref;
36
41
  /** An SPL COption<Pubkey> (u32 tag + 32 bytes) at `at`, as an Option<Pubkey> value. */
37
42
  protected coptionKey(at: string): Value;
38
43
  /** Why a place cannot be written, naming what to change. */
@@ -55,7 +60,11 @@ export declare abstract class StorageEmitter extends AliasEmitter {
55
60
  */
56
61
  /** A whole struct account copied as a value (`return vault`, `info = vault`): fixed-size structs only. */
57
62
  private wholeAccount;
58
- protected writeAggregate(target: Ref, valueNode: ts.Expression): void;
63
+ /**
64
+ * Write an aggregate value into `target`. `fresh`: the target is a value just declared (or a temporary), which no
65
+ * expression can read yet, so a literal is built in it directly rather than in a temporary first.
66
+ */
67
+ protected writeAggregate(target: Ref, valueNode: ts.Expression, fresh?: boolean): void;
59
68
  /** The Vec view of a FixedVec stored at `lv` (`{ len, items[cap] }`). */
60
69
  protected fixedVec(lv: string, elem: FieldType, cap: number): NonNullable<Ref["vec"]>;
61
70
  /** A heap Vec (a Vec<T> in a `@layout borsh` struct) at `lv`: `{ len, cap, items }`, grown by ts_hvec_reserve. */
@@ -174,6 +174,9 @@ export class StorageEmitter extends AliasEmitter {
174
174
  return { lv: l.c, type: l.type, writable: !l.readonly };
175
175
  if (l && l.type.kind === "vec")
176
176
  return this.withFixedVec({ lv: l.c, type: l.type, writable: true });
177
+ // An Option<struct> instruction argument: read like an Option<struct> field.
178
+ if (l && l.type.kind === "optionArg")
179
+ return { lv: l.c, type: l.type.option, writable: false };
177
180
  // A struct loaded from a remaining account.
178
181
  if (l && l.type.kind === "structRef")
179
182
  return { lv: `(*${l.c})`, type: { kind: "struct", name: l.type.struct }, writable: l.type.writable };
@@ -309,7 +312,9 @@ export class StorageEmitter extends AliasEmitter {
309
312
  const idx = this.index(node.arguments[0], `(uint64_t)${l.c}.len`);
310
313
  return { lv: `((${fieldC(l.type.elem)} *)${l.c}.ptr)[${idx}]`, type: l.type.elem, writable: false };
311
314
  }
312
- const base = this.ref(node.expression.expression);
315
+ let base = this.ref(node.expression.expression);
316
+ if (base && base.type.kind === "option" && base.type.inner.kind === "array")
317
+ base = this.someValue(base);
313
318
  if (base && (base.type.kind === "array" || base.type.kind === "vec")) {
314
319
  if (node.arguments.length !== 1)
315
320
  this.fail(node, "get(index) takes one argument");
@@ -320,6 +325,15 @@ export class StorageEmitter extends AliasEmitter {
320
325
  }
321
326
  return undefined;
322
327
  }
328
+ /**
329
+ * The value of an Option<FixedArray> / Option<Struct> place TypeScript has narrowed to Some: the place inside it.
330
+ * An empty option aborts (5108), the backstop of the narrowing.
331
+ */
332
+ someValue(r) {
333
+ const t = r.type;
334
+ this.line(`if (!${r.lv}.some) TS_FAIL(TS_ERR_UNWRAP, "TypeSOL: option is empty");`);
335
+ return this.withFixedVec({ ...r, lv: `${r.lv}.v`, type: t.inner, path: undefined, vec: undefined });
336
+ }
323
337
  /** An SPL COption<Pubkey> (u32 tag + 32 bytes) at `at`, as an Option<Pubkey> value. */
324
338
  coptionKey(at) {
325
339
  const opt = { kind: "option", inner: PUBKEY };
@@ -453,9 +467,25 @@ export class StorageEmitter extends AliasEmitter {
453
467
  this.assertUsable(a, node);
454
468
  return { lv: `(*d_${a.name})`, type: { kind: "struct", name: a.kind.struct.name }, writable: false };
455
469
  }
456
- writeAggregate(target, valueNode) {
470
+ /**
471
+ * Write an aggregate value into `target`. `fresh`: the target is a value just declared (or a temporary), which no
472
+ * expression can read yet, so a literal is built in it directly rather than in a temporary first.
473
+ */
474
+ writeAggregate(target, valueNode, fresh = false) {
457
475
  if (ts.isParenthesizedExpression(valueNode))
458
- return this.writeAggregate(target, valueNode.expression);
476
+ return this.writeAggregate(target, valueNode.expression, fresh);
477
+ // `fixedArray<T, N>(fill)` as a field's value: filled in place.
478
+ if (target.type.kind === "array" && ts.isCallExpression(valueNode) && this.exportName(valueNode.expression) === "fixedArray") {
479
+ const [elemNode, lenNode] = valueNode.typeArguments ?? [];
480
+ const elem = elemNode && resolveScalarType(elemNode, this.scope);
481
+ const len = lenNode && ts.isLiteralTypeNode(lenNode) && ts.isNumericLiteral(lenNode.literal) ? Number(lenNode.literal.text) : NaN;
482
+ if (!elem || !sameType(elem, target.type.elem) || len !== target.type.len || valueNode.arguments.length !== 1)
483
+ this.fail(valueNode, `expected fixedArray<${typeName(target.type.elem)}, ${target.type.len}>(fill)`);
484
+ const fill = this.expect(this.expr(valueNode.arguments[0], elem), elem, valueNode.arguments[0]);
485
+ const i = this.tmp("i");
486
+ this.line(`for (uint64_t ${i} = 0; ${i} < ${len}; ${i}++) ${this.writeStorage({ lv: `${target.lv}[${i}]`, type: elem, writable: true }, fill.c)};`);
487
+ return;
488
+ }
459
489
  if (target.type.kind === "option" && target.type.inner.kind === "struct") {
460
490
  if (valueNode.kind === ts.SyntaxKind.NullKeyword) {
461
491
  this.line(`${target.lv}.some = 0;`);
@@ -568,23 +598,26 @@ export class StorageEmitter extends AliasEmitter {
568
598
  for (const k of given.keys())
569
599
  if (!s.fields.some((f) => f.name === k))
570
600
  this.fail(valueNode, `${s.name} has no field "${k}"`);
571
- // Build in a temporary so `p = { x: p.y, y: p.x }` reads the old values.
572
- const tmp = this.tmp("st");
573
- this.line(`TSS_${s.name} ${tmp};`);
601
+ // Build in a temporary so `p = { x: p.y, y: p.x }` reads the old values (a fresh target has none to read).
602
+ const tmp = fresh ? undefined : this.tmp("st");
603
+ if (tmp)
604
+ this.line(`TSS_${s.name} ${tmp};`);
605
+ const into = tmp ?? target.lv;
574
606
  for (const f of s.fields)
575
607
  if (!given.has(f.name))
576
608
  this.fail(valueNode, `missing field "${f.name}" of ${s.name}`);
577
609
  // Fields are evaluated in source order, as in JS, straight into the temporary.
578
610
  for (const [name, e] of given) {
579
611
  const f = s.fields.find((x) => x.name === name);
580
- const sub = { lv: `${tmp}.${f.name}`, type: f.type, writable: true };
612
+ const sub = { lv: `${into}.${f.name}`, type: f.type, writable: true };
581
613
  const vt = this.storageValueType(f.type);
582
614
  if (vt)
583
615
  this.line(this.writeStorage(sub, this.expect(this.expr(e, vt), vt, e).c) + ";");
584
616
  else
585
- this.writeAggregate(sub, e);
617
+ this.writeAggregate(sub, e, true);
586
618
  }
587
- this.line(`ts_memcpy(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
619
+ if (tmp)
620
+ this.line(`ts_memcpy(&${target.lv}, &${tmp}, sizeof(${tmp}));`);
588
621
  return;
589
622
  }
590
623
  if (ts.isConditionalExpression(valueNode)) {
@@ -632,7 +665,13 @@ export class StorageEmitter extends AliasEmitter {
632
665
  }
633
666
  if (heap)
634
667
  this.fail(valueNode, `expected a ${typeName(target.type)}: a Vec argument or another list of the same elements`);
635
- const src = this.ref(valueNode) ?? this.wholeAccount(valueNode);
668
+ let src = this.ref(valueNode) ?? this.wholeAccount(valueNode);
669
+ // A narrowed Option<FixedArray> / Option<Struct> place (`x.tiers !== null` before it): its value.
670
+ if (src &&
671
+ src.type.kind === "option" &&
672
+ (src.type.inner.kind === "array" || src.type.inner.kind === "struct") &&
673
+ sameType(src.type.inner, target.type))
674
+ src = this.someValue(src);
636
675
  if (!src || !sameType(src.type, target.type))
637
676
  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" : ""}`);
638
677
  // Same-typed places are either distinct or identical (`a.p = a.p`); ts_copy skips the latter.
@@ -719,7 +758,7 @@ export class StorageEmitter extends AliasEmitter {
719
758
  case "enum":
720
759
  return scalarSize(t);
721
760
  case "option":
722
- return 1 + (t.inner.kind === "struct" ? this.fieldBytes(t.inner) : scalarSize(t.inner));
761
+ return 1 + (t.inner.kind === "struct" || t.inner.kind === "array" ? this.fieldBytes(t.inner) : scalarSize(t.inner));
723
762
  case "dataEnum":
724
763
  return 1 + this.model.dataEnums.get(t.name).payload;
725
764
  case "fstring":
@@ -0,0 +1,5 @@
1
+ import ts from "typescript";
2
+ /** A sentence to add to a TypeScript diagnostic, or undefined when TypeScript's own message says enough. */
3
+ export declare function hintForTypeScript(d: ts.Diagnostic, message: string, libPath: string): string | undefined;
4
+ /** "ClassDeclaration is not supported …" in words a TypeScript developer recognizes. */
5
+ export declare function unsupportedSyntax(kind: ts.SyntaxKind, where: "top level" | "expression"): string;
@@ -0,0 +1,88 @@
1
+ // What to write instead, for the TypeScript errors and the syntax a newcomer to TypeSOL meets first. TypeScript's own
2
+ // suggestions (install @types/node, add the dom library, return a Promise) point the wrong way for a Solana program.
3
+ import { readFileSync } from "node:fs";
4
+ import ts from "typescript";
5
+ let libNames;
6
+ /** The functions and values lib/typesol.d.ts exports, so "Cannot find name 'log'" can say where log comes from. */
7
+ function typesolExports(libPath) {
8
+ if (!libNames) {
9
+ libNames = new Set();
10
+ try {
11
+ for (const m of readFileSync(libPath, "utf8").matchAll(/^export declare (?:function|const) (\w+)/gm))
12
+ libNames.add(m[1]);
13
+ }
14
+ catch {
15
+ // Without the library file there is nothing to suggest.
16
+ }
17
+ }
18
+ return libNames;
19
+ }
20
+ const MINMAX_HINT = 'Math works on numbers; use min(a, b) and max(a, b) from "typesol", which take bigints';
21
+ const BIGINT_HINT = "integers (u64, u32, i64 …) are bigint in TypeSOL: write 1n, not 1, and take u64, not number";
22
+ /** A sentence to add to a TypeScript diagnostic, or undefined when TypeScript's own message says enough. */
23
+ export function hintForTypeScript(d, message, libPath) {
24
+ // The whole source line, so a Math.max(…) is seen even when TypeScript marks only the assignment around it.
25
+ let line = "";
26
+ if (d.file && d.start !== undefined) {
27
+ const text = d.file.text;
28
+ const from = text.lastIndexOf("\n", d.start - 1) + 1;
29
+ const to = text.indexOf("\n", d.start);
30
+ line = text.slice(from, to < 0 ? undefined : to);
31
+ }
32
+ // Cannot find name 'x' (2304), with TypeScript's advice to install @types/node (2580, 2591), a test runner's types
33
+ // (2582, 2593) or the dom library (2584).
34
+ const name = /^Cannot find name '([^']+)'/.exec(message)?.[1];
35
+ if (name !== undefined) {
36
+ if (name === "console")
37
+ return 'a program writes logs with log("…") from "typesol"';
38
+ if (name === "Math")
39
+ return MINMAX_HINT;
40
+ if (typesolExports(libPath).has(name))
41
+ return `import { ${name} } from "typesol"`;
42
+ return undefined;
43
+ }
44
+ switch (d.code) {
45
+ case 2367: // This comparison appears to be unintentional because the types 'bigint' and 'number' have no overlap.
46
+ case 2365: // Operator '+=' cannot be applied to types 'bigint' and 'number'.
47
+ case 2322: // Type 'number' is not assignable to type 'bigint'.
48
+ case 2345: // Argument of type 'bigint' is not assignable to parameter of type 'number'.
49
+ if (/\bMath\.\w+\(/.test(line))
50
+ return MINMAX_HINT;
51
+ if (/\bbigint\b/.test(message) && (/\bnumber\b/.test(message) || /'-?\d+'/.test(message)))
52
+ return BIGINT_HINT;
53
+ return undefined;
54
+ case 7053: // Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'FixedArray<…>'.
55
+ case 7015: // Element implicitly has an 'any' type because index expression is not of type 'number'.
56
+ if (/FixedArray|Vec|FixedVec|FixedString/.test(message))
57
+ return "indexing with [ ] is not supported: use .get(i) and .set(i, value), with i a bigint (0n)";
58
+ return undefined;
59
+ case 1064: // The return type of an async function … must be the global Promise<T> type.
60
+ return "async is not supported: an instruction runs start to finish within one call; remove async";
61
+ case 2540: // Cannot assign to 'x' because it is a read-only property.
62
+ return "to change an account, take it as Mut<T> (Mut<Signer> for a signer whose lamports change)";
63
+ default:
64
+ return undefined;
65
+ }
66
+ }
67
+ /** Plain words for the syntax kinds the compiler refuses, and what to use instead. */
68
+ const SYNTAX = {
69
+ [ts.SyntaxKind.ClassDeclaration]: "classes are not supported: describe account data with an interface and logic with functions",
70
+ [ts.SyntaxKind.ElementAccessExpression]: "indexing with [ ] is not supported: use .get(i) and .set(i, value) (i is a bigint)",
71
+ [ts.SyntaxKind.TemplateExpression]: "template strings are not supported: log the parts one by one, or use an error enum member for a message",
72
+ [ts.SyntaxKind.SpreadElement]: "spread (...) is not supported: copy the fields one by one",
73
+ [ts.SyntaxKind.ArrayLiteralExpression]: "array literals are only allowed inline as seeds or CPI lists; declare local arrays with fixedArray<T, N>(fill)",
74
+ [ts.SyntaxKind.FunctionExpression]: "function expressions are not supported: declare a function at the top level",
75
+ [ts.SyntaxKind.AwaitExpression]: "await is not supported: an instruction runs start to finish within one call",
76
+ [ts.SyntaxKind.TypeOfExpression]: "typeof is not supported at run time: the types are known when the program compiles",
77
+ [ts.SyntaxKind.DeleteExpression]: "delete is not supported: account fields always exist; set the value instead",
78
+ [ts.SyntaxKind.ModuleDeclaration]: "namespaces are not supported: use separate files and import from them",
79
+ };
80
+ /** "ClassDeclaration is not supported …" in words a TypeScript developer recognizes. */
81
+ export function unsupportedSyntax(kind, where) {
82
+ const known = SYNTAX[kind];
83
+ if (known)
84
+ return known;
85
+ return where === "top level"
86
+ ? `this kind of statement (${ts.SyntaxKind[kind]}) is not supported at the top level of a TypeSOL file`
87
+ : `this syntax (${ts.SyntaxKind[kind]}) is not supported in TypeSOL expressions`;
88
+ }