@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
|
@@ -10,6 +10,34 @@ import { ExpressionEmitter } from "./expressions.js";
|
|
|
10
10
|
* Calls: built-in functions, Vec methods, helpers, remaining accounts, foreign account reads and return data.
|
|
11
11
|
*/
|
|
12
12
|
/** List methods taking a callback (or a value) that expand into a loop. */
|
|
13
|
+
/** solana_program's ProgramError variants with no data, in order from InvalidArgument (2) on. */
|
|
14
|
+
const PROGRAM_ERRORS = [
|
|
15
|
+
"InvalidArgument",
|
|
16
|
+
"InvalidInstructionData",
|
|
17
|
+
"InvalidAccountData",
|
|
18
|
+
"AccountDataTooSmall",
|
|
19
|
+
"InsufficientFunds",
|
|
20
|
+
"IncorrectProgramId",
|
|
21
|
+
"MissingRequiredSignature",
|
|
22
|
+
"AccountAlreadyInitialized",
|
|
23
|
+
"UninitializedAccount",
|
|
24
|
+
"NotEnoughAccountKeys",
|
|
25
|
+
"AccountBorrowFailed",
|
|
26
|
+
"MaxSeedLengthExceeded",
|
|
27
|
+
"InvalidSeeds",
|
|
28
|
+
"BorshIoError",
|
|
29
|
+
"AccountNotRentExempt",
|
|
30
|
+
"UnsupportedSysvar",
|
|
31
|
+
"IllegalOwner",
|
|
32
|
+
"MaxAccountsDataAllocationsExceeded",
|
|
33
|
+
"InvalidRealloc",
|
|
34
|
+
"MaxInstructionTraceLengthExceeded",
|
|
35
|
+
"BuiltinProgramsMustConsumeComputeUnits",
|
|
36
|
+
"InvalidAccountOwner",
|
|
37
|
+
"ArithmeticOverflow",
|
|
38
|
+
"Immutable",
|
|
39
|
+
"IncorrectAuthority",
|
|
40
|
+
];
|
|
13
41
|
const LIST_METHODS = new Set(["forEach", "some", "every", "find", "findIndex", "reduce", "includes", "indexOf"]);
|
|
14
42
|
export class CallEmitter extends ExpressionEmitter {
|
|
15
43
|
call(node, topLevel) {
|
|
@@ -36,12 +64,49 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
36
64
|
if (!this.namesError(args[1])) {
|
|
37
65
|
// A code computed at run time (a helper that returns its error as a value): u32, the program error it names.
|
|
38
66
|
const v = this.expr(args[1], U32);
|
|
67
|
+
if (v.type.kind === "string")
|
|
68
|
+
this.fail(args[1], "require's error is a string literal, a member of an error enum (CounterError.X) or a u32 code; a template string or string variable is not: give the message to an error enum member");
|
|
39
69
|
const code = v.literal !== undefined ? this.literal(v.literal, U32, args[1]) : this.expect(v, U32, args[1]);
|
|
40
70
|
this.line(`if (!${cond.c}) return ts_fail_code(${code.c}, ${cString(`Error: the code returned (${this.location(node)})`)});`);
|
|
41
71
|
return undefined;
|
|
42
72
|
}
|
|
73
|
+
// A built-in ProgramError: its u64 form (the index shifted into the high 32 bits), as solana_program returns it.
|
|
74
|
+
if (ts.isPropertyAccessExpression(args[1]) && this.exportName(args[1].expression) === "ProgramError") {
|
|
75
|
+
const idx = PROGRAM_ERRORS.indexOf(args[1].name.text);
|
|
76
|
+
if (idx < 0)
|
|
77
|
+
this.fail(args[1].name, `ProgramError has no ${args[1].name.text}`);
|
|
78
|
+
// `const PROGRAM_ERROR_LOG_PREFIX = "Program error: "`: the log line a native entrypoint writes for it.
|
|
79
|
+
const pre = this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value;
|
|
80
|
+
const text = typeof pre === "string" ? `${pre}${args[1].name.text}` : `Error: ${args[1].name.text} (${this.location(node)})`;
|
|
81
|
+
this.line(`if (!${cond.c}) TS_FAIL(((uint64_t)${idx + 2}) << 32, ${cString(text)});`);
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
43
84
|
const err = this.errorRef(args[1]);
|
|
44
|
-
|
|
85
|
+
// `const ERROR_LOG_PREFIX = "AMM error: "`: the program's errors log as its native entrypoint logs them.
|
|
86
|
+
const prefix = this.model.constants.get("ERROR_LOG_PREFIX")?.value;
|
|
87
|
+
const text = typeof prefix === "string" ? `${prefix}${err.msg}` : `Error ${err.code} ${err.name}: ${err.msg} (${this.location(node)})`;
|
|
88
|
+
this.line(`if (!${cond.c}) TS_FAIL(${err.code}, ${cString(text)});`);
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
case "panic": {
|
|
92
|
+
// String literals, or top-level string constants.
|
|
93
|
+
const text = (a) => {
|
|
94
|
+
if (ts.isStringLiteralLike(a))
|
|
95
|
+
return a.text;
|
|
96
|
+
const v = ts.isIdentifier(a) ? this.model.constants.get(a.text)?.value : undefined;
|
|
97
|
+
return typeof v === "string" ? v : undefined;
|
|
98
|
+
};
|
|
99
|
+
if (args.length > 2 || args.some((a) => text(a) === undefined))
|
|
100
|
+
this.fail(node, 'panic() takes an optional message and an optional "file:line:column" location: string literals or string constants');
|
|
101
|
+
const msg = args.length ? text(args[0]) : "explicit panic";
|
|
102
|
+
// The location the runtime reports ("SBF program Panicked in <file> at <line>:<column>"): the given one, as a
|
|
103
|
+
// ported program's panic reports it, else this source line.
|
|
104
|
+
const at = args.length > 1 ? text(args[1]) : this.location(node);
|
|
105
|
+
const m = /^(.*?):(\d+)(?::(\d+))?$/.exec(at);
|
|
106
|
+
const [file, line, col] = m ? [m[1], m[2], m[3] ?? "0"] : [at, "0", "0"];
|
|
107
|
+
this.line(`sol_log(${cString(msg)});`);
|
|
108
|
+
this.line(`sol_panic_(${cString(file)}, ${Buffer.byteLength(file)}, ${line}, ${col});`);
|
|
109
|
+
this.line(`__builtin_unreachable();`);
|
|
45
110
|
return undefined;
|
|
46
111
|
}
|
|
47
112
|
case "log": {
|
|
@@ -56,7 +121,14 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
56
121
|
this.line(`sol_log_((const char *)${t}.ptr, ${t}.len);`);
|
|
57
122
|
}
|
|
58
123
|
else {
|
|
59
|
-
|
|
124
|
+
let value = v.literal !== undefined ? this.expect(v, U64, args[0]) : v;
|
|
125
|
+
// An Option TypeScript has narrowed to its value (after `x === null` was ruled out): log the value.
|
|
126
|
+
if (value.type.kind === "option") {
|
|
127
|
+
const t = this.checker.getTypeAtLocation(args[0]);
|
|
128
|
+
if (t.isUnion() && t.types.some((m) => m.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)))
|
|
129
|
+
this.fail(args[0], "log() takes a value, not an Option that may be null: check `x !== null` first, or log `${x}` (null prints as null)");
|
|
130
|
+
value = this.unwrap(value, args[0]);
|
|
131
|
+
}
|
|
60
132
|
if (value.type.kind === "pubkey")
|
|
61
133
|
this.line(`sol_log_pubkey(${value.c});`);
|
|
62
134
|
else if (value.type.kind === "int") {
|
|
@@ -220,7 +292,9 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
220
292
|
const v = this.expr(args[0]);
|
|
221
293
|
const x = v.literal !== undefined ? this.literal(v.literal, U64, args[0]) : v;
|
|
222
294
|
if (x.type.kind !== "int" || INT_INFO[x.type.name].signed)
|
|
223
|
-
this.fail(args[0], "isqrt needs an unsigned integer (u8 …
|
|
295
|
+
this.fail(args[0], "isqrt needs an unsigned integer (u8 … u256)");
|
|
296
|
+
if (x.type.name === "u256")
|
|
297
|
+
return { c: `ts_isqrt_u256(${x.c})`, type: x.type };
|
|
224
298
|
const wide = INT_INFO[x.type.name].bytes === 16;
|
|
225
299
|
return { c: wide ? `ts_isqrt_u128(${x.c})` : `((${INT_INFO[x.type.name].c})ts_isqrt_u64((uint64_t)(${x.c})))`, type: x.type };
|
|
226
300
|
}
|
|
@@ -513,6 +587,34 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
513
587
|
this.line(`TS_TRY(ts_init_account(${h}, params->program_id, TS_DISC_${s.name}, sizeof(TSS_${s.name})));`);
|
|
514
588
|
return { c: `((TSS_${s.name} *)(${h}->data + 8))`, type: { kind: "structRef", struct: s.name, writable: true } };
|
|
515
589
|
}
|
|
590
|
+
case "createProgramAddress": {
|
|
591
|
+
// Pubkey::create_program_address(seeds, program): the bump is the last seed; null when the seeds give a point
|
|
592
|
+
// on the curve (Rust's Err(PubkeyError::InvalidSeeds)) or are too many / too long.
|
|
593
|
+
if (args.length !== 2)
|
|
594
|
+
this.fail(node, "createProgramAddress(seeds, program) takes the seeds (bump last) and the program's address");
|
|
595
|
+
const seeds = this.seeds(args[0], 0);
|
|
596
|
+
const program = this.expect(this.expr(args[1], PUBKEY), PUBKEY, args[1]);
|
|
597
|
+
const t = this.tmp("cpa");
|
|
598
|
+
this.model.options.set("pubkey", PUBKEY);
|
|
599
|
+
this.line(`${optC(PUBKEY)} ${t};`);
|
|
600
|
+
this.line(`${t}.some = ts_create_pda_address(${seeds.name}, ${seeds.count}, ${program.c}, &${t}.v) == SUCCESS;`);
|
|
601
|
+
return { c: t, type: { kind: "option", inner: PUBKEY } };
|
|
602
|
+
}
|
|
603
|
+
case "logBase64": {
|
|
604
|
+
// msg!("{prefix}{base64 of the struct's bytes}"): a fixed-layout struct's bytes are its bincode / Borsh form
|
|
605
|
+
// when it holds integers and Pubkeys only (Raydium's ray_log).
|
|
606
|
+
if (args.length !== 2 || !ts.isStringLiteralLike(args[0]))
|
|
607
|
+
this.fail(node, 'logBase64("prefix", value) takes a string literal and a struct value');
|
|
608
|
+
const place = this.structPlace(args[1]);
|
|
609
|
+
if (!place)
|
|
610
|
+
this.fail(args[1], "logBase64 logs a struct value (a local, a literal bound to a const, or account data)");
|
|
611
|
+
const sd = this.model.structs.get(place.struct);
|
|
612
|
+
if (sd.size === undefined || sd.vec || sd.fields.some((f) => !["int", "pubkey", "array"].includes(f.type.kind)))
|
|
613
|
+
this.fail(args[1], `${sd.name} must hold only integers, Pubkeys and fixed arrays of them for its bytes to be its serialized form`);
|
|
614
|
+
const prefix = args[0].text;
|
|
615
|
+
this.line(`ts_log_base64(${cString(prefix)}, ${Buffer.byteLength(prefix)}, (const uint8_t *)${place.ptr}, sizeof(TSS_${sd.name}));`);
|
|
616
|
+
return undefined;
|
|
617
|
+
}
|
|
516
618
|
case "findProgramAddress": {
|
|
517
619
|
// Pubkey::find_program_address(seeds, program).0: the canonical PDA of any program.
|
|
518
620
|
if (args.length !== 2)
|
|
@@ -578,6 +680,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
578
680
|
this.fail(node, "bigEndian(value) is a PDA seed: use it inside a seeds list");
|
|
579
681
|
case "loadAccount":
|
|
580
682
|
case "loadAccountMut":
|
|
683
|
+
case "loadRaw":
|
|
684
|
+
case "loadRawMut":
|
|
581
685
|
case "loadForeign":
|
|
582
686
|
this.fail(node, `bind ${builtin}<T>(...) to a const first: const p = ${builtin}<T>(account)`);
|
|
583
687
|
case "emit":
|
|
@@ -625,6 +729,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
625
729
|
this.fail(node, `${callee.text} returns a function: bind it (const f = ${callee.text}(…)) or call it right away (${callee.text}(…)(…))`);
|
|
626
730
|
if (local?.closure)
|
|
627
731
|
return this.expandClosure(local.closure, node.arguments, node);
|
|
732
|
+
if (local?.choice)
|
|
733
|
+
return this.callChoice(local.choice, node.arguments, node);
|
|
628
734
|
const name = calleeName(callee, this.model.helperDecls, this.checker) ?? callee.text;
|
|
629
735
|
if (!local && this.model.factories.has(name))
|
|
630
736
|
this.fail(node, `${callee.text} returns a function: bind it (const f = ${callee.text}(…)) or call it right away (${callee.text}(…)(…))`);
|
|
@@ -653,8 +759,29 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
653
759
|
if (ts.isIdentifier(callee.expression)) {
|
|
654
760
|
const l = this.lookup(callee.expression.text);
|
|
655
761
|
if (l?.type.kind === "vecArg") {
|
|
762
|
+
// Bytes (instruction data, a Vec<u8> argument): little-endian reads at a byte offset, bounds-checked (5104).
|
|
763
|
+
const le = {
|
|
764
|
+
readU8: ["uint8_t", 1, U8],
|
|
765
|
+
readU16: ["uint16_t", 2, { kind: "int", name: "u16" }],
|
|
766
|
+
readU32: ["uint32_t", 4, { kind: "int", name: "u32" }],
|
|
767
|
+
readU64: ["uint64_t", 8, U64],
|
|
768
|
+
readU128: ["__uint128_t", 16, { kind: "int", name: "u128" }],
|
|
769
|
+
readPubkey: ["SolPubkey", 32, PUBKEY],
|
|
770
|
+
};
|
|
771
|
+
if (le[method] && l.type.elem.kind === "int" && l.type.elem.name === "u8") {
|
|
772
|
+
if (args.length !== 1)
|
|
773
|
+
this.fail(node, `${method}(offset) takes the byte offset`);
|
|
774
|
+
const [c, size, type] = le[method];
|
|
775
|
+
const off = this.tmp("off");
|
|
776
|
+
this.line(`uint64_t ${off} = ${this.expect(this.expr(args[0], U64), U64, args[0]).c};`);
|
|
777
|
+
this.line(`if (${off} > (uint64_t)${l.c}.len || (uint64_t)${l.c}.len - ${off} < ${size}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: read past the end of the bytes");`);
|
|
778
|
+
const t = this.tmp("rd");
|
|
779
|
+
this.line(`${c} ${t};`);
|
|
780
|
+
this.line(`ts_memcpy(&${t}, ${l.c}.ptr + ${off}, ${size});`);
|
|
781
|
+
return type.kind === "pubkey" ? { c: `(&${t})`, type } : { c: t, type };
|
|
782
|
+
}
|
|
656
783
|
if (method !== "get" || args.length !== 1)
|
|
657
|
-
this.fail(node, "Vec arguments are read-only: use .get(i) and
|
|
784
|
+
this.fail(node, "Vec arguments are read-only: use .get(i), .length, and on bytes readU8/U16/U32/U64/U128/readPubkey(offset)");
|
|
658
785
|
const elem = l.type.elem;
|
|
659
786
|
if (elem.kind === "string") {
|
|
660
787
|
const idx = this.index(args[0], `(uint64_t)${l.c}.len`);
|
|
@@ -1317,6 +1444,47 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1317
1444
|
this.line(l.trim());
|
|
1318
1445
|
return { c: `((TSS_${s.name} *)(${h}->data + 8))`, type: { kind: "structRef", struct: s.name, writable: false } };
|
|
1319
1446
|
}
|
|
1447
|
+
/**
|
|
1448
|
+
* `loadRaw<T>(acct)` / `loadRawMut<T>(acct)`: a native program's account (no discriminator) as a fixed-layout struct
|
|
1449
|
+
* from byte 0, checked as a `#[repr(C)]` type's load_checked does: this program's (3007), large enough (3003).
|
|
1450
|
+
*/
|
|
1451
|
+
loadRaw(node, mut) {
|
|
1452
|
+
const fn = mut ? "loadRawMut" : "loadRaw";
|
|
1453
|
+
const targ = node.typeArguments?.[0];
|
|
1454
|
+
const s = targ && ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? this.model.structs.get(targ.typeName.text) : undefined;
|
|
1455
|
+
if (!s || s.size === undefined || s.vec)
|
|
1456
|
+
this.fail(node, `${fn} needs a fixed-size struct type: ${fn}<MyStruct>(account)`);
|
|
1457
|
+
if (s.layout === "borsh")
|
|
1458
|
+
this.fail(node, `${s.name} is @layout borsh: ${fn} reads fixed layouts only`);
|
|
1459
|
+
if (node.arguments.length !== 1)
|
|
1460
|
+
this.fail(node, `${fn}<T>(account) takes one remaining account or AccountInfo parameter`);
|
|
1461
|
+
let h = this.handle(node.arguments[0]);
|
|
1462
|
+
let param;
|
|
1463
|
+
if (!h) {
|
|
1464
|
+
const acct = this.accountParam(node.arguments[0], "the account");
|
|
1465
|
+
if (acct.kind.kind !== "info")
|
|
1466
|
+
this.fail(node.arguments[0], "pass a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter");
|
|
1467
|
+
if (mut && !isWritable(acct.kind))
|
|
1468
|
+
this.fail(node.arguments[0], `${acct.name} must be Mut<AccountInfo> to load it with loadRawMut`);
|
|
1469
|
+
if (!this.ix)
|
|
1470
|
+
this.fail(node, `load ${acct.name} in the instruction and pass the struct on`);
|
|
1471
|
+
h = `a_${acct.name}`;
|
|
1472
|
+
param = this.ix.accounts.indexOf(acct);
|
|
1473
|
+
}
|
|
1474
|
+
this.line(`if (!ts_key_eq(&${h}->owner, params->program_id)) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: account not owned by this program");`);
|
|
1475
|
+
this.line(`if (${h}->data_len < sizeof(TSS_${s.name})) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account data too small");`);
|
|
1476
|
+
if (mut) {
|
|
1477
|
+
this.line(`TS_TRY(ts_check_writable(${h}));`);
|
|
1478
|
+
const slot = this.claimSlots.get(node);
|
|
1479
|
+
if (slot)
|
|
1480
|
+
this.line(param === undefined
|
|
1481
|
+
? `TS_TRY(ts_claim_mut_rec(params, ${h}, &${slot}, params->ka_num));`
|
|
1482
|
+
: `TS_TRY(ts_claim_mut_at_rec(params, ${param}, &${slot}));`);
|
|
1483
|
+
else
|
|
1484
|
+
this.line(param === undefined ? `TS_TRY(ts_claim_mut(params, ${h}));` : `TS_TRY(ts_claim_mut_at(params, ${param}));`);
|
|
1485
|
+
}
|
|
1486
|
+
return { c: `((TSS_${s.name} *)(${h}->data))`, type: { kind: "structRef", struct: s.name, writable: mut } };
|
|
1487
|
+
}
|
|
1320
1488
|
/** `loadAccount<T>(acct)` / `loadAccountMut<T>(acct)`: checked view of a program account. */
|
|
1321
1489
|
loadAccount(node, mut) {
|
|
1322
1490
|
let targ = node.typeArguments?.[0];
|
|
@@ -1705,7 +1873,7 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1705
1873
|
return true;
|
|
1706
1874
|
if (!ts.isPropertyAccessExpression(node))
|
|
1707
1875
|
return false;
|
|
1708
|
-
if (this.exportName(node.expression) === "AnchorError")
|
|
1876
|
+
if (this.exportName(node.expression) === "AnchorError" || this.exportName(node.expression) === "ProgramError")
|
|
1709
1877
|
return true;
|
|
1710
1878
|
return ts.isIdentifier(node.expression) && this.model.errorEnums.has(node.expression.text);
|
|
1711
1879
|
}
|
|
@@ -17,6 +17,12 @@ export declare abstract class ExpressionEmitter extends StorageEmitter {
|
|
|
17
17
|
* when the account was left out / the option is empty. (A method call through `?.` is not supported.)
|
|
18
18
|
*/
|
|
19
19
|
protected optionalChain(node: ts.PropertyAccessExpression): Value;
|
|
20
|
+
/**
|
|
21
|
+
* `xs.find(cb)!.a.b` and `xs.find(cb)?.a` on a list of structs: the element is located with findIndex, then read as
|
|
22
|
+
* `xs.get(i).a.b`. With `!` an element that is not found fails the instruction (5108, as `x!` on an empty Option);
|
|
23
|
+
* with `?.` the field comes back as an Option, empty when nothing matched. Undefined for any other expression.
|
|
24
|
+
*/
|
|
25
|
+
protected foundAccess(node: ts.Expression, hint?: ValueType): Value | undefined;
|
|
20
26
|
protected literal(value: bigint, type: ValueType, node: ts.Node): Value;
|
|
21
27
|
protected expr(node: ts.Expression, hint?: ValueType): Value;
|
|
22
28
|
protected property(node: ts.PropertyAccessExpression): Value;
|
|
@@ -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,
|
|
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
|
-
|
|
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. */
|