@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
@@ -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
+ }
@@ -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" },
@@ -84,11 +84,34 @@ export type ValueType = ScalarType | {
84
84
  | {
85
85
  kind: "epochRewards";
86
86
  }
87
- /** A struct loaded from a remaining account with loadAccount / loadAccountMut. */
87
+ /**
88
+ * A struct loaded from a remaining account with loadAccount / loadAccountMut. `nullable`: a RedBlackTree's
89
+ * `get(k)` / `remove(k)` of a struct value, NULL when the key is absent (narrowed with `x !== null` before use).
90
+ */
88
91
  | {
89
92
  kind: "structRef";
90
93
  struct: string;
91
94
  writable: boolean;
95
+ nullable?: boolean;
96
+ }
97
+ /** `rawArrayAt<T>(acct, offset, capacity)`: `capacity` elements in place at a run-time offset (`T *` + count). */
98
+ | {
99
+ kind: "rawArray";
100
+ elem: FieldType;
101
+ writable: boolean;
102
+ }
103
+ /** `rbTreeAt<K, V>(acct, offset, capacity, compare?)`: lib-sokoban's RedBlackTree in place (a `TsRbt`). */
104
+ | {
105
+ kind: "rbTree";
106
+ inst: string;
107
+ writable: boolean;
108
+ }
109
+ /** A node of a RedBlackTree (min / max / nodeAt / for … of): a `TsRbtEntry`; `nullable` for min / max. */
110
+ | {
111
+ kind: "rbEntry";
112
+ inst: string;
113
+ writable: boolean;
114
+ nullable?: boolean;
92
115
  }
93
116
  /** A data-enum place (local value, argument, or alias into account data): `TS_DE_<name> *`. */
94
117
  | {
@@ -134,7 +157,8 @@ export type FieldType = ScalarType | {
134
157
  * room for N elements. With `heap`, a `Vec<T>` in a `@layout borsh` struct: Anchor's Vec, held on the heap while the
135
158
  * instruction runs (`TSH_*`: length, capacity, elements) and bounded only by the account when it is written back.
136
159
  * With `big`, a `BigVec<T>` (the last field of a struct read with loadRaw): stored like a trailing Vec, its room set by
137
- * the account's size, never resized.
160
+ * the account's size, never resized. With `raw` (and `big`), a `rawArrayAt` view: a run-time count of elements in
161
+ * place, no stored length.
138
162
  */
139
163
  | {
140
164
  kind: "vec";
@@ -143,6 +167,7 @@ export type FieldType = ScalarType | {
143
167
  heap?: true;
144
168
  optional?: true;
145
169
  big?: true;
170
+ raw?: true;
146
171
  };
147
172
  export interface StructField {
148
173
  name: string;
@@ -187,6 +212,8 @@ export interface StructDef {
187
212
  accountDiscriminator: number[];
188
213
  eventDiscriminator: number[];
189
214
  node: ts.InterfaceDeclaration;
215
+ /** Not exported (`interface Pair { … }`): its file's own, for helpers and locals, and left out of the IDL. */
216
+ local?: true;
190
217
  /**
191
218
  * How account data stores it: "fixed" (every field at a fixed offset, the default) or "borsh" (`@layout borsh`:
192
219
  * Anchor's bytes, where strings, Vecs and Options take only what they hold).
@@ -438,6 +465,13 @@ export interface HelperParam {
438
465
  /** `{ kind: "account" }` for account parameters (then `account` says which kind). */
439
466
  type: ValueType;
440
467
  account?: ParamKind;
468
+ /**
469
+ * `Inout<T>`: the caller's place itself, which the helper may change (a pointer, never a copy). `type` is then a
470
+ * writable structRef, an arrayArg, or (for a FixedVec) a vecArg standing in for the place; code reads `inout` first.
471
+ */
472
+ inout?: FieldType & {
473
+ kind: "struct" | "array" | "vec";
474
+ };
441
475
  node: ts.ParameterDeclaration;
442
476
  }
443
477
  /** A function written as `function f(…)`, `const f = (…) => …` or `const f = function (…) {…}`. */
@@ -472,14 +506,19 @@ export interface Helper {
472
506
  fnArgIndexes?: number[];
473
507
  /** The declaring file's `typesol` imports (local name -> export name). */
474
508
  imports: Map<string, string>;
509
+ /** `/** @noinline *\/`: a C function of its own that clang never inlines, so its locals get a stack frame of their own. */
510
+ noinline?: boolean;
475
511
  }
476
512
  /** A top-level compile-time constant. `type` is set when annotated (`const FEE: u16 = 30n`). */
477
513
  export interface ConstDef {
478
514
  name: string;
479
- /** `{ pubkey }` for `const ADMIN = pubkey("…")`: the decoded 32 bytes. */
515
+ /**
516
+ * `{ pubkey }` for `const ADMIN = pubkey("…")`: the decoded 32 bytes; `null` only for ERROR_LOG_PREFIX /
517
+ * PROGRAM_ERROR_LOG_PREFIX (failures that log nothing).
518
+ */
480
519
  value: bigint | boolean | string | {
481
520
  pubkey: number[];
482
- };
521
+ } | null;
483
522
  type?: ScalarType;
484
523
  }
485
524
  /** A data-carrying enum: `export type Action = { kind: "Deposit"; amount: u64 } | { kind: "Pause" }`. */
@@ -574,6 +613,28 @@ export interface ProgramModel {
574
613
  }>;
575
614
  /** Structs read or written with loadBorsh / storeBorsh, filled in while emitting: their ts_bdec_ / ts_benc_ codecs. */
576
615
  borshNative: Set<string>;
616
+ /** RedBlackTree instances (key, value, comparator), filled in while emitting: their per-tree C functions. */
617
+ rbTrees: Map<string, RbTreeInst>;
618
+ /**
619
+ * The program makes views of native accounts (loadRaw, loadRawAt, rawArrayAt, rbTreeAt and their Mut forms): their
620
+ * owner checks share one cache (ts_owned), forgotten at every CPI and owner write. Set before any body is emitted.
621
+ */
622
+ ownerCache?: boolean;
623
+ }
624
+ /**
625
+ * One `rbTreeAt<K, V>(…, compare?)` instantiation: lib-sokoban 0.3's RedBlackTree<K, V, N> over K and V (N is the
626
+ * run-time capacity). `c` is the prefix of its C functions (`ts_rbt<n>_find` …); `compare` the helper ordering keys
627
+ * (`compare(searched, nodeKey)`: negative, 0 or positive), or none for the default order.
628
+ */
629
+ export interface RbTreeInst {
630
+ key: string;
631
+ c: string;
632
+ keyType: FieldType;
633
+ valueType: FieldType;
634
+ keySize: number;
635
+ valueSize: number;
636
+ stride: number;
637
+ compare?: Helper;
577
638
  }
578
639
  export declare function isWritable(k: ParamKind): boolean;
579
640
  export declare function typeName(t: ValueType | FieldType): string;