@typesol/cli 0.39.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,6 +4,7 @@ import { calleeName, resolveValueType } from "../analyze.js";
4
4
  import { INT_INFO, unsignedC, optionKey, sameType, typeName } from "../model.js";
5
5
  import { U64, U8, I64, BOOL, PUBKEY, STRING, HASH, cString, intLiteral, scalarStorageC, optC, valueC, vecCount } from "./shared.js";
6
6
  import { StorageEmitter } from "./storage.js";
7
+ import { unsupportedSyntax } from "../hints.js";
7
8
  /**
8
9
  * Expressions: literals, operators with checked arithmetic, property reads, conditionals, text and casts.
9
10
  */
@@ -99,6 +100,86 @@ export class ExpressionEmitter extends StorageEmitter {
99
100
  this.lines[declAt] = `${" ".repeat(this.indent)}${optC(scalar)} ${t};\n${" ".repeat(this.indent)}ts_memzero(&${t}, sizeof(${t}));`;
100
101
  return { c: t, type: { kind: "option", inner: scalar } };
101
102
  }
103
+ /**
104
+ * `xs.find(cb)!.a.b` and `xs.find(cb)?.a` on a list of structs: the element is located with findIndex, then read as
105
+ * `xs.get(i).a.b`. With `!` an element that is not found fails the instruction (5108, as `x!` on an empty Option);
106
+ * with `?.` the field comes back as an Option, empty when nothing matched. Undefined for any other expression.
107
+ */
108
+ foundAccess(node, hint) {
109
+ if (!ts.isPropertyAccessExpression(node))
110
+ return undefined;
111
+ const names = [];
112
+ let e = node;
113
+ let optional = false;
114
+ while (ts.isPropertyAccessExpression(e)) {
115
+ names.unshift(e.name);
116
+ if (e.questionDotToken)
117
+ optional = true;
118
+ e = e.expression;
119
+ while (ts.isParenthesizedExpression(e))
120
+ e = e.expression;
121
+ }
122
+ let bang = false;
123
+ if (ts.isNonNullExpression(e)) {
124
+ bang = true;
125
+ e = e.expression;
126
+ while (ts.isParenthesizedExpression(e))
127
+ e = e.expression;
128
+ }
129
+ if (!ts.isCallExpression(e) || !ts.isPropertyAccessExpression(e.expression) || e.expression.name.text !== "find")
130
+ return undefined;
131
+ if (!bang && !optional)
132
+ return undefined;
133
+ if (bang && optional)
134
+ return undefined; // `find(…)!.x?.y`: not this shape
135
+ const list = e.expression.expression;
136
+ if (this.isRemaining(list))
137
+ return undefined;
138
+ const f = ts.factory;
139
+ const place = (n) => {
140
+ ts.setTextRange(n, node);
141
+ n.parent = node.parent;
142
+ return n;
143
+ };
144
+ const findIndex = place(f.createCallExpression(place(f.createPropertyAccessExpression(list, "findIndex")), undefined, e.arguments));
145
+ const at = this.expr(findIndex);
146
+ const found = this.tmp("found");
147
+ this.line(`int64_t ${found} = ${at.c};`);
148
+ const index = `__found${this.temp++}`;
149
+ this.scopes.at(-1).set(index, { c: `((uint64_t)${found})`, type: U64, mutable: false });
150
+ let access = place(f.createCallExpression(place(f.createPropertyAccessExpression(list, "get")), undefined, [place(f.createIdentifier(index))]));
151
+ for (const n of names)
152
+ access = place(f.createPropertyAccessExpression(access, n));
153
+ if (bang && !optional) {
154
+ this.line(`if (${found} < 0) TS_FAIL(TS_ERR_UNWRAP, "TypeSOL: find matched no element");`);
155
+ return this.expr(access, hint);
156
+ }
157
+ // `?.`: an Option of the field, empty when nothing matched.
158
+ const t = this.tmp("oc");
159
+ const declAt = this.lines.length;
160
+ this.line(`/* ${t} */`);
161
+ let inner;
162
+ this.line(`if (${found} >= 0) {`);
163
+ this.block(() => {
164
+ const v = this.expr(access);
165
+ const typed = v.literal !== undefined ? this.literal(v.literal, U64, node) : v;
166
+ if (typed.type.kind === "option") {
167
+ inner = typed.type.inner;
168
+ this.line(`ts_memcpy(&${t}, &${typed.c}, sizeof(${t}));`);
169
+ return;
170
+ }
171
+ if (typed.type.kind !== "int" && typed.type.kind !== "bool" && typed.type.kind !== "pubkey" && typed.type.kind !== "enum")
172
+ this.fail(node, `?. gives an Option, so the field must be an integer, boolean, Pubkey or enum, not ${typeName(typed.type)}`);
173
+ inner = typed.type;
174
+ this.line(`${t}.some = 1;`);
175
+ this.line(inner.kind === "pubkey" ? `${t}.v = *(${typed.c});` : `${t}.v = ${typed.c};`);
176
+ });
177
+ this.line(`}`);
178
+ const scalar = inner;
179
+ this.model.options.set(optionKey(scalar), scalar);
180
+ this.lines[declAt] = `${" ".repeat(this.indent)}${optC(scalar)} ${t};\n${" ".repeat(this.indent)}ts_memzero(&${t}, sizeof(${t}));`;
181
+ return { c: t, type: { kind: "option", inner: scalar } };
182
+ }
102
183
  literal(value, type, node) {
103
184
  if (type.kind !== "int")
104
185
  this.fail(node, `expected ${typeName(type)}, got an integer literal`);
@@ -131,6 +212,9 @@ export class ExpressionEmitter extends StorageEmitter {
131
212
  this.fail(node, "! works on Option values and optional accounts (acct!.field); check other values with `x !== null`");
132
213
  return this.unwrap(v, node);
133
214
  }
215
+ const viaFind = this.foundAccess(node, hint);
216
+ if (viaFind)
217
+ return viaFind;
134
218
  if (ts.isPropertyAccessExpression(node) && node.questionDotToken)
135
219
  return this.optionalChain(node);
136
220
  const unbanged = this.withoutBang(node);
@@ -262,7 +346,7 @@ export class ExpressionEmitter extends StorageEmitter {
262
346
  this.fail(node, "this call does not produce a value");
263
347
  return v;
264
348
  }
265
- this.fail(node, `${ts.SyntaxKind[node.kind]} is not supported in TypeSOL expressions`);
349
+ this.fail(node, unsupportedSyntax(node.kind, "expression"));
266
350
  }
