@typesol/cli 0.42.0 → 0.44.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 (78) hide show
  1. package/CHANGELOG.md +350 -0
  2. package/NOTICE +71 -0
  3. package/README.md +35 -18
  4. package/SECURITY.md +32 -5
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.js +5 -5
  7. package/dist/cli.js +196 -72
  8. package/dist/compiler/analyze.js +447 -12
  9. package/dist/compiler/diagnostics.d.ts +1 -0
  10. package/dist/compiler/diagnostics.js +13 -0
  11. package/dist/compiler/emit/alias.d.ts +45 -1
  12. package/dist/compiler/emit/alias.js +143 -6
  13. package/dist/compiler/emit/base.d.ts +28 -1
  14. package/dist/compiler/emit/base.js +77 -9
  15. package/dist/compiler/emit/borsh.js +11 -5
  16. package/dist/compiler/emit/calls.d.ts +80 -0
  17. package/dist/compiler/emit/calls.js +612 -54
  18. package/dist/compiler/emit/cpi-core.d.ts +23 -4
  19. package/dist/compiler/emit/cpi-core.js +261 -12
  20. package/dist/compiler/emit/cpi.js +8 -2
  21. package/dist/compiler/emit/create.js +3 -0
  22. package/dist/compiler/emit/expressions.js +44 -8
  23. package/dist/compiler/emit/function.js +10 -0
  24. package/dist/compiler/emit/program.js +30 -1
  25. package/dist/compiler/emit/rbtree.d.ts +7 -0
  26. package/dist/compiler/emit/rbtree.js +142 -0
  27. package/dist/compiler/emit/shared.d.ts +25 -0
  28. package/dist/compiler/emit/shared.js +45 -4
  29. package/dist/compiler/emit/statements.d.ts +27 -1
  30. package/dist/compiler/emit/statements.js +305 -23
  31. package/dist/compiler/emit/storage.d.ts +25 -2
  32. package/dist/compiler/emit/storage.js +116 -64
  33. package/dist/compiler/emit/token.js +2 -2
  34. package/dist/compiler/emit/views.d.ts +60 -0
  35. package/dist/compiler/emit/views.js +523 -0
  36. package/dist/compiler/idl.js +2 -1
  37. package/dist/compiler/index.d.ts +15 -1
  38. package/dist/compiler/index.js +40 -3
  39. package/dist/compiler/model.d.ts +65 -4
  40. package/dist/compiler/model.js +14 -0
  41. package/dist/compiler/toolchain.d.ts +56 -1
  42. package/dist/compiler/toolchain.js +246 -12
  43. package/dist/testing-stake.d.ts +2 -1
  44. package/dist/testing-stake.js +2 -1
  45. package/dist/testing.js +6 -4
  46. package/dist/tools/clientgen.d.ts +15 -0
  47. package/dist/tools/clientgen.js +173 -7
  48. package/dist/tools/cpigen.d.ts +0 -15
  49. package/dist/tools/cpigen.js +19 -8
  50. package/dist/tools/doctor.d.ts +17 -2
  51. package/dist/tools/doctor.js +64 -4
  52. package/dist/tools/portgen.js +43 -18
  53. package/dist/workspace.d.ts +20 -0
  54. package/dist/workspace.js +173 -6
  55. package/docs/ai.md +10 -5
  56. package/docs/architecture.md +10 -3
  57. package/docs/audit.md +63 -17
  58. package/docs/case-study-escrow.md +1 -1
  59. package/docs/case-study-phoenix.md +226 -0
  60. package/docs/case-study-raydium-amm.md +3 -3
  61. package/docs/case-study-spl-stake-pool.md +5 -5
  62. package/docs/cli.md +17 -8
  63. package/docs/client.md +11 -3
  64. package/docs/errors.md +1 -1
  65. package/docs/language.md +148 -12
  66. package/docs/mainnet.md +21 -10
  67. package/docs/migrate-from-anchor.md +3 -1
  68. package/docs/runtime.md +12 -2
  69. package/docs/security-model.md +38 -6
  70. package/docs/stability.md +42 -4
  71. package/docs/testing.md +25 -0
  72. package/docs/troubleshooting.md +17 -2
  73. package/lib/typesol.d.ts +221 -4
  74. package/llms-full.txt +336 -65
  75. package/llms.txt +2 -2
  76. package/package.json +4 -2
  77. package/runtime/typesol_rt.h +429 -13
  78. package/test/programs/LICENSE-Apache-2.0.txt +201 -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" },
