@typesol/cli 0.42.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +227 -0
  2. package/README.md +10 -7
  3. package/dist/compiler/analyze.js +443 -12
  4. package/dist/compiler/diagnostics.d.ts +1 -0
  5. package/dist/compiler/diagnostics.js +13 -0
  6. package/dist/compiler/emit/alias.d.ts +44 -0
  7. package/dist/compiler/emit/alias.js +135 -4
  8. package/dist/compiler/emit/base.d.ts +25 -0
  9. package/dist/compiler/emit/base.js +58 -7
  10. package/dist/compiler/emit/calls.d.ts +67 -0
  11. package/dist/compiler/emit/calls.js +521 -46
  12. package/dist/compiler/emit/cpi-core.d.ts +20 -3
  13. package/dist/compiler/emit/cpi-core.js +226 -5
  14. package/dist/compiler/emit/cpi.js +8 -2
  15. package/dist/compiler/emit/expressions.js +38 -7
  16. package/dist/compiler/emit/program.js +30 -1
  17. package/dist/compiler/emit/rbtree.d.ts +7 -0
  18. package/dist/compiler/emit/rbtree.js +142 -0
  19. package/dist/compiler/emit/shared.d.ts +8 -0
  20. package/dist/compiler/emit/shared.js +9 -1
  21. package/dist/compiler/emit/statements.d.ts +27 -1
  22. package/dist/compiler/emit/statements.js +288 -19
  23. package/dist/compiler/emit/storage.d.ts +23 -2
  24. package/dist/compiler/emit/storage.js +100 -56
  25. package/dist/compiler/emit/token.js +2 -2
  26. package/dist/compiler/emit/views.d.ts +60 -0
  27. package/dist/compiler/emit/views.js +523 -0
  28. package/dist/compiler/idl.js +2 -1
  29. package/dist/compiler/model.d.ts +65 -4
  30. package/dist/compiler/model.js +14 -0
  31. package/dist/compiler/toolchain.d.ts +15 -0
  32. package/dist/compiler/toolchain.js +146 -11
  33. package/docs/architecture.md +9 -2
  34. package/docs/case-study-phoenix.md +226 -0
  35. package/docs/language.md +139 -8
  36. package/docs/migrate-from-anchor.md +1 -0
  37. package/docs/runtime.md +1 -1
  38. package/docs/stability.md +21 -2
  39. package/docs/troubleshooting.md +5 -2
  40. package/lib/typesol.d.ts +221 -4
  41. package/llms-full.txt +169 -14
  42. package/llms.txt +1 -1
  43. package/package.json +2 -2
  44. package/runtime/typesol_rt.h +407 -0
@@ -39,6 +39,8 @@ const PROGRAM_ERRORS = [
39
39
  "IncorrectAuthority",
40
40
  ];
41
41
  const LIST_METHODS = new Set(["forEach", "some", "every", "find", "findIndex", "reduce", "includes", "indexOf"]);