267
351
  property(node) {
268
352
  const field = node.name.text;
@@ -294,7 +378,16 @@ export class ExpressionEmitter extends StorageEmitter {
294
378
  if (l?.type.kind === "vecArg")
295
379
  return { c: `((uint64_t)${l.c}.len)`, type: U64 };
296
380
  }
297
- this.fail(node, "use byteLength(s) for strings; .length is available on arrays, Vecs and remainingAccounts()");
381
+ let what = "this value";
382
+ try {
383
+ what = this.checker.typeToString(this.checker.getTypeAtLocation(node.expression));
384
+ }
385
+ catch {
386
+ // a synthetic node: no type to name
387
+ }
388
+ if (/^string$|^FixedString/.test(what))
389
+ this.fail(node, "use byteLength(s) for strings; .length is available on arrays, Vecs and remainingAccounts()");
390
+ this.fail(node, `.length is available on arrays, Vecs, map / filter chains and remainingAccounts(), not on ${what}`);
298
391
  }
299
392
  if (this.isTxIx(node.expression)) {
300
393
  const ix = this.expr(node.expression);
@@ -47,6 +47,18 @@ export function emitProgram(analysis, opts = {}) {
47
47
  else if (maxAccounts.value > 32n)
48
48
  out.push(`#define TS_MAX_ACCOUNTS ${maxAccounts.value}`);
49
49
  }
50
+ // `const PANIC_ON_OVERFLOW = true`: arithmetic overflow and division by zero stop the program as a Rust panic does
51
+ // (`checked_mul(…).unwrap()`: ProgramFailedToComplete, no code) instead of failing with 5100 / 5101.
52
+ const panicFlag = model.constants.get("PANIC_ON_OVERFLOW");
53
+ if (panicFlag) {
54
+ if (typeof panicFlag.value !== "boolean")
55
+ reporter.error(analysis.sourceFile, "PANIC_ON_OVERFLOW must be true or false");
56
+ else if (panicFlag.value)
57
+ out.push(`#define TS_PANIC_ON_OVERFLOW 1`);
58
+ }
59
+ // An error with code 0 must not return 0 (success): see ts_fail.
60
+ if ([...model.errorEnums.values()].some((m) => [...m.values()].some((e) => e.code === 0)))
61
+ out.push(`#define TS_CUSTOM_ZERO 1`);
50
62
  out.push(`#include "typesol_rt.h"`, "");
51
63
  for (const inner of model.options.values())
52
64
  if (inner.kind !== "struct" && inner.kind !== "array")
@@ -65,6 +65,11 @@ export interface Ref {
65
65
  };
66
66
  };
67
67
  }