@@ -5,7 +5,7 @@ import { type Sbpf } from "./toolchain.js";
5
5
  import type { ProgramModel } from "./model.js";
6
6
  export { CompileError, formatDiagnostic, type Diagnostic } from "./diagnostics.js";
7
7
  export type { ProgramModel } from "./model.js";
8
- export { SBPF_VERSIONS, type Sbpf } from "./toolchain.js";
8
+ export { SBPF_VERSIONS, TESTED_TOOLCHAIN, type Sbpf } from "./toolchain.js";
9
9
  /** The hint the CLI adds under a TypeScript error (what to write instead in a TypeSOL program), for the editor plugin. */
10
10
  export declare function typescriptHint(d: ts.Diagnostic): string | undefined;
11
11
  export interface Generated {
@@ -20,7 +20,15 @@ export declare function generate(entry: string, opts?: EmitOptions): Generated;
20
20
  export interface BuildManifest {
21
21
  program: string;
22
22
  compiler: string;
23
+ /** The first line of `clang --version`: the compiler of the generated C. */
23
24
  clang: string;
25
+ /** The platform-tools version (`v1.52`), when the SDK's layout tells it for sure (from 0.44.0). */
26
+ platformTools?: string;
27
+ /** The machine that built it: `process.platform` and `process.arch` (from 0.44.0). */
28
+ host?: {
29
+ os: string;
30
+ arch: string;
31
+ };
24
32
  /** The TypeScript version that type-checked the sources (pinned: it decides what compiles). */
25
33
  typescript: string;
26
34
  sbpf: Sbpf;
@@ -45,6 +53,12 @@ export declare function build(entry: string, outDir: string, programAddress: str
45
53
  }): BuildResult;
46
54
  /** The package version (one source: package.json), recorded in build manifests and shown by the CLI. */
47
55
  export declare const COMPILER_VERSION: string;
56
+ /** A build's toolchain in one line: `clang 20.1.7-rust-dev (…), platform-tools v1.52, darwin-arm64, TypeSOL 0.44.0`. */
57
+ export declare function describeToolchain(m: Pick<BuildManifest, "clang" | "platformTools" | "host" | "compiler">): string;
58
+ /** What differs between two builds' toolchains and compilers (the fields both record), e.g. ["clang", "TypeSOL version"]. */
59
+ export declare function toolchainDifferences(a: Partial<BuildManifest>, b: Partial<BuildManifest>): string[];
60
+ /** The ELF's own length (it ends with the section header table): a program account keeps it zero-padded. */
61
+ export declare function elfLength(elf: Buffer): number;
48
62
  /**
49
63
  * Whether `deployed` (a .so, e.g. from `solana program dump`) is exactly what `entry` builds to. Program accounts
50
64
  * keep the ELF zero-padded to their allocation, so trailing zeros are ignored.
@@ -7,10 +7,10 @@ import { analyze, LIB_PATH } from "./analyze.js";
7
7
  import { hintForTypeScript } from "./hints.js";
8
8
  import { emitProgram } from "./emit/index.js";
9
9
  import { buildIdl } from "./idl.js";
10
- import { buildSharedObject, toolchainVersion } from "./toolchain.js";
10
+ import { buildSharedObject, checkToolchain, shortClang, TESTED_TOOLCHAIN } from "./toolchain.js";
11
11
  import { RUNTIME_DIR } from "./toolchain.js";
12
12
  export { CompileError, formatDiagnostic } from "./diagnostics.js";
13
- export { SBPF_VERSIONS } from "./toolchain.js";
13
+ export { SBPF_VERSIONS, TESTED_TOOLCHAIN } from "./toolchain.js";
14
14
  /** The hint the CLI adds under a TypeScript error (what to write instead in a TypeSOL program), for the editor plugin. */
15
15
  export function typescriptHint(d) {
16
16
  return hintForTypeScript(d, ts.flattenDiagnosticMessageText(d.messageText, "\n"), LIB_PATH);
@@ -33,6 +33,8 @@ export function build(entry, outDir, programAddress, opts = {}) {
33
33
  const soPath = `${base}.so`;
34
34
  const idlPath = `${base}.json`;
35
35
  writeFileSync(cPath, gen.c);
36
+ // Before clang runs: an untested toolchain is a warning (once), or an error in strict mode.
37
+ const toolchain = checkToolchain();
36
38
  buildSharedObject(cPath, soPath, opts.sbpf);
37
39
  const idl = buildIdl(gen.model, programAddress);
38
40
  writeFileSync(idlPath, JSON.stringify(idl, null, 2) + "\n");
@@ -44,7 +46,9 @@ export function build(entry, outDir, programAddress, opts = {}) {
44
46
  const manifest = {
45
47
  program: gen.model.name,
46
48
  compiler: COMPILER_VERSION,
47
- clang: toolchainVersion(),
49
+ clang: toolchain.clang,
50
+ ...(toolchain.platformTools ? { platformTools: toolchain.platformTools } : {}),
51
+ host: { os: process.platform, arch: process.arch },
48
52
  typescript: ts.version,
49
53
  sbpf: opts.sbpf ?? "v0",
50
54
  profile: !!opts.profile,
@@ -57,6 +61,39 @@ export function build(entry, outDir, programAddress, opts = {}) {
57
61
  }
58
62
  /** The package version (one source: package.json), recorded in build manifests and shown by the CLI. */
59
63
  export const COMPILER_VERSION = createRequire(import.meta.url)("../../package.json").version;
64
+ /** A build's toolchain in one line: `clang 20.1.7-rust-dev (…), platform-tools v1.52, darwin-arm64, TypeSOL 0.44.0`. */
65
+ export function describeToolchain(m) {
66
+ return [
67
+ shortClang(m.clang),
68
+ `platform-tools ${m.platformTools ?? "unknown"}`,
69
+ m.host ? `${m.host.os}-${m.host.arch}` : "host unknown",
70
+ `TypeSOL ${m.compiler}`,
71
+ ...(m.clang === TESTED_TOOLCHAIN.clang ? ["the tested toolchain"] : []),
72
+ ].join(", ");
73
+ }
74
+ /** What differs between two builds' toolchains and compilers (the fields both record), e.g. ["clang", "TypeSOL version"]. */
75
+ export function toolchainDifferences(a, b) {
76
+ const out = [];
77
+ if (a.compiler !== b.compiler)
78
+ out.push("TypeSOL version");
79
+ if (a.clang !== b.clang)
80
+ out.push("clang");
81
+ if (a.platformTools && b.platformTools && a.platformTools !== b.platformTools)
82
+ out.push("platform-tools");
83
+ if (a.typescript !== b.typescript)
84
+ out.push("TypeScript");
85
+ if (a.sbpf !== b.sbpf)
86
+ out.push("SBPF version");
87
+ // The host is recorded, not compared: one clang version is meant to give the same bytes on every host.
88
+ return out;
89
+ }
90
+ /** The ELF's own length (it ends with the section header table): a program account keeps it zero-padded. */
91
+ export function elfLength(elf) {
92
+ if (elf.length < 0x40 || elf.readUInt32BE(0) !== 0x7f454c46)
93
+ return elf.length;
94
+ const end = Number(elf.readBigUInt64LE(0x28)) + elf.readUInt16LE(0x3a) * elf.readUInt16LE(0x3c);
95
+ return end > 0 && end <= elf.length ? end : elf.length;
96
+ }
60
97
  /**
61
98
  * Whether `deployed` (a .so, e.g. from `solana program dump`) is exactly what `entry` builds to. Program accounts
62
99
  * keep the ELF zero-padded to their allocation, so trailing zeros are ignored.