@typesol/cli 0.38.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.
- package/CHANGELOG.md +373 -2
- package/README.md +43 -26
- package/SECURITY.md +1 -1
- package/dist/cli.js +37 -3
- package/dist/compiler/analyze.d.ts +6 -11
- package/dist/compiler/analyze.js +331 -34
- package/dist/compiler/emit/alias.js +3 -2
- package/dist/compiler/emit/base.d.ts +7 -1
- package/dist/compiler/emit/base.js +2 -0
- package/dist/compiler/emit/borsh.js +63 -2
- package/dist/compiler/emit/calls.d.ts +14 -1
- package/dist/compiler/emit/calls.js +311 -21
- package/dist/compiler/emit/cpi-core.js +17 -5
- package/dist/compiler/emit/cpi.js +81 -27
- package/dist/compiler/emit/create.d.ts +7 -0
- package/dist/compiler/emit/create.js +27 -0
- package/dist/compiler/emit/expressions.d.ts +6 -0
- package/dist/compiler/emit/expressions.js +102 -6
- package/dist/compiler/emit/function.d.ts +7 -0
- package/dist/compiler/emit/function.js +164 -29
- package/dist/compiler/emit/program.js +27 -2
- package/dist/compiler/emit/shared.d.ts +15 -5
- package/dist/compiler/emit/shared.js +5 -0
- package/dist/compiler/emit/statements.d.ts +28 -1
- package/dist/compiler/emit/statements.js +270 -13
- package/dist/compiler/emit/storage.d.ts +10 -1
- package/dist/compiler/emit/storage.js +50 -11
- package/dist/compiler/hints.d.ts +5 -0
- package/dist/compiler/hints.js +88 -0
- package/dist/compiler/idl.d.ts +1 -1
- package/dist/compiler/idl.js +42 -11
- package/dist/compiler/index.d.ts +3 -0
- package/dist/compiler/index.js +6 -1
- package/dist/compiler/model.d.ts +47 -10
- package/dist/compiler/model.js +14 -4
- package/dist/testing.js +8 -0
- package/dist/tools/clientgen.js +10 -1
- package/dist/tools/portgen.d.ts +6 -0
- package/dist/tools/portgen.js +68 -17
- package/docs/architecture.md +5 -4
- package/docs/audit.md +31 -19
- package/docs/case-study-escrow.md +5 -5
- package/docs/case-study-jito-mev.md +9 -5
- package/docs/case-study-marginfi.md +797 -0
- package/docs/case-study-multisig.md +3 -3
- package/docs/case-study-raydium-amm.md +80 -0
- package/docs/case-study-raydium-clmm.md +44 -33
- package/docs/case-study-raydium-cp-swap.md +3 -3
- package/docs/cli.md +5 -5
- package/docs/client.md +1 -1
- package/docs/errors.md +13 -5
- package/docs/language.md +65 -32
- package/docs/migrate-from-anchor.md +4 -1
- package/docs/runtime.md +1 -1
- package/docs/security-model.md +2 -1
- package/docs/testing.md +34 -1
- package/docs/troubleshooting.md +6 -0
- package/lib/typesol.d.ts +118 -10
- package/package.json +9 -7
- package/runtime/typesol_rt.h +158 -17
- package/ts-plugin/index.js +24 -1
|
@@ -18,8 +18,10 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
18
18
|
}
|
|
19
19
|
else {
|
|
20
20
|
const program = this.accountParam(a[0], "invoke's program");
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
// Address<A, "base58"> (Anchor's `address = ID` on an UncheckedAccount): the key is that program's; the runtime
|
|
22
|
+
// refuses a CPI into an account that is not executable.
|
|
23
|
+
if (program.kind.kind !== "program" && program.kind.kind !== "system" && program.kind.kind !== "tokenProgram" && !program.constraints.address)
|
|
24
|
+
this.fail(a[0], 'invoke\'s program must be a Program<"address">, UncheckedProgram, Address<A, "address">, SystemProgram, token program or remaining account');
|
|
23
25
|
programKey = `&a_${program.name}->key`;
|
|
24
26
|
}
|
|
25
27
|
const hasSeeds = a.length === 4;
|
|
@@ -33,7 +35,7 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
33
35
|
for (const el of a[1].elements) {
|
|
34
36
|
if (ts.isSpreadElement(el)) {
|
|
35
37
|
if (!this.ix)
|
|
36
|
-
this.fail(el, "
|
|
38
|
+
this.fail(el, "pass the remaining accounts to a CPI from the instruction; a helper reads them one at a time with .get(i)");
|
|
37
39
|
const inner = el.expression;
|
|
38
40
|
const fnName = ts.isCallExpression(inner) ? this.exportName(inner.expression) : undefined;
|
|
39
41
|
const wrapped = ts.isCallExpression(inner) && (fnName === "readonly" || fnName === "writable") && inner.arguments.length === 1;
|
|
@@ -59,13 +61,17 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
59
61
|
parts.push({ kind: "meta", c: metas[metas.length - 1] });
|
|
60
62
|
continue;
|
|
61
63
|
}
|
|
62
|
-
|
|
64
|
+
// An optional account as it is (no `!`): left out of the list when it was not passed (Rust's
|
|
65
|
+
// `if let Some(a) = &self.a { accounts.push(…) }`).
|
|
66
|
+
const maybe = this.accountAt(el.arguments[0]);
|
|
67
|
+
const skipped = !!maybe?.optional && !isS && ts.isIdentifier(el.arguments[0]);
|
|
68
|
+
const acct = skipped ? maybe : this.accountParam(el.arguments[0], `${fn}()'s argument`);
|
|
63
69
|
if (isW && !isWritable(acct.kind))
|
|
64
70
|
this.fail(el, `"${acct.name}" is not writable here; declare it Mut<...>`);
|
|
65
71
|
if (isS && acct.kind.kind !== "signer" && !hasSeeds)
|
|
66
72
|
this.fail(el, `"${acct.name}" did not sign; pass signerSeeds to sign for a PDA, or declare it Signer`);
|
|
67
73
|
metas.push(`{&a_${acct.name}->key, ${isW}, ${isS}}`);
|
|
68
|
-
parts.push({ kind: "meta", c: metas[metas.length - 1] });
|
|
74
|
+
parts.push({ kind: "meta", c: metas[metas.length - 1], when: skipped ? `a_${acct.name} != NULL` : undefined });
|
|
69
75
|
}
|
|
70
76
|
// The CPI's account list is built in a buffer with room for one entry per instruction account.
|
|
71
77
|
if (metas.length > accountLimit(this.model))
|
|
@@ -137,9 +143,9 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
137
143
|
const seeds = hasSeeds && !multi ? this.signingSeeds(a[3]) : { name: "NULL", count: 0 };
|
|
138
144
|
const metasName = this.tmp("metas");
|
|
139
145
|
let count = String(metas.length);
|
|
140
|
-
if (parts.some((p) => p.kind === "spread")) {
|
|
146
|
+
if (parts.some((p) => p.kind === "spread" || p.when)) {
|
|
141
147
|
// Room for every account of the instruction (ts_invoke's scratch holds TS_MAX_ACCOUNTS records).
|
|
142
|
-
const n = this.ix.accounts.length;
|
|
148
|
+
const n = this.ix ? this.ix.accounts.length : 0;
|
|
143
149
|
const cnt = this.tmp("nmetas");
|
|
144
150
|
this.line(`TS_METAS_ROOM(${metasName});`);
|
|
145
151
|
this.line(`uint64_t ${cnt} = 0;`);
|
|
@@ -148,7 +154,7 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
148
154
|
this.line(`if (${total} > TS_MAX_ACCOUNTS) TS_FAIL(TS_ERR_TOO_MANY_ACCOUNTS, "TypeSOL: the CPI lists more than ${accountLimit(this.model)} accounts");`);
|
|
149
155
|
for (const p of parts) {
|
|
150
156
|
if (p.kind === "meta") {
|
|
151
|
-
this.line(`${metasName}[${cnt}++] = (SolAccountMeta)${p.c};`);
|
|
157
|
+
this.line(`${p.when ? `if (${p.when}) ` : ""}${metasName}[${cnt}++] = (SolAccountMeta)${p.c};`);
|
|
152
158
|
continue;
|
|
153
159
|
}
|
|
154
160
|
const i = this.tmp("ri");
|
|
@@ -287,8 +293,40 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
287
293
|
for (const f of s.fields)
|
|
288
294
|
if (!given.has(f.name))
|
|
289
295
|
this.fail(obj, `missing field "${f.name}" of ${s.name}`);
|
|
290
|
-
|
|
291
|
-
|
|
296
|
+
// A field's bytes, staged when its value is evaluated: a nested struct written as a literal is Borsh field by field
|
|
297
|
+
// (its Options one byte when empty), as Anchor serializes it.
|
|
298
|
+
const stage = (f, e) => {
|
|
299
|
+
if (f.type.kind === "struct" && ts.isObjectLiteralExpression(e)) {
|
|
300
|
+
const sd = this.model.structs.get(f.type.name);
|
|
301
|
+
// Its Options and enums go out as Borsh, so the IDL describes them so; account data or arguments need it fixed.
|
|
302
|
+
if (sd.fields.some((x) => x.type.kind === "option" || x.type.kind === "dataEnum")) {
|
|
303
|
+
if (this.fixedLayoutStructs().has(sd.name))
|
|
304
|
+
this.fail(e, `${sd.name} has Option or enum fields and is account data or an argument (fixed layout there, Borsh in events); declare a separate struct for the event`);
|
|
305
|
+
sd.wire = "borsh";
|
|
306
|
+
}
|
|
307
|
+
const fields = new Map();
|
|
308
|
+
for (const p of e.properties) {
|
|
309
|
+
if (ts.isPropertyAssignment(p) && ts.isIdentifier(p.name))
|
|
310
|
+
fields.set(p.name.text, p.initializer);
|
|
311
|
+
else if (ts.isShorthandPropertyAssignment(p))
|
|
312
|
+
fields.set(p.name.text, p.name);
|
|
313
|
+
else
|
|
314
|
+
this.fail(p, "use plain `field: value` entries");
|
|
315
|
+
}
|
|
316
|
+
for (const k of fields.keys())
|
|
317
|
+
if (!sd.fields.some((x) => x.name === k))
|
|
318
|
+
this.fail(e, `${sd.name} has no field "${k}"`);
|
|
319
|
+
for (const x of sd.fields)
|
|
320
|
+
if (!fields.has(x.name))
|
|
321
|
+
this.fail(e, `missing field "${x.name}" of ${sd.name}`);
|
|
322
|
+
const parts = new Map();
|
|
323
|
+
for (const [k, v] of fields)
|
|
324
|
+
parts.set(k, stage(sd.fields.find((x) => x.name === k), v));
|
|
325
|
+
return (put) => {
|
|
326
|
+
for (const name of sd.declared ?? sd.fields.map((x) => x.name))
|
|
327
|
+
parts.get(name)(put);
|
|
328
|
+
};
|
|
329
|
+
}
|
|
292
330
|
if (f.type.kind === "vec" && f.type.cap !== undefined) {
|
|
293
331
|
// A FixedVec keeps its fixed layout, as in account data: u32 length, then room for N elements.
|
|
294
332
|
const ft = f.type;
|
|
@@ -297,11 +335,21 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
297
335
|
this.line(`ts_memzero(&${t}, sizeof(${t}));`);
|
|
298
336
|
this.writeAggregate({ lv: t, type: ft, writable: true }, e);
|
|
299
337
|
const n = this.fieldBytes(ft);
|
|
300
|
-
|
|
301
|
-
continue;
|
|
338
|
+
return (put) => put(`&${t}`, String(n), n);
|
|
302
339
|
}
|
|
303
340
|
if (f.type.kind === "vec") {
|
|
304
|
-
// A Vec is Borsh: u32 length, then the elements, read from a Vec argument or account data when emitted.
|
|
341
|
+
// A Vec is Borsh: u32 length, then the elements, read from a Vec argument or account data when emitted. An
|
|
342
|
+
// Option<Vec<T>> puts a tag byte first: null, an Option<Vec<T>> argument (None or Some) or a list (Some).
|
|
343
|
+
const optional = f.type.optional === true;
|
|
344
|
+
const tag = (put, some) => {
|
|
345
|
+
const t = this.tmp("vt");
|
|
346
|
+
this.line(`uint8_t ${t} = ${some};`);
|
|
347
|
+
put(`&${t}`, "1", 1);
|
|
348
|
+
return t;
|
|
349
|
+
};
|
|
350
|
+
if (optional && e.kind === ts.SyntaxKind.NullKeyword) {
|
|
351
|
+
return (put) => tag(put, "0");
|
|
352
|
+
}
|
|
305
353
|
const l = ts.isIdentifier(e) ? this.lookup(e.text) : undefined;
|
|
306
354
|
const r = l?.type.kind === "vecArg" ? undefined : this.ref(e);
|
|
307
355
|
const elemSize = this.fieldBytes(f.type.elem);
|
|
@@ -309,25 +357,28 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
309
357
|
if (!sameType(l.type.elem, f.type.elem))
|
|
310
358
|
this.fail(e, `expected a ${typeName(f.type)}`);
|
|
311
359
|
const c = l.c;
|
|
312
|
-
|
|
360
|
+
const maybe = l.type.optional === true;
|
|
361
|
+
return (put) => {
|
|
362
|
+
const some = optional ? tag(put, maybe ? `${c}.ptr != NULL` : "1") : undefined;
|
|
313
363
|
const n = this.tmp("vl");
|
|
314
364
|
this.line(`uint32_t ${n} = (uint32_t)${c}.len;`);
|
|
315
|
-
put(`&${n}`, "4");
|
|
365
|
+
put(`&${n}`, some && maybe ? `(${some} ? 4 : 0)` : "4");
|
|
316
366
|
put(`(const uint8_t *)${c}.ptr`, `(uint64_t)${n} * ${elemSize}`);
|
|
317
|
-
}
|
|
367
|
+
};
|
|
318
368
|
}
|
|
319
369
|
else if (r?.vec && r.type.kind === "vec" && sameType(r.type.elem, f.type.elem)) {
|
|
320
370
|
const info = r.vec;
|
|
321
|
-
|
|
371
|
+
return (put) => {
|
|
372
|
+
if (optional)
|
|
373
|
+
tag(put, "1");
|
|
322
374
|
const n = this.tmp("vl");
|
|
323
375
|
this.line(`uint32_t ${n} = (uint32_t)${vecCount(info)};`);
|
|
324
376
|
put(`&${n}`, "4");
|
|
325
377
|
put(`(const uint8_t *)${info.items}`, `(uint64_t)${n} * ${elemSize}`);
|
|
326
|
-
}
|
|
378
|
+
};
|
|
327
379
|
}
|
|
328
380
|
else
|
|
329
|
-
this.fail(e, `expected a ${typeName(f.type)}: a Vec argument or a list in account data`);
|
|
330
|
-
continue;
|
|
381
|
+
this.fail(e, `expected a ${typeName(f.type)}: ${optional ? "null, " : ""}a Vec argument or a list in account data`);
|
|
331
382
|
}
|
|
332
383
|
if (f.type.kind === "option" && f.type.inner.kind === "struct")
|
|
333
384
|
this.fail(obj, "Option<struct> fields are not supported in events yet");
|
|
@@ -340,7 +391,7 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
340
391
|
this.fail(e, `expected a ${enumName}`);
|
|
341
392
|
this.line(`TSE_${enumName} ${t};`);
|
|
342
393
|
this.line(`ts_memcpy(&${t}, &${src.lv}, sizeof(${t}));`);
|
|
343
|
-
|
|
394
|
+
return (put) => this.serializeDataEnumLv(t, enumName, put);
|
|
344
395
|
}
|
|
345
396
|
else if (vt) {
|
|
346
397
|
const v = this.ownedString(this.expect(this.expr(e, vt), vt, e));
|
|
@@ -349,7 +400,7 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
349
400
|
else
|
|
350
401
|
this.line(`${valueC(vt)} ${t} = ${v.c};`);
|
|
351
402
|
const held = { c: vt.kind === "pubkey" ? `(&${t})` : t, type: vt };
|
|
352
|
-
|
|
403
|
+
return (put) => this.serialize(held, e, put);
|
|
353
404
|
}
|
|
354
405
|
else if (f.type.kind === "fstring") {
|
|
355
406
|
// Event FixedString keeps its fixed layout: u32 length + capacity bytes.
|
|
@@ -357,7 +408,7 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
357
408
|
const v = this.expect(this.expr(e, STRING), STRING, e);
|
|
358
409
|
this.line(`TS_FStr${cap} ${t};`);
|
|
359
410
|
this.line(`TS_TRY(ts_fstr_set((uint8_t *)&${t}, ${cap}, ${v.c}));`);
|
|
360
|
-
|
|
411
|
+
return (put) => put(`&${t}`, String(4 + cap), 4 + cap);
|
|
361
412
|
}
|
|
362
413
|
else {
|
|
363
414
|
const src = this.ref(e);
|
|
@@ -366,12 +417,15 @@ export class CpiEmitter extends MetaplexEmitter {
|
|
|
366
417
|
const n = this.fieldBytes(f.type);
|
|
367
418
|
this.line(`uint8_t ${t}[${n}];`);
|
|
368
419
|
this.line(`ts_memcpy(${t}, &${src.lv}, ${n});`);
|
|
369
|
-
|
|
420
|
+
return (put) => put(t, String(n), n);
|
|
370
421
|
}
|
|
371
|
-
}
|
|
422
|
+
};
|
|
423
|
+
for (const [name, e] of given)
|
|
424
|
+
staged.set(name, stage(s.fields.find((x) => x.name === name), e));
|
|
372
425
|
this.sendEvent(s, obj, cpi, (put) => {
|
|
373
|
-
|
|
374
|
-
|
|
426
|
+
// Borsh order: as declared (the fixed layout stores growable Vecs last).
|
|
427
|
+
for (const name of s.declared ?? s.fields.map((f) => f.name))
|
|
428
|
+
staged.get(name)(put);
|
|
375
429
|
});
|
|
376
430
|
return undefined;
|
|
377
431
|
}
|
|
@@ -36,6 +36,13 @@ export declare abstract class CreateEmitter extends CpiCoreEmitter {
|
|
|
36
36
|
protected systemTransfer(node: ts.CallExpression): undefined;
|
|
37
37
|
/** systemProgram.createAccount(payer, account, lamports, space, owner, signerSeeds?) */
|
|
38
38
|
protected createAccount(node: ts.CallExpression, system: AccountParam): undefined;
|
|
39
|
+
/**
|
|
40
|
+
* systemProgram.createPda(payer, account, space, owner, seeds): Anchor's `init` with `seeds`, `space` and `owner = …`
|
|
41
|
+
* on an `UncheckedAccount` — the PDA of this program for `seeds` (2006 otherwise), created owned by `owner`, or over
|
|
42
|
+
* an address someone already funded topped up, allocated and assigned. Returns the bump. Leading the body, it runs
|
|
43
|
+
* before the other constraints, as Anchor's `init` does.
|
|
44
|
+
*/
|
|
45
|
+
protected createPda(node: ts.CallExpression): Value;
|
|
39
46
|
/** systemProgram.allocate(account, space, signerSeeds?) / systemProgram.assign(account, owner, signerSeeds?). */
|
|
40
47
|
protected allocateOrAssign(node: ts.CallExpression, system: AccountParam, method: "allocate" | "assign"): undefined;
|
|
41
48
|
}
|
|
@@ -565,6 +565,33 @@ export class CreateEmitter extends CpiCoreEmitter {
|
|
|
565
565
|
], buf, len, seeds);
|
|
566
566
|
return undefined;
|
|
567
567
|
}
|
|
568
|
+
/**
|
|
569
|
+
* systemProgram.createPda(payer, account, space, owner, seeds): Anchor's `init` with `seeds`, `space` and `owner = …`
|
|
570
|
+
* on an `UncheckedAccount` — the PDA of this program for `seeds` (2006 otherwise), created owned by `owner`, or over
|
|
571
|
+
* an address someone already funded topped up, allocated and assigned. Returns the bump. Leading the body, it runs
|
|
572
|
+
* before the other constraints, as Anchor's `init` does.
|
|
573
|
+
*/
|
|
574
|
+
createPda(node) {
|
|
575
|
+
const a = node.arguments;
|
|
576
|
+
if (a.length !== 5)
|
|
577
|
+
this.fail(node, "createPda(payer, account, space, owner, seeds)");
|
|
578
|
+
const payer = this.accountParam(a[0], "the payer");
|
|
579
|
+
if (payer.kind.kind !== "signer" || !payer.kind.mut)
|
|
580
|
+
this.fail(a[0], "the payer must be a Mut<Signer>");
|
|
581
|
+
const acct = this.accountParam(a[1], "the new account");
|
|
582
|
+
if (acct.kind.kind !== "info" || !isWritable(acct.kind))
|
|
583
|
+
this.fail(a[1], "the new account must be a Mut<AccountInfo>");
|
|
584
|
+
const space = this.tmp("space");
|
|
585
|
+
this.line(`uint64_t ${space} = ${this.expect(this.expr(a[2], U64), U64, a[2]).c};`);
|
|
586
|
+
const owner = this.tmp("owner");
|
|
587
|
+
this.line(`SolPubkey ${owner} = *(${this.expect(this.expr(a[3], PUBKEY), PUBKEY, a[3]).c});`);
|
|
588
|
+
const seeds = this.seeds(a[4], 1);
|
|
589
|
+
this.recordPda(acct, seeds.idl);
|
|
590
|
+
const b = this.tmp("bump");
|
|
591
|
+
this.line(`uint8_t ${b};`);
|
|
592
|
+
this.line(`TS_TRY(ts_create_pda_owned(params, a_${payer.name}, a_${acct.name}, ${seeds.name}, ${seeds.count}, &${owner}, ${space}, &${b}));`);
|
|
593
|
+
return { c: b, type: U8 };
|
|
594
|
+
}
|
|
568
595
|
/** systemProgram.allocate(account, space, signerSeeds?) / systemProgram.assign(account, owner, signerSeeds?). */
|
|
569
596
|
allocateOrAssign(node, system, method) {
|
|
570
597
|
const a = node.arguments;
|
|
@@ -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);
|
|
@@ -179,7 +263,7 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
179
263
|
if (l.type.kind === "vec")
|
|
180
264
|
this.fail(node, `"${node.text}" is a list; use .get(i) and .length`);
|
|
181
265
|
if (l.type.kind === "remaining")
|
|
182
|
-
return { c:
|
|
266
|
+
return { c: l.c, type: l.type };
|
|
183
267
|
return l.type.kind === "pubkey" && !l.ptr ? { c: `(&${l.c})`, type: l.type } : { c: l.c, type: l.type };
|
|
184
268
|
}
|
|
185
269
|
const k = this.model.constants.get(node.text);
|
|
@@ -262,13 +346,13 @@ 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;
|
|
269
353
|
if (field === "length") {
|
|
270
354
|
if (this.isRemaining(node.expression))
|
|
271
|
-
return { c: `((uint64_t)(params->ka_num - ${this.
|
|
355
|
+
return { c: `((uint64_t)(params->ka_num - ${this.remainingBase(node.expression)}))`, type: U64 };
|
|
272
356
|
const sysvar = this.instructionsParam(node.expression);
|
|
273
357
|
if (sysvar) {
|
|
274
358
|
this.assertUsable(sysvar, node.expression);
|
|
@@ -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);
|
|
@@ -808,9 +901,12 @@ export class ExpressionEmitter extends StorageEmitter {
|
|
|
808
901
|
return { c: `(a_${optionalAccount.name} ${neg ? "!=" : "=="} NULL)`, type: BOOL };
|
|
809
902
|
}
|
|
810
903
|
const v = this.expr(other);
|
|
811
|
-
if (v.type.kind !== "option")
|
|
812
|
-
this.fail(other, "only Option values can be compared with null");
|
|
813
904
|
const neg = op === K.ExclamationEqualsEqualsToken || op === K.ExclamationEqualsToken;
|
|
905
|
+
// An Option<Vec<T>> argument: None leaves its view's pointer NULL (a Some, empty or not, points into the data).
|
|
906
|
+
if (v.type.kind === "vecArg" && v.type.optional)
|
|
907
|
+
return { c: `((${v.c}).ptr ${neg ? "!=" : "=="} NULL)`, type: BOOL };
|
|
908
|
+
if (v.type.kind !== "option" && v.type.kind !== "optionArg")
|
|
909
|
+
this.fail(other, "only Option values can be compared with null");
|
|
814
910
|
return { c: neg ? `((${v.c}).some != 0)` : `((${v.c}).some == 0)`, type: BOOL };
|
|
815
911
|
}
|
|
816
912
|
const isCmp = op === K.LessThanToken || op === K.LessThanEqualsToken || op === K.GreaterThanToken || op === K.GreaterThanEqualsToken;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
1
2
|
import { type AccountParam, type Instruction } from "../model.js";
|
|
2
3
|
import { StatementEmitter } from "./statements.js";
|
|
3
4
|
/**
|
|
@@ -7,6 +8,12 @@ import { StatementEmitter } from "./statements.js";
|
|
|
7
8
|
export declare class FunctionEmitter extends StatementEmitter {
|
|
8
9
|
emitHelper(): string;
|
|
9
10
|
emitInstruction(): string;
|
|
11
|
+
/**
|
|
12
|
+
* How many statements at the start of `body` create this instruction's Init / InitIfNeeded accounts
|
|
13
|
+
* (`acct.create(…)`, `acct.createIfNeeded(…)`, `systemProgram.createPda(…)`, alone, as a const's value or assigned). 0 when none do, or when one reads a
|
|
14
|
+
* bump the constraint checks find (`acct.pdaBump` of a Seeds account), which must run first.
|
|
15
|
+
*/
|
|
16
|
+
protected leadingCreates(ix: Instruction, body: readonly ts.Statement[]): number;
|
|
10
17
|
/** CloseTo<…> accounts are closed when the instruction succeeds, at every return. */
|
|
11
18
|
protected epilogue(): string[];
|
|
12
19
|
/**
|