68
+ export interface FunctionChoice {
69
+ sel: string;
70
+ whenTrue: Closure | FunctionChoice;
71
+ whenFalse: Closure | FunctionChoice;
72
+ }
68
73
  export interface Local {
69
74
  c: string;
70
75
  /** A value, or a local FixedArray / FixedVec (`fixedArray<T, N>(…)`, `const ys = xs.map(…)`) held in place. */
@@ -84,6 +89,11 @@ export interface Local {
84
89
  decl?: ts.VariableDeclaration | ts.ParameterDeclaration;
85
90
  /** A local closure (`const f = (…) => …` reading the enclosing function's variables), expanded where it is called. */
86
91
  closure?: Closure;
92
+ /**
93
+ * `const g = c ? f : h` between functions: the condition, evaluated once where g is declared (`sel`, a C bool), and
94
+ * the two functions, each a closure or another choice. A call runs the chosen one's expansion only.
95
+ */
96
+ choice?: FunctionChoice;
87
97
  /** `const t = loadAccount<T>(acct)` / `loadAccountMut`: the account it views (a `TsAccount *`), to pass to helpers. */
88
98
  loaded?: {
89
99
  handle: string;
@@ -1,6 +1,6 @@
1
1
  import ts from "typescript";
2
2
  import { type FieldType } from "../model.js";
3
- import { type Value, type Closure, type Ref } from "./shared.js";
3
+ import { type Value, type Closure, type FunctionChoice, type Ref } from "./shared.js";
4
4
  import { CpiEmitter } from "./cpi.js";
5
5
  /**
6
6
  * Statements: variables, assignment, control flow and return.
@@ -18,6 +18,25 @@ export declare abstract class StatementEmitter extends CpiEmitter {
18
18
  * As in JS, the length is read again before every step, so a body that pushes or pops sees the new length.
19
19
  */
20
20
  protected forOf(stmt: ts.ForOfStatement): void;
21
+ /** The functions a list literal names (`[f, g]`: closures, helpers or choices), or undefined when it holds anything else. */
22
+ protected functionList(list: ts.ArrayLiteralExpression): (Closure | FunctionChoice)[] | undefined;
23
+ /**
24
+ * `for (const f of [g, h]) …`: unrolled, the body once per function with f bound to it, in order. `continue` goes to
25
+ * the next function, `break` past the last (the copies sit in a do { } while (0)).
26
+ */
27
+ protected forOfFunctions(stmt: ts.ForOfStatement, name: ts.Identifier): void;
28
+ /**
29
+ * `c ? f : h` where both sides name functions (or other choices): the condition is evaluated here, once, into a C bool,
30
+ * and a call later expands only the chosen function. Undefined when the expression is not such a choice.
31
+ */
32
+ protected functionChoice(init: ts.Expression, name: string): FunctionChoice | undefined;
33
+ /**
34
+ * Evaluate a function choice's conditions into C bools, as JS does: the outer one first, an inner one only when its
35
+ * side is taken (`a ? f : b ? g : h` reads b only when a is false). Its sides are known to name functions.
36
+ */
37
+ private bindChoice;
38
+ /** A call of a function chosen at run time: an if / else, each side expanding its function with the same arguments. */
39
+ protected callChoice(choice: FunctionChoice, args: readonly ts.Expression[], node: ts.Node): Value | undefined;
21
40
  /** The function an identifier names (a closure, a local function or a helper), as something to expand; else undefined. */
22
41
  protected functionNamed(id: ts.Identifier): Closure | undefined;
23
42
  /** `xs.map(…)` / `xs.filter(…)` (or a chain of them): a list built element by element, not stored anywhere yet. */
@@ -1,7 +1,7 @@
1
1
  import ts from "typescript";
2
2
  import { MAX_RETURN_DATA, calleeName, resolveScalarType, resolveValueType, structNameOf, typesolName } from "../analyze.js";
3
3
  import { INT_INFO, isScalar, optionKey, scalarSize, typeName } from "../model.js";
4
- import { U64, BOOL, cString, fixedVecC, optC, scalarC, scalarStorageC, valueC } from "./shared.js";
4
+ import { U64, BOOL, cString, fixedVecC, optC, scalarC, scalarStorageC, valueC, } from "./shared.js";
5
5
  import { CpiEmitter } from "./cpi.js";
6
6
  /**
7
7
  * Statements: variables, assignment, control flow and return.
@@ -255,6 +255,8 @@ export class StatementEmitter extends CpiEmitter {
255
255
  this.fail(stmt.initializer, "write for (const x of list): one const name, no type annotation");
256
256
  if (this.isRemaining(stmt.expression))
257
257
  this.fail(stmt.expression, "iterate remaining accounts with for (let i = 0n; i < rest.length; i++) and rest.get(i)");
258
+ if (ts.isArrayLiteralExpression(stmt.expression) && this.functionList(stmt.expression))
259
+ return this.forOfFunctions(stmt, d.name);
258
260
  // Synthetic `list.length` / `list.get(i)` nodes placed at the loop, so errors and checks point at the source.
259
261
  const f = ts.factory;
260
262
  const index = `__of${this.temp++}`;
@@ -281,6 +283,140 @@ export class StatementEmitter extends CpiEmitter {
281
283
  this.loops.pop();
282
284
  });
283
285
  }
286
+ /** The functions a list literal names (`[f, g]`: closures, helpers or choices), or undefined when it holds anything else. */
287
+ functionList(list) {
288
+ if (!list.elements.length)
289
+ return undefined;
290
+ const fns = [];
291
+ for (const el of list.elements) {
292
+ if (!ts.isIdentifier(el))
293
+ return undefined;
294
+ const l = this.lookup(el.text);
295
+ const f = l?.choice ?? this.functionNamed(el);
296
+ if (!f)
297
+ return undefined;
298
+ fns.push(f);
299
+ }
300
+ return fns;
301
+ }
302
+ /**
303
+ * `for (const f of [g, h]) …`: unrolled, the body once per function with f bound to it, in order. `continue` goes to
304
+ * the next function, `break` past the last (the copies sit in a do { } while (0)).
305
+ */
306
+ forOfFunctions(stmt, name) {
307
+ const fns = this.functionList(stmt.expression);
308
+ this.line(`do {`);
309
+ this.block(() => {
310
+ for (const f of fns) {
311
+ const next = this.tmp("ts_continue_");
312
+ this.line(`{`);
313
+ this.block(() => {
314
+ this.scopes.at(-1).set(name.text, "sel" in f ? { c: "", type: BOOL, mutable: false, choice: f } : { c: "", type: BOOL, mutable: false, closure: f });
315
+ this.loops.push(next);
316
+ try {
317
+ this.body(stmt.statement);
318
+ }
319
+ finally {
320
+ this.loops.pop();
321
+ }
322
+ });
323
+ this.line(`}`);
324
+ this.line(`${next}:;`);
325
+ }
326
+ });
327
+ this.line(`} while (0);`);
328
+ }
329
+ /**
330
+ * `c ? f : h` where both sides name functions (or other choices): the condition is evaluated here, once, into a C bool,
331
+ * and a call later expands only the chosen function. Undefined when the expression is not such a choice.
332
+ */
333
+ functionChoice(init, name) {
334
+ const strip = (x) => (ts.isParenthesizedExpression(x) ? strip(x.expression) : x);
335
+ const e = strip(init);
336
+ if (!ts.isConditionalExpression(e))
337
+ return undefined;
338
+ const inline = (x) => ts.isArrowFunction(strip(x)) || ts.isFunctionExpression(strip(x));
339
+ // What a side names, decided from the names alone (nothing is evaluated): a function, a choice, or neither.
340
+ const named = (x) => {
341
+ const y = strip(x);
342
+ if (ts.isIdentifier(y))
343
+ return !!(this.lookup(y.text)?.choice ?? this.functionNamed(y));
344
+ return ts.isConditionalExpression(y) && named(y.whenTrue) && named(y.whenFalse);
345
+ };
346
+ const fnSide = (x) => {
347
+ const y = strip(x);
348
+ return named(y) || (ts.isConditionalExpression(y) && (fnSide(y.whenTrue) || fnSide(y.whenFalse)));
349
+ };
350
+ if (!fnSide(e.whenTrue) && !fnSide(e.whenFalse)) {
351
+ if (inline(e.whenTrue) && inline(e.whenFalse))
352
+ this.fail(e, "declare each function with const first, then choose between them: const g = c ? f : h");
353
+ return undefined; // a choice between values: an ordinary conditional
354
+ }
355
+ if (inline(e.whenTrue) || inline(e.whenFalse))
356
+ this.fail(e, "declare each function with const first, then choose between them: const g = c ? f : h");
357
+ if (!named(e))
358
+ this.fail(e, "choose between functions on both sides: const g = c ? f : h");
359
+ return this.bindChoice(e, name);
360
+ }
361
+ /**
362
+ * Evaluate a function choice's conditions into C bools, as JS does: the outer one first, an inner one only when its
363
+ * side is taken (`a ? f : b ? g : h` reads b only when a is false). Its sides are known to name functions.
364
+ */
365
+ bindChoice(e, name, guard) {
366
+ const strip = (x) => (ts.isParenthesizedExpression(x) ? strip(x.expression) : x);
367
+ const sel = `l_${name}_sel_${this.temp++}`;
368
+ if (guard === undefined) {
369
+ const cond = this.expect(this.expr(e.condition, BOOL), BOOL, e.condition);
370
+ this.line(`bool ${sel} = ${cond.c};`);
371
+ }
372
+ else {
373
+ this.line(`bool ${sel} = false;`);
374
+ this.line(`if (${guard}) {`);
375
+ this.block(() => {
376
+ const cond = this.expect(this.expr(e.condition, BOOL), BOOL, e.condition);
377
+ this.line(`${sel} = ${cond.c};`);
378
+ });
379
+ this.line(`}`);
380
+ }
381
+ const within = (taken) => (guard === undefined ? taken : `(${guard}) && ${taken}`);
382
+ const side = (x, taken) => {
383
+ const y = strip(x);
384
+ if (ts.isIdentifier(y))
385
+ return (this.lookup(y.text)?.choice ?? this.functionNamed(y));
386
+ return this.bindChoice(y, name, within(taken));
387
+ };
388
+ return { sel, whenTrue: side(e.whenTrue, sel), whenFalse: side(e.whenFalse, `!${sel}`) };
389
+ }
390
+ /** A call of a function chosen at run time: an if / else, each side expanding its function with the same arguments. */
391
+ callChoice(choice, args, node) {
392
+ const t = this.tmp("chosen");
393
+ const declAt = this.lines.length;
394
+ this.line(`/* ${t} */`);
395
+ let type;
396
+ let anyValue = false;
397
+ const branch = (f) => {
398
+ const v = "sel" in f ? this.callChoice(f, args, node) : this.expandClosure(f, args, node);
399
+ if (!v)
400
+ return;
401
+ anyValue = true;
402
+ if (!type)
403
+ type = v.type;
404
+ const w = this.ownedString(this.expect(v, type, node));
405
+ this.line(w.type.kind === "pubkey" ? `${t} = *(${w.c});` : `${t} = ${w.c};`);
406
+ };
407
+ this.line(`if (${choice.sel}) {`);
408
+ this.block(() => branch(choice.whenTrue));
409
+ this.line(`} else {`);
410
+ this.block(() => branch(choice.whenFalse));
411
+ this.line(`}`);
412
+ if (!anyValue || !type)
413
+ return undefined;
414
+ const vt = type;
415
+ if (vt.kind === "account" || vt.kind === "remaining" || vt.kind === "structRef" || vt.kind === "vecArg")
416
+ this.fail(node, "functions chosen at run time return plain values (integers, booleans, Pubkeys, strings, options)");
417
+ this.lines[declAt] = this.lines[declAt].replace(`/* ${t} */`, `${vt.kind === "pubkey" ? "SolPubkey" : valueC(vt)} ${t};`);
418
+ return vt.kind === "pubkey" ? { c: `(&${t})`, type: vt } : { c: t, type: vt };
419
+ }
284
420
  /** The function an identifier names (a closure, a local function or a helper), as something to expand; else undefined. */
285
421
  functionNamed(id) {
286
422
  const l = this.lookup(id.text);
@@ -360,8 +496,31 @@ export class StatementEmitter extends CpiEmitter {
360
496
  if (st.kind === "map") {
361
497
  const ret = st.fn.body && !ts.isBlock(st.fn.body) ? st.fn.body : undefined;
362
498
  const bare = ret && ts.isParenthesizedExpression(ret) ? ret.expression : ret;
363
- if (bare && ts.isObjectLiteralExpression(bare))
364
- this.fail(st.fn, "a map to structs is stored, with the struct type: const ys: FixedVec<MyStruct, N> = xs.map((x) => ({ … }))");
499
+ if (bare && ts.isObjectLiteralExpression(bare)) {
500
+ // A map to structs inside a chain: each element built in a struct of its own, which the next stage reads.
501
+ const sname = st.fn.type ? structNameOf(st.fn.type, this.scope) : undefined;
502
+ const S = sname ? this.model.structs.get(sname) : undefined;
503
+ if (!S)
504
+ this.fail(st.fn, "name the struct the callback builds: xs.map((x): MyStruct => ({ … })) (or store the list: const ys: FixedVec<MyStruct, N> = xs.map(…))");
505
+ if (S.size === undefined || S.vec)
506
+ this.fail(st.fn, `${S.name} has variable-size fields and cannot be built in a chain`);
507
+ const closure = { node: st.fn, name: "map's callback", scopes: [...this.scopes], env: this.envNow(), imports: this.scope.imports };
508
+ const sc = this.tmp("lm_s");
509
+ this.line(`TSS_${S.name} ${sc}__v;`);
510
+ this.line(`ts_memzero(&${sc}__v, sizeof(${sc}__v));`);
511
+ this.expandClosure(closure, [element, idx].slice(0, st.fn.parameters.length), st.fn, {
512
+ lv: `${sc}__v`,
513
+ type: { kind: "struct", name: S.name },
514
+ writable: true,
515
+ });
516
+ this.line(`TSS_${S.name} *${sc} = &${sc}__v;`);
517
+ const id = `__ls${this.temp++}`;
518
+ this.scopes
519
+ .at(-1)
520
+ .set(id, { c: sc, type: { kind: "structRef", struct: S.name, writable: true }, mutable: false, paths: [`@${sc}`], owned: true });
521
+ element = place(f.createIdentifier(id));
522
+ continue;
523
+ }
365
524
  }
366
525
  const closure = { node: st.fn, name: `${st.kind}'s callback`, scopes: [...this.scopes], env: this.envNow(), imports: this.scope.imports };
367
526
  const v = this.expandClosure(closure, [element, idx].slice(0, st.fn.parameters.length), st.fn);
@@ -584,7 +743,7 @@ export class StatementEmitter extends CpiEmitter {
584
743
  params.set(name, { c: c2, type, mutable: true });
585
744
  });
586
745
  const declared = fn.type && fn.type.kind !== ts.SyntaxKind.VoidKeyword ? resolveValueType(fn.type, calleeScope) : undefined;
587
- if (fn.type && fn.type.kind !== ts.SyntaxKind.VoidKeyword && !declared)
746
+ if (fn.type && fn.type.kind !== ts.SyntaxKind.VoidKeyword && !declared && !into)
588
747
  this.fail(fn.type, "closures return integers, booleans, Pubkeys, strings, enums or Options");
589
748
  const frame = {
590
749
  label: this.tmp("ts_ret_"),
@@ -975,6 +1134,13 @@ export class StatementEmitter extends CpiEmitter {
975
1134
  // A function as a value: another name for one (`const h = g`), or the one a function returns (`adder(5n)`).
976
1135
  const made = ts.isCallExpression(init) ? this.madeFunction(init) : undefined;
977
1136
  const alias = ts.isIdentifier(init) ? this.functionNamed(init) : undefined;
1137
+ const choice = this.functionChoice(init, name);
1138
+ if (choice) {
1139
+ if (mutable)
1140
+ this.fail(d, "bind functions with const");
1141
+ this.scopes.at(-1).set(name, { c: "", type: BOOL, mutable: false, choice });
1142
+ continue;
1143
+ }
978
1144
  if (made || alias) {
979
1145
  if (mutable)
980
1146
  this.fail(d, "bind functions with const");
@@ -1029,14 +1195,18 @@ export class StatementEmitter extends CpiEmitter {
1029
1195
  this.scopes.at(-1).set(name, { c, type: t, mutable });
1030
1196
  continue;
1031
1197
  }
1032
- if (fn === "loadAccount" || fn === "loadAccountMut" || fn === "loadForeign") {
1198
+ if (fn === "loadAccount" || fn === "loadAccountMut" || fn === "loadForeign" || fn === "loadRaw" || fn === "loadRawMut") {
1033
1199
  if (mutable)
1034
1200
  this.fail(d, "bind loaded accounts with const");
1035
- const t = fn === "loadForeign" ? this.loadForeign(init) : this.loadAccount(init, fn === "loadAccountMut");
1201
+ const t = fn === "loadForeign"
1202
+ ? this.loadForeign(init)
1203
+ : fn === "loadRaw" || fn === "loadRawMut"
1204
+ ? this.loadRaw(init, fn === "loadRawMut")
1205
+ : this.loadAccount(init, fn === "loadAccountMut");
1036
1206
  this.line(`${valueC(t.type)}${c} = ${t.c};`);
1037
1207
  // The account it views, kept to pass the struct on to a helper that takes Account<T> / Mut<T>.
1038
1208
  let loaded;
1039
- if (fn !== "loadForeign" && t.type.kind === "structRef") {
1209
+ if ((fn === "loadAccount" || fn === "loadAccountMut") && t.type.kind === "structRef") {
1040
1210
  // The view is `((TSS_T *)(h->data + 8))` over a `TsAccount *h` that stays in scope with it.
1041
1211
  const h = /^\(\(TSS_\w+ \*\)\((\w+)->data \+ 8\)\)$/.exec(t.c)?.[1];
1042
1212
  if (h)
@@ -0,0 +1,5 @@
1
+ import ts from "typescript";
2
+ /** A sentence to add to a TypeScript diagnostic, or undefined when TypeScript's own message says enough. */
3
+ export declare function hintForTypeScript(d: ts.Diagnostic, message: string, libPath: string): string | undefined;
4
+ /** "ClassDeclaration is not supported …" in words a TypeScript developer recognizes. */
5
+ export declare function unsupportedSyntax(kind: ts.SyntaxKind, where: "top level" | "expression"): string;
@@ -0,0 +1,88 @@
1
+ // What to write instead, for the TypeScript errors and the syntax a newcomer to TypeSOL meets first. TypeScript's own
2
+ // suggestions (install @types/node, add the dom library, return a Promise) point the wrong way for a Solana program.
3
+ import { readFileSync } from "node:fs";
4
+ import ts from "typescript";
5
+ let libNames;
6
+ /** The functions and values lib/typesol.d.ts exports, so "Cannot find name 'log'" can say where log comes from. */
7
+ function typesolExports(libPath) {
8
+ if (!libNames) {
9
+ libNames = new Set();
10
+ try {
11
+ for (const m of readFileSync(libPath, "utf8").matchAll(/^export declare (?:function|const) (\w+)/gm))
12
+ libNames.add(m[1]);
13
+ }
14
+ catch {
15
+ // Without the library file there is nothing to suggest.
16
+ }
17
+ }
18
+ return libNames;
19
+ }
20
+ const MINMAX_HINT = 'Math works on numbers; use min(a, b) and max(a, b) from "typesol", which take bigints';
21
+ const BIGINT_HINT = "integers (u64, u32, i64 …) are bigint in TypeSOL: write 1n, not 1, and take u64, not number";
22
+ /** A sentence to add to a TypeScript diagnostic, or undefined when TypeScript's own message says enough. */
23
+ export function hintForTypeScript(d, message, libPath) {
24
+ // The whole source line, so a Math.max(…) is seen even when TypeScript marks only the assignment around it.
25
+ let line = "";
26
+ if (d.file && d.start !== undefined) {
27
+ const text = d.file.text;
28
+ const from = text.lastIndexOf("\n", d.start - 1) + 1;
29
+ const to = text.indexOf("\n", d.start);
30
+ line = text.slice(from, to < 0 ? undefined : to);
31
+ }
32
+ // Cannot find name 'x' (2304), with TypeScript's advice to install @types/node (2580, 2591), a test runner's types
33
+ // (2582, 2593) or the dom library (2584).
34
+ const name = /^Cannot find name '([^']+)'/.exec(message)?.[1];
35
+ if (name !== undefined) {
36
+ if (name === "console")
37
+ return 'a program writes logs with log("…") from "typesol"';
38
+ if (name === "Math")
39
+ return MINMAX_HINT;
40
+ if (typesolExports(libPath).has(name))
41
+ return `import { ${name} } from "typesol"`;
42
+ return undefined;
43
+ }
44
+ switch (d.code) {
45
+ case 2367: // This comparison appears to be unintentional because the types 'bigint' and 'number' have no overlap.
46
+ case 2365: // Operator '+=' cannot be applied to types 'bigint' and 'number'.
47
+ case 2322: // Type 'number' is not assignable to type 'bigint'.
48
+ case 2345: // Argument of type 'bigint' is not assignable to parameter of type 'number'.
49
+ if (/\bMath\.\w+\(/.test(line))
50
+ return MINMAX_HINT;
51
+ if (/\bbigint\b/.test(message) && (/\bnumber\b/.test(message) || /'-?\d+'/.test(message)))
52
+ return BIGINT_HINT;
53
+ return undefined;
54
+ case 7053: // Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'FixedArray<…>'.
55
+ case 7015: // Element implicitly has an 'any' type because index expression is not of type 'number'.
56
+ if (/FixedArray|Vec|FixedVec|FixedString/.test(message))
57
+ return "indexing with [ ] is not supported: use .get(i) and .set(i, value), with i a bigint (0n)";
58
+ return undefined;
59
+ case 1064: // The return type of an async function … must be the global Promise<T> type.
60
+ return "async is not supported: an instruction runs start to finish within one call; remove async";
61
+ case 2540: // Cannot assign to 'x' because it is a read-only property.
62
+ return "to change an account, take it as Mut<T> (Mut<Signer> for a signer whose lamports change)";
63
+ default:
64
+ return undefined;
65
+ }
66
+ }
67
+ /** Plain words for the syntax kinds the compiler refuses, and what to use instead. */
68
+ const SYNTAX = {
69
+ [ts.SyntaxKind.ClassDeclaration]: "classes are not supported: describe account data with an interface and logic with functions",
70
+ [ts.SyntaxKind.ElementAccessExpression]: "indexing with [ ] is not supported: use .get(i) and .set(i, value) (i is a bigint)",
71
+ [ts.SyntaxKind.TemplateExpression]: "template strings are not supported: log the parts one by one, or use an error enum member for a message",
72
+ [ts.SyntaxKind.SpreadElement]: "spread (...) is not supported: copy the fields one by one",
73
+ [ts.SyntaxKind.ArrayLiteralExpression]: "array literals are only allowed inline as seeds or CPI lists; declare local arrays with fixedArray<T, N>(fill)",
74
+ [ts.SyntaxKind.FunctionExpression]: "function expressions are not supported: declare a function at the top level",
75
+ [ts.SyntaxKind.AwaitExpression]: "await is not supported: an instruction runs start to finish within one call",
76
+ [ts.SyntaxKind.TypeOfExpression]: "typeof is not supported at run time: the types are known when the program compiles",
77
+ [ts.SyntaxKind.DeleteExpression]: "delete is not supported: account fields always exist; set the value instead",
78
+ [ts.SyntaxKind.ModuleDeclaration]: "namespaces are not supported: use separate files and import from them",
79
+ };
80
+ /** "ClassDeclaration is not supported …" in words a TypeScript developer recognizes. */
81
+ export function unsupportedSyntax(kind, where) {
82
+ const known = SYNTAX[kind];
83
+ if (known)
84
+ return known;
85
+ return where === "top level"
86
+ ? `this kind of statement (${ts.SyntaxKind[kind]}) is not supported at the top level of a TypeSOL file`
87
+ : `this syntax (${ts.SyntaxKind[kind]}) is not supported in TypeSOL expressions`;
88
+ }
@@ -1,3 +1,4 @@
1
+ import ts from "typescript";
1
2
  import { type EmitOptions } from "./emit/index.js";
2
3
  import { buildIdl } from "./idl.js";
3
4
  import { type Sbpf } from "./toolchain.js";
@@ -5,6 +6,8 @@ import type { ProgramModel } from "./model.js";
5
6
  export { CompileError, formatDiagnostic, type Diagnostic } from "./diagnostics.js";
6
7
  export type { ProgramModel } from "./model.js";
7
8
  export { SBPF_VERSIONS, type Sbpf } from "./toolchain.js";
9
+ /** The hint the CLI adds under a TypeScript error (what to write instead in a TypeSOL program), for the editor plugin. */
10
+ export declare function typescriptHint(d: ts.Diagnostic): string | undefined;
8
11
  export interface Generated {
9
12
  model: ProgramModel;
10
13
  c: string;
@@ -3,13 +3,18 @@ import { createRequire } from "node:module";
3
3
  import ts from "typescript";
4
4
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
5
  import path from "node:path";
6
- import { analyze } from "./analyze.js";
6
+ import { analyze, LIB_PATH } from "./analyze.js";
7
+ import { hintForTypeScript } from "./hints.js";
7
8
  import { emitProgram } from "./emit/index.js";
8
9
  import { buildIdl } from "./idl.js";
9
10
  import { buildSharedObject, toolchainVersion } from "./toolchain.js";
10
11
  import { RUNTIME_DIR } from "./toolchain.js";
11
12
  export { CompileError, formatDiagnostic } from "./diagnostics.js";
12
13
  export { SBPF_VERSIONS } from "./toolchain.js";
14
+ /** The hint the CLI adds under a TypeScript error (what to write instead in a TypeSOL program), for the editor plugin. */
15
+ export function typescriptHint(d) {
16
+ return hintForTypeScript(d, ts.flattenDiagnosticMessageText(d.messageText, "\n"), LIB_PATH);
17
+ }
13
18
  /** Typecheck, enforce the TypeSOL subset, and generate C. Throws CompileError with every diagnostic. */
14
19
  export function generate(entry, opts = {}) {
15
20
  const analysis = analyze(entry, opts.files);
@@ -6,7 +6,7 @@ mainnet as `MFv2hWf31Z9kbCa1snEPYctwafyhdvnV7FZnsebVacA` (version 0.1.12 in its
6
6
  456093551), not a rebuild.
7
7
 
8
8
  Marginfi is large: 124 instructions, 12 zero-copy accounts, 255 errors, and its amounts, prices and rates in I80F48
9
- fixed point. The port comes in parts, each checked before the next:
9
+ fixed point. All 124 are ported, in five parts, each checked against the binary before the next:
10
10
 
11
11
  | Part | What | Status |
12
12
  | --- | --- | --- |
@@ -14,7 +14,7 @@ fixed point. The port comes in parts, each checked before the next:
14
14
  | 2 | Group and bank administration, interest; accounts, deposits, repayments and fees | done |
15
15
  | 3 | Oracles, the risk engine, withdrawals and borrows | done |
16
16
  | 4 | Liquidation and bankruptcy | done |
17
- | 5 | The rest: flash loans, administration, orders, staked SOL, the integrations | in progress: flash loans, account, group and fee state administration, bank administration (but resizing), placing, closing and executing orders, rebalances, resizing, the monitor archive, staked-SOL administration and Scope configuration, Solend, Kamino, Drift and JupLend banks, every oracle setup's pricing and venue rebalance legs done (all 124 instructions) |
17
+ | 5 | The rest: flash loans, administration, orders, staked SOL, the integrations | done |
18
18
 
19
19
  The files are in [`showcase/mainnet/marginfi`](https://github.com/typesol-lang/typesol/tree/main/showcase/mainnet/marginfi):
20
20