@typesol/cli 0.39.0 → 0.41.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.
- package/CHANGELOG.md +74 -0
- package/README.md +29 -23
- package/dist/ai.d.ts +10 -0
- package/dist/ai.js +43 -0
- package/dist/cli.js +52 -4
- package/dist/compiler/analyze.js +13 -7
- package/dist/compiler/diagnostics.d.ts +2 -0
- package/dist/compiler/emit/base.d.ts +2 -1
- package/dist/compiler/emit/calls.d.ts +5 -0
- package/dist/compiler/emit/calls.js +173 -5
- package/dist/compiler/emit/expressions.d.ts +6 -0
- package/dist/compiler/emit/expressions.js +95 -2
- package/dist/compiler/emit/program.js +12 -0
- package/dist/compiler/emit/shared.d.ts +10 -0
- package/dist/compiler/emit/statements.d.ts +20 -1
- package/dist/compiler/emit/statements.js +177 -7
- package/dist/compiler/hints.d.ts +5 -0
- package/dist/compiler/hints.js +88 -0
- package/dist/compiler/index.d.ts +3 -0
- package/dist/compiler/index.js +6 -1
- package/dist/tools/mcp.d.ts +11 -0
- package/dist/tools/mcp.js +208 -0
- package/dist/workspace.js +8 -0
- package/docs/ai.md +52 -0
- package/docs/audit.md +16 -14
- package/docs/case-study-marginfi.md +2 -2
- package/docs/case-study-raydium-amm.md +80 -0
- package/docs/case-study-raydium-cp-swap.md +77 -41
- package/docs/language.md +27 -7
- package/docs/stability.md +56 -0
- package/docs/testing.md +6 -5
- package/docs/troubleshooting.md +6 -0
- package/lib/typesol.d.ts +73 -2
- package/llms-full.txt +1195 -0
- package/llms.txt +30 -0
- package/package.json +4 -2
- package/runtime/typesol_rt.h +47 -0
- package/ts-plugin/index.js +24 -1
|
@@ -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
|
-
|
|
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"
|
|
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
|
|
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
|
+
}
|
package/dist/compiler/index.d.ts
CHANGED
|
@@ -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;
|
package/dist/compiler/index.js
CHANGED
|
@@ -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);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
type Message = {
|
|
2
|
+
jsonrpc: "2.0";
|
|
3
|
+
id?: number | string | null;
|
|
4
|
+
method?: string;
|
|
5
|
+
params?: Record<string, unknown>;
|
|
6
|
+
};
|
|
7
|
+
/** One request's response (undefined for a notification). */
|
|
8
|
+
export declare function handle(msg: Message): object | undefined;
|
|
9
|
+
/** Serve on stdin / stdout until stdin closes. Logs go to stderr: stdout carries only protocol messages. */
|
|
10
|
+
export declare function serve(): Promise<void>;
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// `typesol mcp`: a Model Context Protocol server over stdio (newline-delimited JSON-RPC 2.0), so an AI coding agent
|
|
2
|
+
// (Claude Code, Cursor, …) can check a program, read its IDL and search the TypeSOL docs as tools. No dependencies.
|
|
3
|
+
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { AGENT_RULES } from "../ai.js";
|
|
8
|
+
import { CompileError, COMPILER_VERSION, generate } from "../compiler/index.js";
|
|
9
|
+
import { buildIdl } from "../compiler/idl.js";
|
|
10
|
+
const DOCS = fileURLToPath(new URL("../../docs", import.meta.url));
|
|
11
|
+
const README = fileURLToPath(new URL("../../README.md", import.meta.url));
|
|
12
|
+
/** Any address: the IDL's `address` field, when the caller gives none. */
|
|
13
|
+
const PLACEHOLDER_ADDRESS = "11111111111111111111111111111111";
|
|
14
|
+
/** The program to work on: a file path, or source text (written to a temporary file, so imports of "typesol" work). */
|
|
15
|
+
function withProgram(args, fn) {
|
|
16
|
+
if (typeof args.file === "string") {
|
|
17
|
+
const file = path.resolve(args.file);
|
|
18
|
+
if (!existsSync(file))
|
|
19
|
+
throw new Error(`no such file: ${file}`);
|
|
20
|
+
return fn(file);
|
|
21
|
+
}
|
|
22
|
+
if (typeof args.source !== "string")
|
|
23
|
+
throw new Error("give `file` (a path) or `source` (the program's text)");
|
|
24
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), "typesol-mcp-"));
|
|
25
|
+
const entry = path.join(dir, "program.ts");
|
|
26
|
+
writeFileSync(entry, args.source);
|
|
27
|
+
try {
|
|
28
|
+
return fn(entry, new Map([[entry, args.source]]));
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
rmSync(dir, { recursive: true, force: true });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** The docs as sections (a heading and what follows it), for the search tool. */
|
|
35
|
+
function sections() {
|
|
36
|
+
const out = [];
|
|
37
|
+
const files = [
|
|
38
|
+
README,
|
|
39
|
+
...(existsSync(DOCS)
|
|
40
|
+
? readdirSync(DOCS)
|
|
41
|
+
.filter((f) => f.endsWith(".md"))
|
|
42
|
+
.map((f) => path.join(DOCS, f))
|
|
43
|
+
: []),
|
|
44
|
+
];
|
|
45
|
+
for (const f of files) {
|
|
46
|
+
const name = path.basename(f);
|
|
47
|
+
let heading = name;
|
|
48
|
+
let text = [];
|
|
49
|
+
const flush = () => {
|
|
50
|
+
if (text.join("").trim())
|
|
51
|
+
out.push({ source: name, heading, text: text.join("\n").trim() });
|
|
52
|
+
text = [];
|
|
53
|
+
};
|
|
54
|
+
for (const line of readFileSync(f, "utf8").split("\n")) {
|
|
55
|
+
if (/^#{1,3} /.test(line)) {
|
|
56
|
+
flush();
|
|
57
|
+
heading = line.replace(/^#+ /, "");
|
|
58
|
+
}
|
|
59
|
+
else
|
|
60
|
+
text.push(line);
|
|
61
|
+
}
|
|
62
|
+
flush();
|
|
63
|
+
}
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
const TOOLS = [
|
|
67
|
+
{
|
|
68
|
+
name: "check",
|
|
69
|
+
description: "Type-check a TypeSOL program and list what the compiler refuses, each with its file, line, column, message and, for the usual mistakes, a hint saying what to write instead. Give `file` (a path) or `source` (the program's text).",
|
|
70
|
+
inputSchema: {
|
|
71
|
+
type: "object",
|
|
72
|
+
properties: {
|
|
73
|
+
file: { type: "string", description: "path to the program's entry .ts file" },
|
|
74
|
+
source: { type: "string", description: "the program's source text" },
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
run(args) {
|
|
78
|
+
return withProgram(args, (entry, files) => {
|
|
79
|
+
try {
|
|
80
|
+
const { model } = generate(entry, { files });
|
|
81
|
+
return { text: JSON.stringify({ ok: true, program: model.name, instructions: model.instructions.map((i) => i.name), diagnostics: [] }) };
|
|
82
|
+
}
|
|
83
|
+
catch (e) {
|
|
84
|
+
if (!(e instanceof CompileError))
|
|
85
|
+
throw e;
|
|
86
|
+
// Source given as text is reported as program.ts, not the temporary file it was checked in.
|
|
87
|
+
const diagnostics = files ? e.diagnostics.map((d) => ({ ...d, file: path.basename(d.file) })) : e.diagnostics;
|
|
88
|
+
return { text: JSON.stringify({ ok: false, diagnostics }) };
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
name: "idl",
|
|
95
|
+
description: "The Anchor-compatible IDL a TypeSOL program compiles to (instructions, accounts, types, errors, events). Give `file` or `source`.",
|
|
96
|
+
inputSchema: {
|
|
97
|
+
type: "object",
|
|
98
|
+
properties: { file: { type: "string" }, source: { type: "string" }, address: { type: "string", description: "the program address to record" } },
|
|
99
|
+
},
|
|
100
|
+
run(args) {
|
|
101
|
+
return withProgram(args, (entry, files) => {
|
|
102
|
+
try {
|
|
103
|
+
const address = typeof args.address === "string" ? args.address : PLACEHOLDER_ADDRESS;
|
|
104
|
+
return { text: JSON.stringify(buildIdl(generate(entry, { files }).model, address), null, 2) };
|
|
105
|
+
}
|
|
106
|
+
catch (e) {
|
|
107
|
+
if (!(e instanceof CompileError))
|
|
108
|
+
throw e;
|
|
109
|
+
return { text: JSON.stringify({ ok: false, diagnostics: e.diagnostics }), isError: true };
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
{
|
|
115
|
+
name: "docs",
|
|
116
|
+
description: "Search the TypeSOL documentation (the language reference, errors, testing, CLI, porting from Anchor, case studies). Returns the best-matching sections.",
|
|
117
|
+
inputSchema: { type: "object", properties: { query: { type: "string" }, limit: { type: "number" } }, required: ["query"] },
|
|
118
|
+
run(args) {
|
|
119
|
+
const words = String(args.query ?? "")
|
|
120
|
+
.toLowerCase()
|
|
121
|
+
.split(/\W+/)
|
|
122
|
+
.filter((w) => w.length > 1);
|
|
123
|
+
if (!words.length)
|
|
124
|
+
throw new Error("give a `query`");
|
|
125
|
+
const scored = sections()
|
|
126
|
+
.map((s) => {
|
|
127
|
+
const hay = `${s.heading}\n${s.text}`.toLowerCase();
|
|
128
|
+
const score = words.reduce((n, w) => n + (hay.split(w).length - 1) + (s.heading.toLowerCase().includes(w) ? 5 : 0), 0);
|
|
129
|
+
return { s, score };
|
|
130
|
+
})
|
|
131
|
+
.filter((x) => x.score > 0)
|
|
132
|
+
.sort((a, b) => b.score - a.score)
|
|
133
|
+
.slice(0, Math.max(1, Math.min(10, Number(args.limit ?? 4))));
|
|
134
|
+
if (!scored.length)
|
|
135
|
+
return { text: "No section matches; try other words, or the `rules` tool." };
|
|
136
|
+
return { text: scored.map(({ s }) => `# ${s.heading} (${s.source})\n\n${s.text.slice(0, 4000)}`).join("\n\n---\n\n") };
|
|
137
|
+
},
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
name: "rules",
|
|
141
|
+
description: "The rules a TypeSOL program follows that ordinary TypeScript habits break (bigint integers, imports, no throw/async/class, Mut<T> for changed accounts, …), and how to check and test.",
|
|
142
|
+
inputSchema: { type: "object", properties: {} },
|
|
143
|
+
run() {
|
|
144
|
+
return { text: AGENT_RULES };
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
];
|
|
148
|
+
/** One request's response (undefined for a notification). */
|
|
149
|
+
export function handle(msg) {
|
|
150
|
+
const reply = (result) => ({ jsonrpc: "2.0", id: msg.id ?? null, result });
|
|
151
|
+
const fail = (code, message) => ({ jsonrpc: "2.0", id: msg.id ?? null, error: { code, message } });
|
|
152
|
+
if (msg.id === undefined || msg.id === null)
|
|
153
|
+
return undefined; // notifications (notifications/initialized, …)
|
|
154
|
+
switch (msg.method) {
|
|
155
|
+
case "initialize":
|
|
156
|
+
return reply({
|
|
157
|
+
protocolVersion: typeof msg.params?.protocolVersion === "string" ? msg.params.protocolVersion : "2025-06-18",
|
|
158
|
+
capabilities: { tools: {} },
|
|
159
|
+
serverInfo: { name: "typesol", version: COMPILER_VERSION },
|
|
160
|
+
instructions: "TypeSOL compiles a TypeScript subset to Solana programs. Call `rules` first, `check` after every edit, `docs` for the reference.",
|
|
161
|
+
});
|
|
162
|
+
case "ping":
|
|
163
|
+
return reply({});
|
|
164
|
+
case "tools/list":
|
|
165
|
+
return reply({ tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) });
|
|
166
|
+
case "tools/call": {
|
|
167
|
+
const tool = TOOLS.find((t) => t.name === msg.params?.name);
|
|
168
|
+
if (!tool)
|
|
169
|
+
return fail(-32602, `unknown tool: ${String(msg.params?.name)}`);
|
|
170
|
+
try {
|
|
171
|
+
const out = tool.run(msg.params?.arguments ?? {});
|
|
172
|
+
return reply({ content: [{ type: "text", text: out.text }], isError: !!out.isError });
|
|
173
|
+
}
|
|
174
|
+
catch (e) {
|
|
175
|
+
return reply({ content: [{ type: "text", text: e instanceof Error ? e.message : String(e) }], isError: true });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
default:
|
|
179
|
+
return fail(-32601, `method not found: ${String(msg.method)}`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/** Serve on stdin / stdout until stdin closes. Logs go to stderr: stdout carries only protocol messages. */
|
|
183
|
+
export function serve() {
|
|
184
|
+
return new Promise((resolve) => {
|
|
185
|
+
let buffer = "";
|
|
186
|
+
process.stdin.setEncoding("utf8");
|
|
187
|
+
process.stdin.on("data", (chunk) => {
|
|
188
|
+
buffer += chunk;
|
|
189
|
+
let nl;
|
|
190
|
+
while ((nl = buffer.indexOf("\n")) >= 0) {
|
|
191
|
+
const line = buffer.slice(0, nl).trim();
|
|
192
|
+
buffer = buffer.slice(nl + 1);
|
|
193
|
+
if (!line)
|
|
194
|
+
continue;
|
|
195
|
+
let out;
|
|
196
|
+
try {
|
|
197
|
+
out = handle(JSON.parse(line));
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
out = { jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } };
|
|
201
|
+
}
|
|
202
|
+
if (out)
|
|
203
|
+
process.stdout.write(JSON.stringify(out) + "\n");
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
process.stdin.on("end", () => resolve());
|
|
207
|
+
});
|
|
208
|
+
}
|
package/dist/workspace.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* Program keypairs live in `<out>/deploy/<name>-keypair.json` (created on first build; keep them, never commit them).
|
|
12
12
|
* The address is recorded in typesol.json on first build, so a lost or swapped keypair is caught before deploying.
|
|
13
13
|
*/
|
|
14
|
+
import { agentsMd, CLAUDE_MD, cursorRule, MCP_JSON } from "./ai.js";
|
|
14
15
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
15
16
|
import path from "node:path";
|
|
16
17
|
import { writeClient } from "./tools/clientgen.js";
|
|
@@ -170,6 +171,13 @@ export function scaffold(dir, name, template = "counter") {
|
|
|
170
171
|
...t.devDependencies,
|
|
171
172
|
},
|
|
172
173
|
}, null, 2) + "\n",
|
|
174
|
+
// AI coding agents: the rules (AGENTS.md, and CLAUDE.md / Cursor's rules pointing at the same text) and the
|
|
175
|
+
// TypeSOL MCP server (check, IDL, docs as tools).
|
|
176
|
+
"AGENTS.md": agentsMd(name),
|
|
177
|
+
"CLAUDE.md": CLAUDE_MD,
|
|
178
|
+
".cursor/rules/typesol.mdc": cursorRule(),
|
|
179
|
+
".mcp.json": MCP_JSON,
|
|
180
|
+
".cursor/mcp.json": MCP_JSON,
|
|
173
181
|
// VS Code loads tsconfig plugins (typesol/ts-plugin) only with the workspace's TypeScript: offer to switch to it.
|
|
174
182
|
".vscode/settings.json": JSON.stringify({ "typescript.tsdk": "node_modules/typescript/lib", "typescript.enablePromptUseWorkspaceTsdk": true }, null, 2) + "\n",
|
|
175
183
|
// target/deploy/*-keypair.json are the programs' addresses: never commit them, but keep a backup.
|