42
+ /** The byte builders of a FixedVec<u8, N> (byteListMethod). */
43
+ const BYTE_METHODS = new Set(["pushLE", "pushKey", "pushBorsh", "setLE", "truncate"]);
42
44
  export class CallEmitter extends ExpressionEmitter {
43
45
  call(node, topLevel) {
44
46
  const callee = node.expression;
@@ -67,7 +69,10 @@ export class CallEmitter extends ExpressionEmitter {
67
69
  if (v.type.kind === "string")
68
70
  this.fail(args[1], "require's error is a string literal, a member of an error enum (CounterError.X) or a u32 code; a template string or string variable is not: give the message to an error enum member");
69
71
  const code = v.literal !== undefined ? this.literal(v.literal, U32, args[1]) : this.expect(v, U32, args[1]);
70
- this.line(`if (!${cond.c}) return ts_fail_code(${code.c}, ${cString(`Error: the code returned (${this.location(node)})`)});`);
72
+ if (this.quietErrors())
73
+ this.line(`if (!${cond.c}) return ts_fail_code_quiet(${code.c});`);
74
+ else
75
+ this.line(`if (!${cond.c}) return ts_fail_code(${code.c}, ${cString(`Error: the code returned (${this.location(node)})`)});`);
71
76
  return undefined;
72
77
  }
73
78
  // A built-in ProgramError: its u64 form (the index shifted into the high 32 bits), as solana_program returns it.
@@ -79,9 +84,13 @@ export class CallEmitter extends ExpressionEmitter {
79
84
  }
80
85
  const err = this.errorRef(args[1]);
81
86
  // `const ERROR_LOG_PREFIX = "AMM error: "`: the program's errors log as its native entrypoint logs them.
87
+ // `const ERROR_LOG_PREFIX = null`: nothing logged, only the code returned.
82
88
  const prefix = this.model.constants.get("ERROR_LOG_PREFIX")?.value;
83
89
  const text = typeof prefix === "string" ? `${prefix}${err.msg}` : `Error ${err.code} ${err.name}: ${err.msg} (${this.location(node)})`;
84
- this.line(`if (!${cond.c}) TS_FAIL(${err.code}, ${cString(text)});`);
90
+ if (prefix === null)
91
+ this.line(`if (!${cond.c}) return ts_fail_quiet(${err.code});`);
92
+ else
93
+ this.line(`if (!${cond.c}) TS_FAIL(${err.code}, ${cString(text)});`);
85
94
  return undefined;
86
95
  }
87
96
  case "panic": {
@@ -97,17 +106,47 @@ export class CallEmitter extends ExpressionEmitter {
97
106
  if (args.length > 2 || args.some((a, i) => !(i === 0 && silent) && text(a) === undefined))
98
107
  this.fail(node, 'panic() takes an optional message (or null to log nothing) and an optional "file:line:column" location: string literals or string constants');
99
108
  const msg = silent ? undefined : args.length ? text(args[0]) : "explicit panic";
100
- // The location the runtime reports ("SBF program Panicked in <file> at <line>:<column>"): the given one, as a
101
- // ported program's panic reports it, else this source line.
102
- const at = args.length > 1 ? text(args[1]) : this.location(node);
103
- const m = /^(.*?):(\d+)(?::(\d+))?$/.exec(at);
104
- const [file, line, col] = m ? [m[1], m[2], m[3] ?? "0"] : [at, "0", "0"];
105
- if (msg !== undefined)
106
- this.line(`sol_log(${cString(msg)});`);
107
- this.line(`sol_panic_(${cString(file)}, ${Buffer.byteLength(file)}, ${line}, ${col});`);
108
- this.line(`__builtin_unreachable();`);
109
+ if (silent && this.panicStyle())
110
+ this.fail(args[0], 'under PANIC_STYLE "solana-1.14" a panic logs its message, as solana_program 1.14\'s panic handler always does: pass the message');
111
+ // The location the runtime reports ("SBF program Panicked in <file> at <line>:<column>"), or the panic line
112
+ // logs: the given one, as a ported program's panic reports it, else this source line (with its column under
113
+ // PANIC_STYLE, as Rust always gives one).
114
+ const at = args.length > 1 ? text(args[1]) : this.panicStyle() ? this.locationWithColumn(node) : this.location(node);
115
+ for (const l of this.panicC(msg, at))
116
+ this.line(l);
109
117
  return undefined;
110
118
  }
119
+ case "panicsAt": {
120
+ // The checked arithmetic of `expression` panics as Rust's does at `location`, with Rust's messages.
121
+ const first = args[0];
122
+ const loc = first && (ts.isStringLiteralLike(first) ? first.text : ts.isIdentifier(first) ? this.model.constants.get(first.text)?.value : undefined);
123
+ if (args.length !== 2 || typeof loc !== "string" || !/^.+:\d+:\d+$/.test(loc))
124
+ this.fail(node, 'panicsAt(location, expression) takes a "file:line:column" string literal (or string constant) and the expression whose arithmetic panics there');
125
+ // Prettier writes an assignment argument in parentheses: `panicsAt(loc, (total += fee))`.
126
+ let inner = args[1];
127
+ while (ts.isParenthesizedExpression(inner))
128
+ inner = inner.expression;
129
+ const outer = this.panicAt;
130
+ this.panicAt = loc;
131
+ try {
132
+ // A statement: an assignment, a compound assignment (`total += fee`) or ++ / --.
133
+ const assigns = (ts.isBinaryExpression(inner) &&
134
+ inner.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
135
+ inner.operatorToken.kind <= ts.SyntaxKind.LastAssignment) ||
136
+ ((ts.isPrefixUnaryExpression(inner) || ts.isPostfixUnaryExpression(inner)) &&
137
+ (inner.operator === ts.SyntaxKind.PlusPlusToken || inner.operator === ts.SyntaxKind.MinusMinusToken));
138
+ if (assigns) {
139
+ if (!ts.isExpressionStatement(node.parent))
140
+ this.fail(inner, "an assignment inside panicsAt is a statement of its own: panicsAt(location, total += fee);");
141
+ this.expressionStatement(inner, topLevel);
142
+ return undefined;
143
+ }
144
+ return this.expr(inner);
145
+ }
146
+ finally {
147
+ this.panicAt = outer;
148
+ }
149
+ }
111
150
  case "abort": {
112
151
  // Rust's abort on SBF: the runtime's `abort` syscall ("SBF program panicked", no location, nothing logged).
113
152
  if (args.length)
@@ -181,6 +220,7 @@ export class CallEmitter extends ExpressionEmitter {
181
220
  if (!isWritable(d.kind))
182
221
  this.fail(args[1], "the destination must be writable (Mut<...>)");
183
222
  this.line(`TS_TRY(ts_close(a_${a.name}, a_${d.name}));`);
223
+ this.forgetOwners();
184
224
  return undefined;
185
225
  }
186
226
  case "minimumBalance": {
@@ -630,6 +670,8 @@ export class CallEmitter extends ExpressionEmitter {
630
670
  this.line(`ts_log_base64(${cString(prefix)}, ${Buffer.byteLength(prefix)}, (const uint8_t *)${place.ptr}, sizeof(TSS_${sd.name}));`);
631
671
  return undefined;
632
672
  }
673
+ case "findProgramAddressWithBump":
674
+ this.fail(node, "bind both results where it is called: const [address, bump] = findProgramAddressWithBump(seeds, program)");
633
675
  case "findProgramAddress": {
634
676
  // Pubkey::find_program_address(seeds, program).0: the canonical PDA of any program.
635
677
  if (args.length !== 2)
@@ -682,15 +724,59 @@ export class CallEmitter extends ExpressionEmitter {
682
724
  case "resizeAccount": {
683
725
  if (args.length !== 2)
684
726
  this.fail(node, "resizeAccount(account, newSize) takes the account and its new size");
727
+ this.assertNoViewAfter(this.viewAccountKey(args[0]), node, "resizeAccount()");
728
+ // A remaining account (or a helper's RemainingAccount): its size when the instruction started is the one the
729
+ // entrypoint recorded in the record's padding, as solana_program 1.14's entrypoint records it for realloc.
730
+ const h = this.handle(args[0]);
731
+ if (h) {
732
+ if (!this.nativeAccountWrites())
733
+ this.line(`TS_TRY(ts_check_writable(${h}));`);
734
+ const size = this.expect(this.expr(args[1], U64), U64, args[1]);
735
+ this.line(`TS_TRY(ts_resize_raw(${h}, ${size.c}, ts_entry_len(${h})));`);
736
+ return undefined;
737
+ }
685
738
  if (!this.ix)
686
- this.fail(node, "resizeAccount() is only available in instructions");
739
+ this.fail(node, "resizeAccount() is only available in instructions (or on a remaining account a helper was given)");
687
740
  const acct = this.accountParam(args[0], "resizeAccount's account");
688
- if (acct.kind.kind !== "info" || !isWritable(acct.kind))
689
- this.fail(args[0], "resizeAccount needs a Mut<AccountInfo> parameter");
741
+ if (acct.kind.kind !== "info" || (!isWritable(acct.kind) && !this.nativeAccountWrites()))
742
+ this.fail(args[0], "resizeAccount needs a Mut<AccountInfo> parameter or a remaining account");
690
743
  const size = this.expect(this.expr(args[1], U64), U64, args[1]);
691
744
  this.line(`TS_TRY(ts_resize_raw(a_${acct.name}, ${size.c}, entry_${acct.name}));`);
692
745
  return undefined;
693
746
  }
747
+ case "closeRaw": {
748
+ // Phoenix's Tombstone, in its order: receiver.lamports = receiver.lamports + account.lamports;
749
+ // account.lamports = 0; account.assign(&system_program::id()); account.realloc(0, false). The data is not
750
+ // zeroed (realloc's zero_init is false): the runtime drops it with the length, and then accepts the new owner.
751
+ if (args.length !== 2)
752
+ this.fail(node, "closeRaw(account, receiver) takes the account to close and the account that gets its lamports");
753
+ this.assertNoViewAfter(this.viewAccountKey(args[0]), node, "closeRaw()");
754
+ const a = this.inPlaceAccount(args[0], "closeRaw's account", true);
755
+ const r = this.inPlaceAccount(args[1], "closeRaw's receiver", false);
756
+ // Closing an account into itself would burn its lamports (the runtime then refuses the instruction).
757
+ if (!this.nativeAccountWrites())
758
+ this.line(`if (${a} == ${r}) TS_FAIL(TS_ERR_DUPLICATE_MUT, "TypeSOL: closeRaw's receiver is the account itself");`);
759
+ const sum = this.tmp("sum");
760
+ this.line(`uint64_t ${sum};`);
761
+ this.line(`if (ts_add_overflow_u64(${r}->lamports, ${a}->lamports, &${sum})) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: arithmetic overflow");`);
762
+ this.line(`${r}->lamports = ${sum};`);
763
+ this.line(`${a}->lamports = 0;`);
764
+ this.line(`ts_memcpy(&${a}->owner, &TS_SYSTEM_PROGRAM_ID, 32);`);
765
+ this.forgetOwners();
766
+ this.line(`${a}->data_len = 0;`);
767
+ return undefined;
768
+ }
769
+ case "assignOwner": {
770
+ // AccountInfo::assign: the owner field written in place; the runtime accepts it at the end of the instruction
771
+ // (or at a CPI) only for an account of this program that is writable and whose data is empty or zeroed.
772
+ if (args.length !== 2)
773
+ this.fail(node, "assignOwner(account, owner) takes the account and its new owner's address");
774
+ const a = this.inPlaceAccount(args[0], "assignOwner's account", true);
775
+ const owner = this.expect(this.expr(args[1], PUBKEY), PUBKEY, args[1]);
776
+ this.line(`ts_memcpy(&${a}->owner, ${owner.c}, 32);`);
777
+ this.forgetOwners();
778
+ return undefined;
779
+ }
694
780
  case "bigEndian":
695
781
  this.fail(node, "bigEndian(value) is a PDA seed: use it inside a seeds list");
696
782
  case "loadAccount":
@@ -700,6 +786,13 @@ export class CallEmitter extends ExpressionEmitter {
700
786
  case "loadForeign":
701
787
  case "loadBorsh":
702
788
  this.fail(node, `bind ${builtin}<T>(...) to a const first: const p = ${builtin}<T>(account)`);
789
+ case "loadRawAt":
790
+ case "loadRawMutAt":
791
+ case "rawArrayAt":
792
+ case "rawArrayMutAt":
793
+ case "rbTreeAt":
794
+ case "rbTreeMutAt":
795
+ this.fail(node, `bind ${builtin}(…) to a const first: const v = ${builtin}<…>(account, offset${builtin.startsWith("load") ? "" : ", capacity"})`);
703
796
  case "storeBorsh":
704
797
  return this.storeBorsh(node);
705
798
  case "emit":
@@ -720,6 +813,26 @@ export class CallEmitter extends ExpressionEmitter {
720
813
  }
721
814
  case "returnData":
722
815
  return this.returnData(node);
816
+ case "setReturnData": {
817
+ // Rust's set_return_data(&bytes): the bytes as they are. More than 1024 is left to the syscall, which refuses
818
+ // it exactly as it refuses the original's call.
819
+ if (args.length !== 1)
820
+ this.fail(node, "setReturnData(bytes) takes one list of u8");
821
+ if (this.ix?.returns)
822
+ this.fail(node, `${this.ix.name} returns a value, which is its return data: return it instead of calling setReturnData (or declare the instruction void)`);
823
+ const what = "setReturnData takes a list of u8: a local FixedVec<u8, N>, a Vec or FixedVec in account data, or the instruction data or a slice of it";
824
+ const s = this.listSpan(args[0]) ?? this.fail(args[0], what);
825
+ if (s.elem.kind !== "int" || s.elem.name !== "u8")
826
+ this.fail(args[0], what);
827
+ this.line(`sol_set_return_data((const uint8_t *)${s.items}, ${s.count});`);
828
+ return undefined;
829
+ }
830
+ case "logComputeUnits": {
831
+ if (args.length)
832
+ this.fail(node, "logComputeUnits() takes no arguments");
833
+ this.line(`sol_log_compute_units();`);
834
+ return undefined;
835
+ }
723
836
  case "programAt":
724
837
  case "sysvarAt":
725
838
  return this.programAt(node, builtin);
@@ -766,6 +879,10 @@ export class CallEmitter extends ExpressionEmitter {
766
879
  return this.callHelper(node, helper);
767
880
  if (ts.isPropertyAccessExpression(callee)) {
768
881
  const method = callee.name.text;
882
+ // A RedBlackTree's methods (rbTreeAt / rbTreeMutAt).
883
+ const onTree = this.treeCall(node);
884
+ if (onTree)
885
+ return onTree.value;
769
886
  const introspected = this.instructionsCall(node, callee, method);
770
887
  if (introspected)
771
888
  return introspected;
@@ -1006,6 +1123,8 @@ export class CallEmitter extends ExpressionEmitter {
1006
1123
  this.fail(node, "only Vecs of Mut<...> / Init<...> accounts can grow or shrink");
1007
1124
  this.line(`TS_TRY(ts_resize(params, ${payer}, a_${v.account.name}, 8 + ${info.fixed} + (${newLen}) * ${info.elemSize}, entry_${v.account.name}));`);
1008
1125
  };
1126
+ if (BYTE_METHODS.has(method))
1127
+ return this.byteListMethod(node, method, v);
1009
1128
  if (info.big !== undefined) {
1010
1129
  const done = this.bigVecMethod(node, method, v, { stageElem, needWritable, elemPaths });
1011
1130
  if (done)
@@ -1159,6 +1278,8 @@ export class CallEmitter extends ExpressionEmitter {
1159
1278
  const vt = v.type;
1160
1279
  if (method === "set")
1161
1280
  return undefined;
1281
+ if (info.raw)
1282
+ this.fail(node, `a RawArray has get, set, .length, for … of and the list methods (its length is the capacity it was made with), not ${method}()`);
1162
1283
  if (method === "slice")
1163
1284
  this.fail(node, "use slice(start, end) right where it is read: for (const x of list.slice(a, b)), list.slice(a, b).forEach(…) or .get(i)");
1164
1285
  if (info.slice)
@@ -1754,7 +1875,7 @@ export class CallEmitter extends ExpressionEmitter {
1754
1875
  const pre = this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value;
1755
1876
  const text = typeof pre === "string" ? `${pre}${PROGRAM_ERRORS[err]}` : `TypeSOL: not ${what}`;
1756
1877
  const bad = id ? `!ts_key_eq(&${h}->key, &${id})` : `!ts_is_token_program(&${h}->key)`;
1757
- this.line(`if (${bad}) TS_FAIL(((uint64_t)${err + 2}) << 32, ${cString(text)});`);
1878
+ this.line(`if (${bad}) ${this.programFail(`((uint64_t)${err + 2}) << 32`, text)};`);
1758
1879
  if (kind.kind === "stakeHistory")
1759
1880
  this.line(`if (${h}->data_len < 8) TS_FAIL(TS_ERR_SYSVAR, "TypeSOL: not the StakeHistory sysvar's data");`);
1760
1881
  return { c: h, type: { kind: "account", program: kind } };
@@ -1909,20 +2030,8 @@ export class CallEmitter extends ExpressionEmitter {
1909
2030
  this.fail(node, `${s.name} is @layout borsh: ${fn} reads fixed layouts only`);
1910
2031
  if (node.arguments.length !== 1)
1911
2032
  this.fail(node, `${fn}<T>(account) takes one remaining account or AccountInfo parameter`);
1912
- let h = this.handle(node.arguments[0]);
1913
- let param;
1914
- if (!h) {
1915
- const acct = this.accountParam(node.arguments[0], "the account");
1916
- if (acct.kind.kind !== "info")
1917
- this.fail(node.arguments[0], "pass a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter");
1918
- if (mut && !isWritable(acct.kind) && !this.nativeAccountWrites())
1919
- this.fail(node.arguments[0], `${acct.name} must be Mut<AccountInfo> to load it with loadRawMut (or declare const NATIVE_ACCOUNT_WRITES = true to leave writability to the runtime, as a native program does)`);
1920
- if (!this.ix)
1921
- this.fail(node, `load ${acct.name} in the instruction and pass the struct on`);
1922
- h = `a_${acct.name}`;
1923
- param = this.ix.accounts.indexOf(acct);
1924
- }
1925
- this.line(`if (!ts_key_eq(&${h}->owner, params->program_id)) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: account not owned by this program");`);
2033
+ const { h, param } = this.rawAccount(node, fn, mut);
2034
+ this.line(this.viewOwnerCheck(h));
1926
2035
  this.line(`if (${h}->data_len < sizeof(TSS_${s.name})) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account data too small");`);
1927
2036
  // A BigVec's stored length must fit in the account. Its capacity is kept in a local: every access is clamped to it
1928
2037
  // (the length may be written again after this), without a division each time.
@@ -1934,21 +2043,56 @@ export class CallEmitter extends ExpressionEmitter {
1934
2043
  // Named in scope, so a loop moved into a function of its own is given it (see outlinedLoop).
1935
2044
  this.scopes.at(-1).set(`__${bigCap}`, { c: bigCap, type: U64, mutable: false });
1936
2045
  }
1937
- // NATIVE_ACCOUNT_WRITES: no writability check and no claim. The view writes in place; the runtime refuses the
1938
- // instruction if a read-only account's data changed, and two views of one account share its bytes (the loader
1939
- // gives a duplicate the same record), as two AccountInfos of one account share one buffer in Rust.
1940
- if (mut && !this.nativeAccountWrites()) {
1941
- this.line(`TS_TRY(ts_check_writable(${h}));`);
1942
- const slot = this.claimSlots.get(node);
1943
- if (slot)
1944
- this.line(param === undefined
1945
- ? `TS_TRY(ts_claim_mut_rec(params, ${h}, &${slot}, params->ka_num));`
1946
- : `TS_TRY(ts_claim_mut_at_rec(params, ${param}, &${slot}));`);
1947
- else
1948
- this.line(param === undefined ? `TS_TRY(ts_claim_mut(params, ${h}));` : `TS_TRY(ts_claim_mut_at(params, ${param}));`);
1949
- }
2046
+ if (mut)
2047
+ this.claimRawMut(node, h, param);
1950
2048
  return { c: `((TSS_${s.name} *)(${h}->data))`, type: { kind: "structRef", struct: s.name, writable: mut }, ...(bigCap ? { bigCap } : {}) };
1951
2049
  }
2050
+ /**
2051
+ * A native account view's owner check (3007). In a program that makes such views the check goes through ts_owned: the
2052
+ * last account found this program's passes with a pointer compare until a CPI or an owner write forgets it.
2053
+ */
2054
+ viewOwnerCheck(h) {
2055
+ const fail = `TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: account not owned by this program")`;
2056
+ return this.model.ownerCache ? `if (!ts_owned(params, ${h})) ${fail};` : `if (!ts_key_eq(&${h}->owner, params->program_id)) ${fail};`;
2057
+ }
2058
+ /** An owner write or a CPI: the owner checks' cache (viewOwnerCheck) is forgotten. */
2059
+ forgetOwners() {
2060
+ if (this.model.ownerCache)
2061
+ this.line(`TS_OWNER_FORGET(params);`);
2062
+ }
2063
+ /**
2064
+ * The account a loadRaw-style view reads (its first argument): a remaining account, or an AccountInfo parameter of
2065
+ * the instruction (`param`: its position, for the claim). `fn` names the call in messages.
2066
+ */
2067
+ rawAccount(node, fn, mut) {
2068
+ const h = this.handle(node.arguments[0]);
2069
+ if (h)
2070
+ return { h };
2071
+ const acct = this.accountParam(node.arguments[0], "the account");
2072
+ if (acct.kind.kind !== "info")
2073
+ this.fail(node.arguments[0], "pass a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter");
2074
+ if (mut && !isWritable(acct.kind) && !this.nativeAccountWrites())
2075
+ this.fail(node.arguments[0], `${acct.name} must be Mut<AccountInfo> to load it with ${fn} (or declare const NATIVE_ACCOUNT_WRITES = true to leave writability to the runtime, as a native program does)`);
2076
+ if (!this.ix)
2077
+ this.fail(node, `load ${acct.name} in the instruction and pass the struct on`);
2078
+ return { h: `a_${acct.name}`, param: this.ix.accounts.indexOf(acct) };
2079
+ }
2080
+ /**
2081
+ * A writable view's checks: the account is writable and loaded mutably once in the instruction (2040).
2082
+ * NATIVE_ACCOUNT_WRITES: no writability check and no claim. The view writes in place; the runtime refuses the
2083
+ * instruction if a read-only account's data changed, and two views of one account share its bytes (the loader
2084
+ * gives a duplicate the same record), as two AccountInfos of one account share one buffer in Rust.
2085
+ */
2086
+ claimRawMut(node, h, param) {
2087
+ if (this.nativeAccountWrites())
2088
+ return;
2089
+ this.line(`TS_TRY(ts_check_writable(${h}));`);
2090
+ const slot = this.claimSlots.get(node);
2091
+ if (slot)
2092
+ this.line(param === undefined ? `TS_TRY(ts_claim_mut_rec(params, ${h}, &${slot}, params->ka_num));` : `TS_TRY(ts_claim_mut_at_rec(params, ${param}, &${slot}));`);
2093
+ else
2094
+ this.line(param === undefined ? `TS_TRY(ts_claim_mut(params, ${h}));` : `TS_TRY(ts_claim_mut_at(params, ${param}));`);
2095
+ }
1952
2096
  /**
1953
2097
  * `const v = loadBorsh<T>(acct)`: the account's data from byte 0 decoded as Borsh into a local `T` (a copy), as
1954
2098
  * `try_from_slice_unchecked` reads it: no owner check, no discriminator, trailing bytes ignored; bytes that are not
@@ -2042,13 +2186,50 @@ export class CallEmitter extends ExpressionEmitter {
2042
2186
  this.line(`TS_TRY(ts_check_unaliased(params, a_${acct.name}));`);
2043
2187
  return `a_${acct.name}`;
2044
2188
  }
2189
+ /**
2190
+ * An account `closeRaw` / `assignOwner` writes in place: a remaining account (a helper's RemainingAccount, a ternary
2191
+ * between them) or an AccountInfo parameter. Without NATIVE_ACCOUNT_WRITES it is checked as the other writes to
2192
+ * accounts the compiler cannot see are: writable (3006; a parameter must be Mut<AccountInfo>), passed once (2040), and
2193
+ * for `owned` this program's (3007). With the flag nothing is checked: the runtime judges the result, as it judges a
2194
+ * native program's.
2195
+ */
2196
+ inPlaceAccount(node, what, owned) {
2197
+ const native = this.nativeAccountWrites();
2198
+ let h = this.handle(node);
2199
+ if (!h) {
2200
+ const acct = this.accountParam(node, what);
2201
+ if (acct.kind.kind !== "info")
2202
+ this.fail(node, `${what} is a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter`);
2203
+ if (!isWritable(acct.kind) && !native)
2204
+ this.fail(node, `${acct.name} must be Mut<AccountInfo> to change it in place (or declare const NATIVE_ACCOUNT_WRITES = true to leave writability to the runtime, as a native program does)`);
2205
+ h = `a_${acct.name}`;
2206
+ }
2207
+ else if (!native)
2208
+ this.line(`TS_TRY(ts_check_writable(${h}));`);
2209
+ if (native)
2210
+ return h;
2211
+ this.line(`TS_TRY(ts_check_unaliased(params, ${h}));`);
2212
+ if (owned)
2213
+ this.line(`if (!ts_key_eq(&${h}->owner, params->program_id)) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: account not owned by this program");`);
2214
+ return h;
2215
+ }
2045
2216
  /** `TS_FAIL` with a built-in ProgramError (no custom code), logged as `require(…, ProgramError.X)` logs it. */
2046
2217
  programErrorFail(name, node) {
2047
2218
  const idx = PROGRAM_ERRORS.indexOf(name);
2048
2219
  // `const PROGRAM_ERROR_LOG_PREFIX = "Program error: "`: the log line a native entrypoint writes for it.
2049
2220
  const pre = this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value;
2050
2221
  const text = typeof pre === "string" ? `${pre}${name}` : `Error: ${name} (${this.location(node)})`;
2051
- return `TS_FAIL(((uint64_t)${idx + 2}) << 32, ${cString(text)})`;
2222
+ return this.programFail(`((uint64_t)${idx + 2}) << 32`, text);
2223
+ }
2224
+ /** A failure with a built-in ProgramError's code: logged with `text`, or nothing under `PROGRAM_ERROR_LOG_PREFIX = null`. */
2225
+ programFail(code, text) {
2226
+ if (this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value === null)
2227
+ return `return ts_fail_quiet(${code})`;
2228
+ return `TS_FAIL(${code}, ${cString(text)})`;
2229
+ }
2230
+ /** `const ERROR_LOG_PREFIX = null`: the program's own errors (and codes returned by its helpers) log nothing. */
2231
+ quietErrors() {
2232
+ return this.model.constants.get("ERROR_LOG_PREFIX")?.value === null;
2052
2233
  }
2053
2234
  /** `loadAccount<T>(acct)` / `loadAccountMut<T>(acct)`: checked view of a program account. */
2054
2235
  loadAccount(node, mut) {
@@ -2165,6 +2346,39 @@ export class CallEmitter extends ExpressionEmitter {
2165
2346
  visit(body);
2166
2347
  return found;
2167
2348
  }
2349
+ /** Whether a helper's body (or a helper it calls) closes or resizes an account: closeRaw / resizeAccount. */
2350
+ helperResizes(body) {
2351
+ return this.helperCalls(body, ["closeRaw", "resizeAccount"]);
2352
+ }
2353
+ /** Whether a helper's body (or a helper it calls) makes a writable tree view, which may change a tree's structure. */
2354
+ helperMakesMutTree(body) {
2355
+ return this.helperCalls(body, ["rbTreeMutAt"]);
2356
+ }
2357
+ /** Whether a helper's body (or a helper it calls) calls one of these built-ins. */
2358
+ helperCalls(body, builtins, seen = new Set()) {
2359
+ if (seen.has(body))
2360
+ return false;
2361
+ seen.add(body);
2362
+ let found = false;
2363
+ const visit = (n) => {
2364
+ if (found)
2365
+ return;
2366
+ if (ts.isCallExpression(n) && ts.isIdentifier(n.expression)) {
2367
+ const fn = this.exportName(n.expression);
2368
+ if (fn && builtins.includes(fn))
2369
+ found = true;
2370
+ else {
2371
+ const name = calleeName(n.expression, this.model.helperDecls, this.checker);
2372
+ const callee = name ? (this.model.generics.get(name)?.node ?? this.model.helpers.get(name)?.node) : undefined;
2373
+ if (callee && this.helperCalls(callee, builtins, seen))
2374
+ found = true;
2375
+ }
2376
+ }
2377
+ ts.forEachChild(n, visit);
2378
+ };
2379
+ visit(body);
2380
+ return found;
2381
+ }
2168
2382
  /**
2169
2383
  * A helper given a closure (a function that reads the caller's variables) for a function parameter: a closure only
2170
2384
  * runs where it is declared, so the helper is expanded here, like a closure, with the closure bound to the
@@ -2174,6 +2388,9 @@ export class CallEmitter extends ExpressionEmitter {
2174
2388
  const g = this.givenClosure(node);
2175
2389
  if (!g)
2176
2390
  return undefined;
2391
+ const tagged = [g.node, ...(ts.isVariableDeclaration(g.node.parent) ? [g.node.parent] : [])];
2392
+ if (tagged.some((n) => ts.getJSDocTags(n).some((t) => t.tagName.text === "noinline")))
2393
+ this.fail(node, `${g.display}() is @noinline, but given a closure it is expanded where it is called: pass a named function`);
2177
2394
  // Type parameters: bound from the call (as an instance would be) while the body is expanded.
2178
2395
  const saved = this.scope;
2179
2396
  if (g.typeParams.length) {
@@ -2286,6 +2503,12 @@ export class CallEmitter extends ExpressionEmitter {
2286
2503
  // A helper that takes accounts may change account data, so account text it gets is copied first.
2287
2504
  // A RemainingAccount(s) parameter counts: the helper may load and write a struct through it.
2288
2505
  const takesAccounts = h.params.some((p) => p.account || p.type.kind === "account" || p.type.kind === "remaining");
2506
+ // A helper that closes or resizes an account it is given ends the caller's views of it (any account it may be).
2507
+ if (takesAccounts && this.helperResizes(h.node))
2508
+ this.assertNoViewAfter("?", node, `${h.display}() (it may close or resize an account it is given)`);
2509
+ // Nor may a helper change a tree of an account a for … of is walking.
2510
+ if (takesAccounts && this.iteratingTrees.size && this.helperMakesMutTree(h.node))
2511
+ this.fail(node, `${h.display}() takes accounts and makes an rbTreeMutAt view, so it may change the tree a for … of is walking (${[...this.iteratingTrees.values()].map((w) => w.name).join(", ")}): collect what it needs in the loop, then call it after`);
2289
2512
  const values = [];
2290
2513
  const pieces = [];
2291
2514
  h.params.forEach((p, i) => {
@@ -2301,6 +2524,8 @@ export class CallEmitter extends ExpressionEmitter {
2301
2524
  values.push(takesAccounts ? this.ownedString(raw) : raw);
2302
2525
  }
2303
2526
  });
2527
+ if (h.params.some((p) => p.inout))
2528
+ this.checkInoutCall(node, h, argNodes, pieces.map((x) => (typeof x === "string" ? x : undefined)));
2304
2529
  // A helper that takes a writable struct account may replace anything stored in it (see assertNotAliased).
2305
2530
  for (const [i, p] of h.params.entries())
2306
2531
  if (p.account && p.account.kind === "account" && p.account.mut && ts.isIdentifier(argNodes[i]))
@@ -2359,6 +2584,8 @@ export class CallEmitter extends ExpressionEmitter {
2359
2584
  return `a_${acct.name}, entry_${acct.name}`;
2360
2585
  return `a_${acct.name}`;
2361
2586
  }
2587
+ if (p.inout)
2588
+ return this.inoutArg(h, p, n);
2362
2589
  switch (p.type.kind) {
2363
2590
  case "signerSeeds": {
2364
2591
  const seeds = this.signerSeedsArg(n);
@@ -2398,14 +2625,189 @@ export class CallEmitter extends ExpressionEmitter {
2398
2625
  const l = ts.isIdentifier(n) ? this.lookup(n.text) : undefined;
2399
2626
  // An Option<Vec<T>> argument passes as its list once checked against null (TypeScript narrows it).
2400
2627
  const t = l?.type.kind === "vecArg" && l.type.optional ? { ...l.type, optional: undefined } : l?.type;
2401
- if (!l || !t || !sameType(t, p.type))
2402
- this.fail(n, `expected a ${typeName(p.type)} instruction argument`);
2403
- return l.c;
2628
+ if (l && t && sameType(t, p.type))
2629
+ return l.c;
2630
+ // A list of the caller's (a local FixedVec or FixedArray, a field of a local struct, or one in account data): a
2631
+ // read-only view of its elements, passed by pointer.
2632
+ const view = this.listViewArg(n, p.type, h);
2633
+ if (view)
2634
+ return view;
2635
+ const what = p.type.elem.kind === "int" && p.type.elem.name === "u8" && p.type.cap === undefined ? "list of u8" : `list of ${typeName(p.type.elem)}`;
2636
+ this.fail(n, `expected a ${what}: an instruction argument, the instruction data or a slice of it, or a FixedVec / FixedArray of ${typeName(p.type.elem)} (a local, a field)`);
2404
2637
  }
2405
2638
  default:
2406
2639
  return this.expect(this.expr(n, p.type), p.type, n);
2407
2640
  }
2408
2641
  }
2642
+ /**
2643
+ * An `Inout<T>` argument: a pointer to the caller's place itself (never a copy), which must be writable. A literal
2644
+ * (`f({ … })`, `fixedArray(…)`) is built in a local of its own, as JS passes a fresh object; a ternary must pick
2645
+ * between two places (a literal branch would be a copy the helper's writes never reach).
2646
+ */
2647
+ inoutArg(h, p, n) {
2648
+ const want = p.inout;
2649
+ const what = `Inout<${typeName(want)}>`;
2650
+ let bare = n;
2651
+ while (ts.isParenthesizedExpression(bare))
2652
+ bare = bare.expression;
2653
+ if (want.kind !== "vec" && (ts.isObjectLiteralExpression(bare) || (ts.isCallExpression(bare) && this.exportName(bare.expression) === "fixedArray")))
2654
+ return this.literalArg(n, want);
2655
+ if (ts.isConditionalExpression(bare)) {
2656
+ if (want.kind !== "struct")
2657
+ this.fail(n, `${h.display}() takes ${p.name} as ${what}: pass the list itself, not a choice between lists`);
2658
+ const place = this.structPlace(bare);
2659
+ if (!place)
2660
+ this.fail(n, `${h.display}() takes ${p.name} as ${what}: both branches must be ${want.name} places (a local, a field, a list element), not values`);
2661
+ if (place.struct !== want.name)
2662
+ this.fail(n, `${h.display}() takes ${p.name} as ${what}; this is a ${place.struct}`);
2663
+ if (!place.writable)
2664
+ this.fail(n, `${h.display}() changes ${p.name} (Inout), and a branch of this choice is read-only`);
2665
+ return place.ptr;
2666
+ }
2667
+ let r = this.ref(n);
2668
+ // A narrowed Option<Struct> / Option<FixedArray> place (`c.opt !== null` before it): the value inside it.
2669
+ if (r && r.type.kind === "option" && sameType(r.type.inner, want))
2670
+ r = this.someValue(r);
2671
+ if (!r || !sameType(r.type, want)) {
2672
+ const l = ts.isIdentifier(n) ? this.lookup(n.text) : undefined;
2673
+ if (l?.type.kind === "vecArg" || l?.type.kind === "optionArg")
2674
+ this.fail(n, `${h.display}() changes ${p.name} (Inout): instruction arguments are read-only; copy the value into a local first`);
2675
+ this.fail(n, `${h.display}() takes ${p.name} as ${what}: pass a ${typeName(want)} place of yours (a local, a field, a list element) for it to change`);
2676
+ }
2677
+ if (!r.writable)
2678
+ this.fail(n, `${h.display}() changes ${p.name} (Inout): ${this.readOnly(r)}`);
2679
+ if (r.vec?.slice)
2680
+ this.fail(n, `${h.display}() takes ${p.name} as ${what}: pass the list, not a slice of it`);
2681
+ return `(&${r.lv})`;
2682
+ }
2683
+ /**
2684
+ * The rules of a call with `Inout<T>` arguments, so the helper's pointer is the only way to the place while it runs
2685
+ * (Rust's one `&mut` at a time) and stays valid: no other argument may share storage with an Inout one (two places,
2686
+ * one inside the other, the same list's elements whatever their indexes, an account and a place in it); a place in
2687
+ * a list whose elements can move is refused when the call may move them; a reference into the place read after the
2688
+ * call is refused (the helper may replace what it points at). Places whose roots differ but may be the same bytes at
2689
+ * run time (two `Dup<…>` accounts, two loadRawMut views under NATIVE_ACCOUNT_WRITES, a helper's account parameters)
2690
+ * are compared at run time (2040).
2691
+ */
2692
+ checkInoutCall(node, h, argNodes, passed) {
2693
+ const show = (e) => {
2694
+ try {
2695
+ return e.getText();
2696
+ }
2697
+ catch {
2698
+ return "this argument";
2699
+ }
2700
+ };
2701
+ const fresh = (e) => {
2702
+ while (ts.isParenthesizedExpression(e))
2703
+ e = e.expression;
2704
+ // A literal, or a struct a helper returns: a value of its own that nothing else reaches.
2705
+ if (ts.isObjectLiteralExpression(e))
2706
+ return true;
2707
+ if (!ts.isCallExpression(e))
2708
+ return false;
2709
+ return this.exportName(e.expression) === "fixedArray" || this.helperOf(e)?.returns?.kind === "struct";
2710
+ };
2711
+ // Each argument passed by reference (Inout, read-only structs and lists, accounts, loaded structs) and its storage.
2712
+ const refs = [];
2713
+ h.params.forEach((p, i) => {
2714
+ const n = argNodes[i];
2715
+ if (p.inout) {
2716
+ const paths = this.pathsOf(n);
2717
+ if (!paths && !fresh(n))
2718
+ this.fail(n, `${h.display}() changes ${p.name} (Inout): pass a local, a field path or a list element (bind anything else to a const first)`);
2719
+ if (paths)
2720
+ refs.push({ i, inout: true, paths });
2721
+ return;
2722
+ }
2723
+ const byRef = p.account || p.type.kind === "structRef" || p.type.kind === "arrayArg" || p.type.kind === "dataEnumArg" || p.type.kind === "vecArg";
2724
+ const paths = byRef ? this.pathsOf(n) : undefined;
2725
+ if (paths)
2726
+ refs.push({ i, inout: false, paths });
2727
+ });
2728
+ for (let a = 0; a < refs.length; a++)
2729
+ for (let b = a + 1; b < refs.length; b++) {
2730
+ const x = refs[a];
2731
+ const y = refs[b];
2732
+ if ((!x.inout && !y.inout) || !this.placesOverlap(x.paths, y.paths))
2733
+ continue;
2734
+ const [w, o] = x.inout ? [x, y] : [y, x];
2735
+ const wn = show(argNodes[w.i]);
2736
+ const on = show(argNodes[o.i]);
2737
+ const op = h.params[o.i];
2738
+ const why = `${wn} and ${on} share storage, and ${h.display}() changes ${h.params[w.i].name} (Inout) in place: while it runs, its parameter must be the only way to that place`;
2739
+ if (op.inout)
2740
+ this.fail(argNodes[Math.max(w.i, o.i)], `${why}. Two elements of one list count as one place whatever their indexes; pass what holds both, or copy one into a local and store it back after the call`);
2741
+ if (op.account)
2742
+ this.fail(argNodes[o.i], `${why}. Pass the account alone and reach ${wn} through it in the helper, or pass only ${wn}`);
2743
+ this.fail(argNodes[o.i], `${why}. Copy ${on} into a local first (const copy: T = ${on}) and pass the copy`);
2744
+ }
2745
+ for (const r of refs) {
2746
+ if (!r.inout)
2747
+ continue;
2748
+ const n = argNodes[r.i];
2749
+ if (this.throughMovableList(n) && this.mayResizeVecs(node))
2750
+ this.fail(n, `${show(n)} is in a list whose elements move when it grows, shrinks or is filtered (a Vec or BigVec), and ${h.display}() may do that (it takes writable or remaining accounts) while it holds ${show(n)}; copy the element into a local (const e: T = …), pass the local and store it back after the call`);
2751
+ this.assertNothingInside(r.paths, node, h.display, show(n));
2752
+ }
2753
+ // Different roots that may still be the same bytes: compared at run time.
2754
+ const root = (p) => p.split(/[.[]/)[0];
2755
+ const local = (c) => {
2756
+ for (const s of [...this.scopes, this.args])
2757
+ for (const l of s.values())
2758
+ if (l.c === c)
2759
+ return l;
2760
+ return undefined;
2761
+ };
2762
+ const mayShare = (a, b) => {
2763
+ if (a === b)
2764
+ return false;
2765
+ const acct = (r) => (r.startsWith("@") ? undefined : this.accounts.get(r));
2766
+ const view = (r) => (r.startsWith("@") && local(r.slice(1))?.view ? r : undefined);
2767
+ const [aa, ba] = [acct(a), acct(b)];
2768
+ if (aa && ba)
2769
+ return aa.index === -1 || ba.index === -1 || !!aa.constraints.dup || !!ba.constraints.dup;
2770
+ if (!this.nativeAccountWrites())
2771
+ return false;
2772
+ return !!((aa || view(a)) && (ba || view(b)));
2773
+ };
2774
+ // A read-only argument beside an Inout one may also be the same bytes: an account the runtime does not keep apart
2775
+ // from a writable one (a read-only parameter is not checked against the writable ones).
2776
+ const readOnlyAccount = (r) => {
2777
+ const a = r.startsWith("@") ? undefined : this.accounts.get(r);
2778
+ return !!a && !isWritable(a.kind);
2779
+ };
2780
+ const mayShareRead = (a, b) => mayShare(a, b) || (a !== b && !!this.accounts.get(a) && !!this.accounts.get(b) && (readOnlyAccount(a) || readOnlyAccount(b)));
2781
+ // The bytes an argument is passed as, when they are the caller's own: a place's pointer, an account's data, a list
2782
+ // view's elements. A copy taken for the call (a helper that takes accounts gets one) shares nothing.
2783
+ const bytes = (r) => {
2784
+ const v = passed[r.i];
2785
+ if (!v)
2786
+ return undefined;
2787
+ const p = h.params[r.i];
2788
+ if (r.inout || (v.startsWith("(&") && (p.type.kind === "structRef" || p.type.kind === "arrayArg" || p.type.kind === "dataEnumArg")))
2789
+ return { lo: `(uint8_t *)${v}`, hi: `(uint8_t *)${v} + sizeof(*${v})` };
2790
+ if (p.account && /^\w+$/.test(v))
2791
+ return { lo: `${v}->data`, hi: `${v}->data + ${v}->data_len` };
2792
+ if (p.type.kind === "vecArg" && /^\w+$/.test(v) && !h.params.some((q) => q.account || q.type.kind === "account" || q.type.kind === "remaining"))
2793
+ return { lo: `${v}.ptr`, hi: `${v}.ptr + (uint64_t)${v}.len * ${this.fieldBytes(p.type.elem)}` };
2794
+ return undefined;
2795
+ };
2796
+ for (let a = 0; a < refs.length; a++)
2797
+ for (let b = a + 1; b < refs.length; b++) {
2798
+ const x = refs[a];
2799
+ const y = refs[b];
2800
+ if (!x.inout && !y.inout)
2801
+ continue;
2802
+ const share = x.inout && y.inout ? mayShare : mayShareRead;
2803
+ if (!x.paths.some((p) => y.paths.some((q) => share(root(p), root(q)))))
2804
+ continue;
2805
+ const [bx, by] = [bytes(x), bytes(y)];
2806
+ if (!bx || !by)
2807
+ continue;
2808
+ this.line(`if (${bx.lo} < ${by.hi} && ${by.lo} < ${bx.hi}) TS_FAIL(TS_ERR_DUPLICATE_MUT, ${cString(`TypeSOL: ${h.display}() was given ${show(argNodes[x.i])} and ${show(argNodes[y.i])}, which share storage`)});`);
2809
+ }
2810
+ }
2409
2811
  /**
2410
2812
  * A struct, array or data-enum helper argument written as a literal (`f({ a: 1n, b: { c } })`, `g([1n, 2n])`, or a
2411
2813
  * ternary with a literal branch): built in a local of its own, as `const x: T = { … }; f(x)` would, and passed by
@@ -2452,6 +2854,79 @@ export class CallEmitter extends ExpressionEmitter {
2452
2854
  this.line(`ts_memcpy(${t}, &${lv}, ${n});`);
2453
2855
  return t;
2454
2856
  }
2857
+ /**
2858
+ * A FixedVec or FixedArray of `elem` given for a read-only list parameter: a `TS_VecArg` view of its elements (the
2859
+ * length as it is at the call). A list this function holds (a local, a field of a struct it owns) is read in place;
2860
+ * one in account data is copied first when the helper takes accounts, as a struct argument is (the helper may write
2861
+ * the account). Undefined when `n` is not such a list.
2862
+ */
2863
+ listViewArg(n, want, h) {
2864
+ const r = this.probe(() => this.ref(n));
2865
+ if (!r)
2866
+ return undefined;
2867
+ const elem = want.elem;
2868
+ // A FixedVec<T, N> parameter holds at most N elements: a list with room for more is refused here, as an
2869
+ // instruction argument with more is refused when decoded.
2870
+ const holds = r.type.kind === "vec" ? r.type.cap : r.type.kind === "array" ? r.type.len : undefined;
2871
+ if (want.cap !== undefined && holds !== undefined && holds > want.cap && (r.type.kind === "vec" || r.type.kind === "array") && sameType(r.type.elem, elem))
2872
+ this.fail(n, `${h.display}() takes at most ${want.cap} elements here (FixedVec<${typeName(elem)}, ${want.cap}>) and this list holds up to ${holds}: declare the parameter FixedVec<${typeName(elem)}, ${holds}> (or InstructionBytes / Vec<${typeName(elem)}>, no limit)`);
2873
+ let items;
2874
+ let count;
2875
+ let room;
2876
+ if (r.type.kind === "vec" && r.type.cap !== undefined && !r.type.heap && !r.type.big && !r.type.raw && r.vec && !r.vec.slice) {
2877
+ if (!sameType(r.type.elem, elem))
2878
+ return undefined;
2879
+ const fresh = this.ref(n);
2880
+ items = fresh.vec.items;
2881
+ count = vecCount(fresh.vec);
2882
+ room = r.type.cap;
2883
+ }
2884
+ else if (r.type.kind === "array") {
2885
+ if (!sameType(r.type.elem, elem))
2886
+ return undefined;
2887
+ items = this.ref(n).lv;
2888
+ count = String(r.type.len);
2889
+ room = r.type.len;
2890
+ }
2891
+ else
2892
+ return undefined;
2893
+ const size = this.fieldBytes(elem);
2894
+ const t = this.tmp("lview");
2895
+ if (h.params.some((p) => p.account || p.type.kind === "account" || p.type.kind === "remaining") && !this.callerHoldsList(n)) {
2896
+ // One buffer per call site, allocated on first use: a call in a loop must not take new heap every pass.
2897
+ const buf = this.tmp("argl");
2898
+ this.hoistLazy(buf, (v) => `uint8_t *${v}`);
2899
+ this.line(`if (${buf} == NULL) TS_TRY(ts_alloc(${room * size}, &${buf}));`);
2900
+ this.line(`TS_VecArg ${t} = {${buf}, (uint32_t)${count}};`);
2901
+ this.line(`ts_memcpy_bulk(${buf}, (const uint8_t *)${items}, (uint64_t)${t}.len * ${size});`);
2902
+ return t;
2903
+ }
2904
+ this.line(`TS_VecArg ${t} = {(const uint8_t *)${items}, (uint32_t)${count}};`);
2905
+ return t;
2906
+ }
2907
+ /** Whether `node` is a list this function holds on its stack (a local list, a field of a struct it owns), not account data. */
2908
+ callerHoldsList(node) {
2909
+ let n = node;
2910
+ for (;;) {
2911
+ if (ts.isParenthesizedExpression(n))
2912
+ n = n.expression;
2913
+ else if (ts.isPropertyAccessExpression(n))
2914
+ n = n.expression;
2915
+ else if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression) && n.expression.name.text === "get")
2916
+ n = n.expression.expression;
2917
+ else
2918
+ break;
2919
+ }
2920
+ if (!ts.isIdentifier(n))
2921
+ return false;
2922
+ const l = this.lookup(n.text);
2923
+ if (!l)
2924
+ return false;
2925
+ // A declared list local has no storage paths; an Inout parameter's (`@p_x`) may be account data.
2926
+ if ((l.type.kind === "vec" || l.type.kind === "array") && !l.paths && !l.readonly)
2927
+ return true;
2928
+ return !!l.owned;
2929
+ }
2455
2930
  /** Whether `node` is (part of) a struct value this function owns: `h`, `h.inner`, `h.list.get(i)`. */
2456
2931
  ownedRoot(node) {
2457
2932
  let n = node;