@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
@@ -0,0 +1,60 @@
1
+ import ts from "typescript";
2
+ import { type RbTreeInst, type ValueType } from "../model.js";
3
+ import { CallEmitter } from "./calls.js";
4
+ import { type Local, type Ref, type Value } from "./shared.js";
5
+ /**
6
+ * Views of native account data at offsets known only at run time (Phoenix's market at byte 576, its trees sized by
7
+ * the market header, Serum's slabs): `loadRawAt` / `loadRawMutAt` (a fixed-layout struct), `rawArrayAt` /
8
+ * `rawArrayMutAt` (a run-time number of elements in place) and `rbTreeAt` / `rbTreeMutAt`, lib-sokoban 0.3's
9
+ * RedBlackTree<K, V, N> byte for byte. Each checks its bounds once, when it is made (ProgramError::AccountDataTooSmall),
10
+ * with the owner, writability and claim checks of loadRaw / loadRawMut.
11
+ */
12
+ export declare abstract class ViewEmitter extends CallEmitter {
13
+ /** The view function a call names (loadRawAt …), or undefined. */
14
+ protected viewFn(node: ts.Expression): string | undefined;
15
+ /** The tree a name holds (`const book = rbTreeMutAt<…>(…)`), with its instance. */
16
+ protected treeOf(node: ts.Expression): {
17
+ local: Local;
18
+ inst: RbTreeInst;
19
+ writable: boolean;
20
+ } | undefined;
21
+ /**
22
+ * `const x = loadRawAt<T>(…)` and the other views, or `const o = tree.get(k)` / `remove` / `min` / `max` / `nodeAt`
23
+ * when it hands out a reference into a node: declared here (true), else left to the general binding (false).
24
+ */
25
+ protected bindView(d: ts.VariableDeclaration, init: ts.Expression, name: string, c: string, mutable: boolean): boolean;
26
+ /** The struct type argument of loadRawAt<T>: a fixed-size struct without a BigVec. */
27
+ private rawAtStruct;
28
+ /** A u64 argument evaluated into a temporary, in argument order. */
29
+ private u64Arg;
30
+ /** The view's account and offset (and capacity), evaluated left to right, then the owner check (3007). */
31
+ private viewStart;
32
+ /** `loadRawAt<T>(acct, offset)` / `loadRawMutAt`: a fixed-layout struct at a run-time byte offset. */
33
+ protected loadRawAt(node: ts.CallExpression, mut: boolean): Value;
34
+ /** `rawArrayAt<T>(acct, offset, capacity)` / `rawArrayMutAt`: `capacity` elements in place, bound to `c` (and `c__n`). */
35
+ protected rawArrayAt(node: ts.CallExpression, mut: boolean, c: string): ValueType;
36
+ /** The place a RawArray local names: a list of `n` elements with no stored length (see Ref.vec). */
37
+ private rawArrayRef;
38
+ /** Rust's alignment of a field type (repr(C), as on SBF): for the node layout check. */
39
+ private alignOf;
40
+ /** Why the default order cannot compare this key type, or undefined. */
41
+ private unordered;
42
+ /**
43
+ * `rbTreeAt<K, V>(acct, offset, capacity, compare?)` / `rbTreeMutAt`: lib-sokoban 0.3's RedBlackTree<K, V, capacity>
44
+ * at a run-time offset (32 + capacity × (16 + size(K) + size(V)) bytes), bound to `c` (a TsRbt).
45
+ */
46
+ protected rbTreeAt(node: ts.CallExpression, mut: boolean, c: string): ValueType;
47
+ /** A pointer to a key or value given to a tree method: a struct place as it is, anything else in a temporary. */
48
+ private treeOperand;
49
+ /** The value stored in node `idx` (0: none) as an expression result: a nullable reference, or an Option copy. */
50
+ private nodeValue;
51
+ protected treeCall(node: ts.CallExpression): {
52
+ value: Value | undefined;
53
+ } | undefined;
54
+ /** A tree node a property is read on: an entry local, or `e!` / `tree.min()!` (checked), as a TsRbtEntry. */
55
+ private entryOf;
56
+ protected viewRef(node: ts.Expression): Ref | undefined;
57
+ /** `rbTreeMutAt(…).min()`, `rawArrayAt(…).get(i)`: a view used without binding it. */
58
+ private unbound;
59
+ protected viewProperty(node: ts.PropertyAccessExpression): Value | undefined;
60
+ }
@@ -0,0 +1,523 @@
1
+ import ts from "typescript";
2
+ import { calleeName } from "../analyze.js";
3
+ import { INT_INFO, isScalar, optionKey, sameType, typeName } from "../model.js";
4
+ import { CallEmitter } from "./calls.js";
5
+ import { U32, U64, fieldC, optC, valueC } from "./shared.js";
6
+ /** The run-time offset views a native program reads its account with. */
7
+ const VIEW_FNS = new Set(["loadRawAt", "loadRawMutAt", "rawArrayAt", "rawArrayMutAt", "rbTreeAt", "rbTreeMutAt"]);
8
+ /** Tree methods that hand out a reference into a node (bound to a const, they alias the tree). */
9
+ const TREE_REFS = new Set(["get", "remove", "removeAt", "min", "max", "nodeAt"]);
10
+ const TREE_METHODS = "length, capacity, initialize(), get(key), insert(key, value), remove(key), removeAt(index), min(), max(), addrOf(key), nodeAt(index), for … of and reversed()";
11
+ /**
12
+ * Views of native account data at offsets known only at run time (Phoenix's market at byte 576, its trees sized by
13
+ * the market header, Serum's slabs): `loadRawAt` / `loadRawMutAt` (a fixed-layout struct), `rawArrayAt` /
14
+ * `rawArrayMutAt` (a run-time number of elements in place) and `rbTreeAt` / `rbTreeMutAt`, lib-sokoban 0.3's
15
+ * RedBlackTree<K, V, N> byte for byte. Each checks its bounds once, when it is made (ProgramError::AccountDataTooSmall),
16
+ * with the owner, writability and claim checks of loadRaw / loadRawMut.
17
+ */
18
+ export class ViewEmitter extends CallEmitter {
19
+ /** The view function a call names (loadRawAt …), or undefined. */
20
+ viewFn(node) {
21
+ while (ts.isParenthesizedExpression(node))
22
+ node = node.expression;
23
+ if (!ts.isCallExpression(node))
24
+ return undefined;
25
+ const fn = this.exportName(node.expression);
26
+ return fn && VIEW_FNS.has(fn) ? fn : undefined;
27
+ }
28
+ /** The tree a name holds (`const book = rbTreeMutAt<…>(…)`), with its instance. */
29
+ treeOf(node) {
30
+ while (ts.isParenthesizedExpression(node))
31
+ node = node.expression;
32
+ if (!ts.isIdentifier(node))
33
+ return undefined;
34
+ const l = this.lookup(node.text);
35
+ if (l?.type.kind !== "rbTree")
36
+ return undefined;
37
+ return { local: l, inst: this.model.rbTrees.get(l.type.inst), writable: l.type.writable };
38
+ }
39
+ /**
40
+ * `const x = loadRawAt<T>(…)` and the other views, or `const o = tree.get(k)` / `remove` / `min` / `max` / `nodeAt`
41
+ * when it hands out a reference into a node: declared here (true), else left to the general binding (false).
42
+ */
43
+ bindView(d, init, name, c, mutable) {
44
+ while (ts.isParenthesizedExpression(init))
45
+ init = init.expression;
46
+ const fn = this.viewFn(init);
47
+ if (fn) {
48
+ if (mutable)
49
+ this.fail(d, `bind ${fn}(…) with const`);
50
+ const call = init;
51
+ // Views of account data (two may share bytes under NATIVE_ACCOUNT_WRITES), each ended by a resize of its account.
52
+ const view = { view: true, viewAcct: this.viewAccountKey(call.arguments[0]), decl: d };
53
+ if (fn === "loadRawAt" || fn === "loadRawMutAt") {
54
+ const v = this.loadRawAt(call, fn === "loadRawMutAt");
55
+ this.line(`${valueC(v.type)}${c} = ${v.c};`);
56
+ this.scopes.at(-1).set(name, { c, type: v.type, mutable: false, paths: [`@${c}`], ...view });
57
+ }
58
+ else if (fn === "rawArrayAt" || fn === "rawArrayMutAt") {
59
+ const type = this.rawArrayAt(call, fn === "rawArrayMutAt", c);
60
+ this.scopes.at(-1).set(name, { c, type, mutable: false, paths: [`@${c}`], ...view });
61
+ }
62
+ else {
63
+ const type = this.rbTreeAt(call, fn === "rbTreeMutAt", c);
64
+ this.scopes.at(-1).set(name, { c, type, mutable: false, ...view });
65
+ }
66
+ return true;
67
+ }
68
+ if (ts.isCallExpression(init) && ts.isPropertyAccessExpression(init.expression) && TREE_REFS.has(init.expression.name.text)) {
69
+ const tree = this.treeOf(init.expression.expression);
70
+ const method = init.expression.name.text;
71
+ if (!tree)
72
+ return false;
73
+ const ref = method === "min" || method === "max" || method === "nodeAt" || !isScalar(tree.inst.valueType);
74
+ if (!ref)
75
+ return false;
76
+ if (mutable)
77
+ this.fail(d, `bind ${method}(…) with const: it refers to a node of the tree`);
78
+ const v = this.treeCall(init).value;
79
+ const ct = valueC(v.type);
80
+ this.line(`${ct.endsWith("*") ? ct : `${ct} `}${c} = ${v.c};`);
81
+ this.scopes.at(-1).set(name, { c, type: v.type, mutable: false, paths: [`@${tree.local.c}[]`], decl: d });
82
+ return true;
83
+ }
84
+ return false;
85
+ }
86
+ /** The struct type argument of loadRawAt<T>: a fixed-size struct without a BigVec. */
87
+ rawAtStruct(node, fn) {
88
+ const targ = node.typeArguments?.[0];
89
+ const s = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? this.model.structs.get(targ.typeName.text) : undefined;
90
+ if (!s || s.size === undefined || s.vec) {
91
+ if (s?.bigVec)
92
+ this.fail(node, `${s.name} ends in a BigVec, whose room runs to the end of the account: read it with loadRaw / loadRawMut, from byte 0`);
93
+ this.fail(node, `${fn} needs a fixed-size struct type: ${fn}<MyStruct>(account, offset)`);
94
+ }
95
+ if (s.layout === "borsh")
96
+ this.fail(node, `${s.name} is @layout borsh: ${fn} reads fixed layouts only`);
97
+ return s;
98
+ }
99
+ /** A u64 argument evaluated into a temporary, in argument order. */
100
+ u64Arg(node, prefix) {
101
+ const t = this.tmp(prefix);
102
+ this.line(`uint64_t ${t} = ${this.expect(this.expr(node, U64), U64, node).c};`);
103
+ return t;
104
+ }
105
+ /** The view's account and offset (and capacity), evaluated left to right, then the owner check (3007). */
106
+ viewStart(node, fn, mut, counts) {
107
+ const want = counts ? 3 : 2;
108
+ const extra = fn.startsWith("rbTree") ? 4 : want;
109
+ if (node.arguments.length < want || node.arguments.length > extra)
110
+ this.fail(node, counts
111
+ ? `${fn}<…>(account, offset, capacity${fn.startsWith("rbTree") ? ", compare?" : ""}) takes the account, the byte offset and the element count`
112
+ : `${fn}<T>(account, offset) takes one remaining account or AccountInfo parameter and the byte offset`);
113
+ const { h, param } = this.rawAccount(node, fn, mut);
114
+ const off = this.u64Arg(node.arguments[1], "off");
115
+ const cap = counts ? this.u64Arg(node.arguments[2], "cap") : undefined;
116
+ this.line(this.viewOwnerCheck(h));
117
+ return { h, param, off, cap };
118
+ }
119
+ /** `loadRawAt<T>(acct, offset)` / `loadRawMutAt`: a fixed-layout struct at a run-time byte offset. */
120
+ loadRawAt(node, mut) {
121
+ const fn = mut ? "loadRawMutAt" : "loadRawAt";
122
+ const s = this.rawAtStruct(node, fn);
123
+ const { h, param, off } = this.viewStart(node, fn, mut, false);
124
+ this.line(`if (${off} > ${h}->data_len || ${h}->data_len - ${off} < sizeof(TSS_${s.name})) ${this.programErrorFail("AccountDataTooSmall", node)};`);
125
+ if (mut)
126
+ this.claimRawMut(node, h, param);
127
+ return { c: `((TSS_${s.name} *)(${h}->data + ${off}))`, type: { kind: "structRef", struct: s.name, writable: mut } };
128
+ }
129
+ /** `rawArrayAt<T>(acct, offset, capacity)` / `rawArrayMutAt`: `capacity` elements in place, bound to `c` (and `c__n`). */
130
+ rawArrayAt(node, mut, c) {
131
+ const fn = mut ? "rawArrayMutAt" : "rawArrayAt";
132
+ const targ = node.typeArguments?.[0];
133
+ const elem = targ && node.typeArguments.length === 1 ? this.localElem(targ) : undefined;
134
+ if (!elem)
135
+ this.fail(node, `${fn}<T>: T is an integer, boolean, Pubkey, enum, FixedString<N> or a fixed-size struct (one type argument)`);
136
+ const size = this.fieldBytes(elem);
137
+ const { h, param, off, cap } = this.viewStart(node, fn, mut, true);
138
+ const bytes = this.tmp("bytes");
139
+ this.line(`uint64_t ${bytes};`);
140
+ this.line(`if (ts_mul_overflow_u64(${cap}, ${size}, &${bytes}) || ${off} > ${h}->data_len || ${h}->data_len - ${off} < ${bytes}) ${this.programErrorFail("AccountDataTooSmall", node)};`);
141
+ if (mut)
142
+ this.claimRawMut(node, h, param);
143
+ this.line(`${fieldC(elem)} *${c} = (${fieldC(elem)} *)(${h}->data + ${off});`);
144
+ this.line(`uint64_t ${c}__n = ${cap};`);
145
+ // Named in scope, so a loop over it moved into a function of its own is given the count (see outlinedLoop).
146
+ this.scopes.at(-1).set(`__${c}__n`, { c: `${c}__n`, type: U64, mutable: false });
147
+ return { kind: "rawArray", elem, writable: mut };
148
+ }
149
+ /** The place a RawArray local names: a list of `n` elements with no stored length (see Ref.vec). */
150
+ rawArrayRef(l) {
151
+ const t = l.type;
152
+ return {
153
+ lv: l.c,
154
+ type: { kind: "vec", elem: t.elem, big: true, raw: true },
155
+ writable: t.writable,
156
+ vec: { len: `${l.c}__n`, items: l.c, fixed: "", elemSize: this.fieldBytes(t.elem), resizable: false, big: `${l.c}__n`, slice: true, raw: true },
157
+ };
158
+ }
159
+ /** Rust's alignment of a field type (repr(C), as on SBF): for the node layout check. */
160
+ alignOf(t) {
161
+ switch (t.kind) {
162
+ case "int":
163
+ return Math.min(INT_INFO[t.name].bytes, 8);
164
+ case "struct":
165
+ return Math.max(1, ...this.model.structs.get(t.name).fields.map((f) => this.alignOf(f.type)));
166
+ case "array":
167
+ return this.alignOf(t.elem);
168
+ case "fstring":
169
+ return 4;
170
+ default:
171
+ return 1;
172
+ }
173
+ }
174
+ /** Why the default order cannot compare this key type, or undefined. */
175
+ unordered(t) {
176
+ if (t.kind === "int" || t.kind === "bool" || t.kind === "enum" || t.kind === "pubkey")
177
+ return undefined;
178
+ if (t.kind === "array")
179
+ return this.unordered(t.elem);
180
+ if (t.kind === "struct") {
181
+ for (const f of this.model.structs.get(t.name).fields) {
182
+ const why = this.unordered(f.type);
183
+ if (why)
184
+ return why;
185
+ }
186
+ return undefined;
187
+ }
188
+ return `a ${typeName(t)} field`;
189
+ }
190
+ /**
191
+ * `rbTreeAt<K, V>(acct, offset, capacity, compare?)` / `rbTreeMutAt`: lib-sokoban 0.3's RedBlackTree<K, V, capacity>
192
+ * at a run-time offset (32 + capacity × (16 + size(K) + size(V)) bytes), bound to `c` (a TsRbt).
193
+ */
194
+ rbTreeAt(node, mut, c) {
195
+ const fn = mut ? "rbTreeMutAt" : "rbTreeAt";
196
+ const [kn, vn] = node.typeArguments ?? [];
197
+ if (!kn || !vn || node.typeArguments.length !== 2)
198
+ this.fail(node, `${fn}<K, V>(account, offset, capacity, compare?) takes the key and value types`);
199
+ const key = this.localElem(kn);
200
+ const value = this.localElem(vn);
201
+ if (!key || key.kind === "fstring")
202
+ this.fail(kn, `${fn}: the key is an integer, boolean, Pubkey, enum or fixed-size struct`);
203
+ if (!value || !(isScalar(value) || value.kind === "struct"))
204
+ this.fail(vn, `${fn}: the value is an integer, boolean, Pubkey, enum or fixed-size struct`);
205
+ const ks = this.fieldBytes(key);
206
+ const vs = this.fieldBytes(value);
207
+ const stride = 16 + ks + vs;
208
+ // sokoban's assert_proper_alignment, and the padding Rust's repr(C) RBNode { key, value } would hold: TypeSOL
209
+ // structs are packed, so the bytes match only when there is none (spell padding out as fields, as Rust ports do).
210
+ if (stride % 8) {
211
+ const pad = 8 - (stride % 8);
212
+ // Padding is spelled out as fields, so it goes in a struct: the value's, else the key's, else one to wrap the value.
213
+ const where = value.kind === "struct"
214
+ ? `add ${pad} bytes of padding to ${typeName(value)}`
215
+ : key.kind === "struct"
216
+ ? `add ${pad} bytes of padding to ${typeName(key)}`
217
+ : `a ${typeName(value)} value has no room for padding: make the value a struct holding it and ${pad} bytes of padding fields`;
218
+ this.fail(node, `a node is 16 + ${ks} + ${vs} = ${stride} bytes, not a multiple of 8 (sokoban asserts it): ${where}`);
219
+ }
220
+ if (ks % this.alignOf(key) || vs % this.alignOf(value) || ks % this.alignOf(value))
221
+ this.fail(node, `Rust would pad RBNode<${typeName(key)}, ${typeName(value)}> (alignment): give the key and value sizes that are multiples of their alignment`);
222
+ const cmpNode = node.arguments[3];
223
+ let compare;
224
+ if (cmpNode) {
225
+ const name = ts.isIdentifier(cmpNode) ? calleeName(cmpNode, this.model.helperDecls, this.checker) : undefined;
226
+ if (name && this.model.generics.has(name))
227
+ this.fail(cmpNode, `the comparator is a plain function (not generic): (a: ${typeName(key)}, b: ${typeName(key)}) => i8`);
228
+ compare = name ? this.model.helpers.get(name) : undefined;
229
+ if (!compare)
230
+ this.fail(cmpNode, `the comparator is a named function (a: ${typeName(key)}, b: ${typeName(key)}) => i8, declared in the program`);
231
+ const ok = (p) => !p.account && (p.type.kind === "structRef" ? key.kind === "struct" && p.type.struct === key.name : sameType(p.type, key));
232
+ if (compare.params.length !== 2 || !compare.params.every(ok) || compare.returns?.kind !== "int")
233
+ this.fail(cmpNode, `${compare.display} must take two ${typeName(key)} keys and return an integer (negative, 0 or positive): (a: ${typeName(key)}, b: ${typeName(key)}) => i8`);
234
+ // An unsigned result can never say "less", so every search would go one way and the tree would be out of order.
235
+ const ret = compare.returns;
236
+ if (!INT_INFO[ret.name].signed)
237
+ this.fail(cmpNode, `${compare.display} returns ${ret.name}, which cannot be negative: a comparator returns a signed integer (negative when a sorts first, 0, positive), (a: ${typeName(key)}, b: ${typeName(key)}) => i8`);
238
+ }
239
+ else {
240
+ const why = this.unordered(key);
241
+ if (why)
242
+ this.fail(kn, `${typeName(key)} has no default order (${why}): pass a comparator, ${fn}<K, V>(account, offset, capacity, compare)`);
243
+ }
244
+ const instKey = `${typeName(key)}|${typeName(value)}|${compare?.name ?? ""}`;
245
+ if (!this.model.rbTrees.has(instKey))
246
+ this.model.rbTrees.set(instKey, {
247
+ key: instKey,
248
+ c: `ts_rbt${this.model.rbTrees.size}`,
249
+ keyType: key,
250
+ valueType: value,
251
+ keySize: ks,
252
+ valueSize: vs,
253
+ stride,
254
+ compare,
255
+ });
256
+ const { h, param, off, cap } = this.viewStart(node, fn, mut, true);
257
+ const bytes = this.tmp("bytes");
258
+ this.line(`uint64_t ${bytes};`);
259
+ // bump_index is a u32 that reaches capacity + 1: a capacity of u32::MAX or more has no tree (no account holds one).
260
+ this.line(`if (${cap} >= 0xFFFFFFFFULL || ts_mul_overflow_u64(${cap}, ${stride}, &${bytes}) || ts_add_overflow_u64(${bytes}, 32, &${bytes}) || ${off} > ${h}->data_len || ${h}->data_len - ${off} < ${bytes}) ${this.programErrorFail("AccountDataTooSmall", node)};`);
261
+ if (mut)
262
+ this.claimRawMut(node, h, param);
263
+ this.line(`TsRbt ${c} = {${h}->data + ${off}, ${cap}};`);
264
+ return { kind: "rbTree", inst: instKey, writable: mut };
265
+ }
266
+ /** A pointer to a key or value given to a tree method: a struct place as it is, anything else in a temporary. */
267
+ treeOperand(node, t) {
268
+ if (t.kind === "struct") {
269
+ let inner = node;
270
+ while (ts.isParenthesizedExpression(inner))
271
+ inner = inner.expression;
272
+ if (ts.isObjectLiteralExpression(inner)) {
273
+ const tmp = this.tmp("rbk");
274
+ this.line(`TSS_${t.name} ${tmp};`);
275
+ this.writeAggregate({ lv: tmp, type: t, writable: true }, inner, true);
276
+ return `(&${tmp})`;
277
+ }
278
+ const place = this.structPlace(node);
279
+ if (!place)
280
+ this.fail(node, `expected a ${t.name}: an object literal or another ${t.name}`);
281
+ if (place.struct !== t.name)
282
+ this.fail(node, `expected a ${t.name}, got a ${place.struct}`);
283
+ return place.ptr;
284
+ }
285
+ const vt = this.storageValueType(t);
286
+ if (!vt || t.kind === "fstring")
287
+ this.fail(node, `a ${typeName(t)} key or value is not supported here`);
288
+ const v = this.expect(this.expr(node, vt), vt, node);
289
+ const tmp = this.tmp("rbv");
290
+ if (t.kind === "pubkey")
291
+ this.line(`SolPubkey ${tmp} = *(${v.c});`);
292
+ else
293
+ this.line(`${fieldC(t)} ${tmp} = ${v.c};`);
294
+ return `(&${tmp})`;
295
+ }
296
+ /** The value stored in node `idx` (0: none) as an expression result: a nullable reference, or an Option copy. */
297
+ nodeValue(tree, idx) {
298
+ const { inst } = tree;
299
+ const off = 16 + inst.keySize;
300
+ const at = `(ts_rbt_node(&${tree.local.c}, ${inst.stride}, ${idx}) + ${off})`;
301
+ if (inst.valueType.kind === "struct") {
302
+ const p = this.tmp("rbval");
303
+ this.line(`TSS_${inst.valueType.name} *${p} = ${idx} ? (TSS_${inst.valueType.name} *)${at} : NULL;`);
304
+ return { c: p, type: { kind: "structRef", struct: inst.valueType.name, writable: tree.writable, nullable: true } };
305
+ }
306
+ const scalar = inst.valueType;
307
+ this.model.options.set(optionKey(scalar), scalar);
308
+ const o = this.tmp("rbopt");
309
+ this.line(`${optC(scalar)} ${o};`);
310
+ this.line(`${o}.some = ${idx} != 0;`);
311
+ this.line(`if (${idx}) ts_memcpy(&${o}.v, ${at}, ${inst.valueSize}); else ts_memzero(&${o}.v, ${inst.valueSize});`);
312
+ return { c: o, type: { kind: "option", inner: scalar } };
313
+ }
314
+ treeCall(node) {
315
+ const callee = node.expression;
316
+ if (!ts.isPropertyAccessExpression(callee))
317
+ return undefined;
318
+ this.unbound(callee.expression);
319
+ const tree = this.treeOf(callee.expression);
320
+ if (!tree)
321
+ return undefined;
322
+ const { inst, local } = tree;
323
+ const t = local.c;
324
+ const S = inst.stride;
325
+ const method = callee.name.text;
326
+ const args = node.arguments;
327
+ const arity = (n, form) => {
328
+ if (args.length !== n)
329
+ this.fail(node, `${method}(${form}) takes ${n === 0 ? "no arguments" : form}`);
330
+ };
331
+ const writes = () => {
332
+ if (!tree.writable)
333
+ this.fail(node, `${method}() changes the tree: make it with rbTreeMutAt`);
334
+ if (this.iteratingTrees.has(t))
335
+ this.fail(node, `${method}() would change the tree a for … of is walking: collect the keys in the loop, then ${method} after it (as Rust's borrow requires)`);
336
+ for (const walked of this.iteratingTrees.values())
337
+ if (this.mayBeSameAccount(walked.acct, local.viewAcct ?? "?"))
338
+ this.fail(node, `${method}() changes a tree that may be ${walked.name}, which a for … of is walking (a view of an account that may be the same one): collect the keys in the loop, then ${method} after it (as Rust's borrow requires)`);
339
+ };
340
+ switch (method) {
341
+ case "initialize": {
342
+ arity(0, "");
343
+ writes();
344
+ this.line(`ts_rbt_initialize(&${t});`);
345
+ return { value: undefined };
346
+ }
347
+ case "insert": {
348
+ arity(2, "key, value");
349
+ writes();
350
+ // An insert may reuse a freed node or overwrite a value: references into the tree's nodes end here.
351
+ this.assertNotAliased([`@${t}`], node);
352
+ const k = this.treeOperand(args[0], inst.keyType);
353
+ const v = this.treeOperand(args[1], inst.valueType);
354
+ const r = this.tmp("rbi");
355
+ this.line(`uint32_t ${r};`);
356
+ this.line(`TS_TRY(${inst.c}_insert(params, &${t}, ${k}, ${v}, &${r}));`);
357
+ this.model.options.set("u32", U32);
358
+ const o = this.tmp("rbopt");
359
+ this.line(`${optC(U32)} ${o};`);
360
+ this.line(`${o}.some = ${r} != 0;`);
361
+ this.line(`${o}.v = ${r};`);
362
+ return { value: { c: o, type: { kind: "option", inner: U32 } } };
363
+ }
364
+ case "remove":
365
+ case "get":
366
+ case "addrOf": {
367
+ arity(1, "key");
368
+ if (method === "remove")
369
+ writes();
370
+ const k = this.treeOperand(args[0], inst.keyType);
371
+ const r = this.tmp("rbi");
372
+ this.line(`uint32_t ${r};`);
373
+ this.line(`TS_TRY(${inst.c}_${method === "remove" ? "remove" : "find"}(params, &${t}, ${k}, &${r}));`);
374
+ if (method === "addrOf")
375
+ return { value: { c: r, type: U32 } };
376
+ return { value: this.nodeValue(tree, r) };
377
+ }
378
+ case "removeAt": {
379
+ // remove(key) for a node already found (addrOf, an entry's index): the same writes, no second search.
380
+ arity(1, "index");
381
+ writes();
382
+ const i = this.expect(this.expr(args[0], U32), U32, args[0]);
383
+ const r = this.tmp("rbi");
384
+ this.line(`uint32_t ${r} = ${inst.c}_remove_at(&${t}, ${i.c});`);
385
+ return { value: this.nodeValue(tree, r) };
386
+ }
387
+ case "min":
388
+ case "max": {
389
+ arity(0, "");
390
+ const r = this.tmp("rbi");
391
+ this.line(`uint32_t ${r} = ts_rbt_find_${method}(&${t}, ${S}, TS_RBT_ROOT(${t}.base));`);
392
+ const e = this.tmp("rbe");
393
+ this.line(`TsRbtEntry ${e} = {${r} ? ts_rbt_node(&${t}, ${S}, ${r}) : NULL, ${r}};`);
394
+ return { value: { c: e, type: { kind: "rbEntry", inst: inst.key, writable: tree.writable, nullable: true } } };
395
+ }
396
+ case "nodeAt": {
397
+ arity(1, "index");
398
+ // sokoban's get_node(i): node i whether or not it holds a key; 0 or past the capacity panics as Rust's indexing.
399
+ const i = this.expect(this.expr(args[0], U32), U32, args[0]);
400
+ const r = this.tmp("rbi");
401
+ this.line(`uint32_t ${r} = ${i.c};`);
402
+ const e = this.tmp("rbe");
403
+ this.line(`TsRbtEntry ${e} = {ts_rbt_node(&${t}, ${S}, ${r}), ${r}};`);
404
+ return { value: { c: e, type: { kind: "rbEntry", inst: inst.key, writable: tree.writable } } };
405
+ }
406
+ case "reversed":
407
+ this.fail(node, "reversed() walks the tree from its largest key in a for … of: for (const e of tree.reversed())");
408
+ }
409
+ this.fail(node, `a RedBlackTree has ${TREE_METHODS}, not ${method}()`);
410
+ }
411
+ /** A tree node a property is read on: an entry local, or `e!` / `tree.min()!` (checked), as a TsRbtEntry. */
412
+ entryOf(node) {
413
+ while (ts.isParenthesizedExpression(node))
414
+ node = node.expression;
415
+ let bang = false;
416
+ if (ts.isNonNullExpression(node)) {
417
+ bang = true;
418
+ node = node.expression;
419
+ while (ts.isParenthesizedExpression(node))
420
+ node = node.expression;
421
+ }
422
+ let v;
423
+ if (ts.isIdentifier(node)) {
424
+ const l = this.lookup(node.text);
425
+ if (l?.type.kind === "rbEntry")
426
+ v = { c: l.c, type: l.type };
427
+ }
428
+ else if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && this.treeOf(node.expression.expression)) {
429
+ const m = node.expression.name.text;
430
+ if (m === "nodeAt" || (bang && (m === "min" || m === "max")))
431
+ v = this.treeCall(node).value;
432
+ }
433
+ if (!v || v.type.kind !== "rbEntry")
434
+ return undefined;
435
+ if (bang && v.type.nullable)
436
+ this.line(`if (${v.c}.index == 0) TS_FAIL(TS_ERR_UNWRAP, "TypeSOL: the tree is empty");`);
437
+ return { c: v.c, inst: this.model.rbTrees.get(v.type.inst), writable: v.type.writable };
438
+ }
439
+ viewRef(node) {
440
+ // `loadRaw<T>(acct).field`, `loadRawAt<T>(acct, offset).inner.b`: a read-only view read where it is made, its checks
441
+ // made there. A writable view claims its account once per instruction: it is bound to a const instead.
442
+ if (ts.isCallExpression(node)) {
443
+ const fn = this.exportName(node.expression);
444
+ if (fn === "loadRaw" || fn === "loadRawAt") {
445
+ const v = fn === "loadRaw" ? this.loadRaw(node, false) : this.loadRawAt(node, false);
446
+ const struct = v.type.struct;
447
+ return { lv: `(*${v.c})`, type: { kind: "struct", name: struct }, writable: false, ...(v.bigCap ? { bigCap: v.bigCap } : {}) };
448
+ }
449
+ if (fn === "loadRawMut" || fn === "loadRawMutAt")
450
+ this.fail(node, `bind ${fn}(…) to a const first, as a writable view claims its account once per instruction: const v = ${fn}<…>(account${fn === "loadRawMutAt" ? ", offset" : ""})`);
451
+ return undefined;
452
+ }
453
+ if (ts.isIdentifier(node)) {
454
+ const l = this.lookup(node.text);
455
+ return l?.type.kind === "rawArray" ? this.rawArrayRef(l) : undefined;
456
+ }
457
+ if (ts.isPropertyAccessExpression(node) && (node.name.text === "key" || node.name.text === "value")) {
458
+ const e = this.entryOf(node.expression);
459
+ if (!e)
460
+ return undefined;
461
+ const { inst } = e;
462
+ if (node.name.text === "key")
463
+ return { lv: `(*(${fieldC(inst.keyType)} *)(${e.c}.node + 16))`, type: inst.keyType, writable: false };
464
+ return { lv: `(*(${fieldC(inst.valueType)} *)(${e.c}.node + ${16 + inst.keySize}))`, type: inst.valueType, writable: e.writable };
465
+ }
466
+ // `o!` on a tree's get / remove result (a nullable reference), or `tree.get(k)!` itself: checked, then the struct.
467
+ if (ts.isNonNullExpression(node)) {
468
+ let inner = node.expression;
469
+ while (ts.isParenthesizedExpression(inner))
470
+ inner = inner.expression;
471
+ let v;
472
+ if (ts.isIdentifier(inner)) {
473
+ const l = this.lookup(inner.text);
474
+ if (l?.type.kind === "structRef" && l.type.nullable)
475
+ v = { c: l.c, type: l.type };
476
+ }
477
+ else if (ts.isCallExpression(inner) && ts.isPropertyAccessExpression(inner.expression) && this.treeOf(inner.expression.expression)) {
478
+ const m = inner.expression.name.text;
479
+ if (m === "get" || m === "remove" || m === "removeAt")
480
+ v = this.treeCall(inner).value;
481
+ }
482
+ if (!v || v.type.kind !== "structRef")
483
+ return undefined;
484
+ this.line(`if (${v.c} == NULL) TS_FAIL(TS_ERR_UNWRAP, "TypeSOL: the key is not in the tree");`);
485
+ return { lv: `(*${v.c})`, type: { kind: "struct", name: v.type.struct }, writable: v.type.writable };
486
+ }
487
+ return undefined;
488
+ }
489
+ /** `rbTreeMutAt(…).min()`, `rawArrayAt(…).get(i)`: a view used without binding it. */
490
+ unbound(node) {
491
+ const fn = this.viewFn(node);
492
+ // loadRawAt(…).field reads in place, loadRawMutAt(…).field names its own fix (viewRef).
493
+ if (fn && fn !== "loadRawAt" && fn !== "loadRawMutAt")
494
+ this.fail(node, `bind ${fn}(…) to a const first: const v = ${fn}<…>(account, offset${fn.startsWith("load") ? "" : ", capacity"})`);
495
+ }
496
+ viewProperty(node) {
497
+ const field = node.name.text;
498
+ // `rbTreeAt(…).length` / `.capacity`: a read-only tree made for the one read.
499
+ let inner = node.expression;
500
+ while (ts.isParenthesizedExpression(inner))
501
+ inner = inner.expression;
502
+ if (this.viewFn(inner) === "rbTreeAt" && (field === "length" || field === "capacity")) {
503
+ const t = this.tmp("rbt");
504
+ this.rbTreeAt(inner, false, t);
505
+ return field === "length" ? { c: `TS_RBT_SIZE(${t}.base)`, type: U64 } : { c: `${t}.cap`, type: U64 };
506
+ }
507
+ this.unbound(node.expression);
508
+ const tree = this.treeOf(node.expression);
509
+ if (tree) {
510
+ if (field === "length")
511
+ return { c: `TS_RBT_SIZE(${tree.local.c}.base)`, type: U64 };
512
+ if (field === "capacity")
513
+ return { c: `${tree.local.c}.cap`, type: U64 };
514
+ this.fail(node.name, `a RedBlackTree has ${TREE_METHODS}, not ${field}`);
515
+ }
516
+ if (field === "index") {
517
+ const e = this.entryOf(node.expression);
518
+ if (e)
519
+ return { c: `${e.c}.index`, type: U32 };
520
+ }
521
+ return undefined;
522
+ }
523
+ }
@@ -60,6 +60,12 @@ export function hintForTypeScript(d, message, libPath) {
60
60
  return "async is not supported: an instruction runs start to finish within one call; remove async";
61
61
  case 2540: // Cannot assign to 'x' because it is a read-only property.
62
62
  return "to change an account, take it as Mut<T> (Mut<Signer> for a signer whose lamports change)";
63
+ case 2344: // Type 'TokenAccount' does not satisfy the constraint 'StakeProgram | SystemProgram | …'.
64
+ if (/\bprogramAt\s*</.test(line))
65
+ return "programAt<P> takes a program: StakeProgram, SystemProgram, TokenProgram, Token2022Program, TokenInterface, AssociatedTokenProgram or MemoProgram (sysvarAt<StakeHistorySysvar> for the sysvar); read other accounts with loadRaw / loadAccount";
66
+ if (/\bsysvarAt\s*</.test(line))
67
+ return "sysvarAt<S> takes StakeHistorySysvar; programs go through programAt<P>";
68
+ return undefined;
63
69
  default:
64
70
  return undefined;
65
71
  }
@@ -209,7 +209,8 @@ function nestGroups(ix, entry) {
209
209
  /** Anchor IDL (spec 0.1.0) so existing Anchor / Codama clients can talk to TypeSOL programs. */
210
210
  export function buildIdl(model, address, version = "0.1.0") {
211
211
  const structs = [...model.structs.values()];
212
- const usedStructs = structs.filter((s) => model.accountStructs.has(s.name) || model.events.has(s.name) || s.size !== undefined);
212
+ // A struct that is not exported is its file's own (helpers and locals): not part of the program's interface.
213
+ const usedStructs = structs.filter((s) => !s.local && (model.accountStructs.has(s.name) || model.events.has(s.name) || s.size !== undefined));
213
214
  const idl = {
214
215
  address,
215
216
  metadata: { name: model.name, version, spec: "0.1.0", description: "Built with TypeSOL" },