@typesol/cli 0.41.0 → 0.43.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 +319 -0
- package/README.md +11 -7
- package/dist/compiler/analyze.js +484 -13
- package/dist/compiler/diagnostics.d.ts +1 -0
- package/dist/compiler/diagnostics.js +13 -0
- package/dist/compiler/emit/alias.d.ts +44 -0
- package/dist/compiler/emit/alias.js +135 -4
- package/dist/compiler/emit/base.d.ts +65 -7
- package/dist/compiler/emit/base.js +91 -7
- package/dist/compiler/emit/borsh.d.ts +7 -0
- package/dist/compiler/emit/borsh.js +86 -1
- package/dist/compiler/emit/calls.d.ts +169 -2
- package/dist/compiler/emit/calls.js +1170 -81
- package/dist/compiler/emit/cpi-core.d.ts +28 -5
- package/dist/compiler/emit/cpi-core.js +238 -12
- package/dist/compiler/emit/cpi.js +16 -16
- package/dist/compiler/emit/create.d.ts +3 -3
- package/dist/compiler/emit/create.js +33 -25
- package/dist/compiler/emit/expressions.js +89 -9
- package/dist/compiler/emit/function.js +2 -2
- package/dist/compiler/emit/outline.d.ts +24 -0
- package/dist/compiler/emit/outline.js +100 -0
- package/dist/compiler/emit/program.js +37 -3
- package/dist/compiler/emit/rbtree.d.ts +7 -0
- package/dist/compiler/emit/rbtree.js +142 -0
- package/dist/compiler/emit/shared.d.ts +43 -1
- package/dist/compiler/emit/shared.js +18 -2
- package/dist/compiler/emit/statements.d.ts +58 -1
- package/dist/compiler/emit/statements.js +549 -22
- package/dist/compiler/emit/storage.d.ts +48 -1
- package/dist/compiler/emit/storage.js +220 -63
- package/dist/compiler/emit/token.d.ts +11 -8
- package/dist/compiler/emit/token.js +233 -104
- package/dist/compiler/emit/views.d.ts +60 -0
- package/dist/compiler/emit/views.js +523 -0
- package/dist/compiler/hints.js +6 -0
- package/dist/compiler/idl.js +2 -1
- package/dist/compiler/model.d.ts +84 -4
- package/dist/compiler/model.js +19 -0
- package/dist/compiler/toolchain.d.ts +15 -0
- package/dist/compiler/toolchain.js +146 -11
- package/dist/testing-stake.d.ts +216 -0
- package/dist/testing-stake.js +526 -0
- package/dist/testing.d.ts +1 -0
- package/dist/testing.js +1 -0
- package/docs/architecture.md +9 -2
- package/docs/case-study-phoenix.md +226 -0
- package/docs/case-study-spl-stake-pool.md +122 -0
- package/docs/errors.md +1 -1
- package/docs/language.md +244 -20
- package/docs/migrate-from-anchor.md +1 -0
- package/docs/runtime.md +1 -1
- package/docs/security-model.md +4 -0
- package/docs/stability.md +33 -1
- package/docs/test-your-program.md +47 -0
- package/docs/testing.md +19 -0
- package/docs/troubleshooting.md +5 -2
- package/lib/typesol.d.ts +462 -44
- package/llms-full.txt +338 -26
- package/llms.txt +1 -1
- package/package.json +2 -2
- package/runtime/typesol_rt.h +476 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
|
-
import { calleeName, discriminator, resolveScalarType, resolveValueType, snakeCase, structNameOf } from "../analyze.js";
|
|
3
|
-
import { borshIdentical } from "./borsh.js";
|
|
2
|
+
import { calleeName, discriminator, resolveScalarType, resolveValueType, snakeCase, structNameOf, typesolName } from "../analyze.js";
|
|
3
|
+
import { borshIdentical, borshNativeStructUnsupported } from "./borsh.js";
|
|
4
4
|
import { ANCHOR_ERRORS } from "../anchor-errors.js";
|
|
5
5
|
import { decodeAddress } from "../../keys.js";
|
|
6
6
|
import { INT_INFO, INT_NAMES, isScalar, isWritable, sameType, scalarSize, typeName, } from "../model.js";
|
|
@@ -39,6 +39,8 @@ const PROGRAM_ERRORS = [
|
|
|
39
39
|
"IncorrectAuthority",
|
|
40
40
|
];
|
|
41
41
|
const LIST_METHODS = new Set(["forEach", "some", "every", "find", "findIndex", "reduce", "includes", "indexOf"]);
|
|
42
|
+
/** The byte builders of a FixedVec<u8, N> (byteListMethod). */
|
|
43
|
+
const BYTE_METHODS = new Set(["pushLE", "pushKey", "pushBorsh", "setLE", "truncate"]);
|
|
42
44
|
export class CallEmitter extends ExpressionEmitter {
|
|
43
45
|
call(node, topLevel) {
|
|
44
46
|
const callee = node.expression;
|
|
@@ -67,25 +69,28 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
67
69
|
if (v.type.kind === "string")
|
|
68
70
|
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");
|
|
69
71
|
const code = v.literal !== undefined ? this.literal(v.literal, U32, args[1]) : this.expect(v, U32, args[1]);
|
|
70
|
-
|
|
72
|
+
if (this.quietErrors())
|
|
73
|
+
this.line(`if (!${cond.c}) return ts_fail_code_quiet(${code.c});`);
|
|
74
|
+
else
|
|
75
|
+
this.line(`if (!${cond.c}) return ts_fail_code(${code.c}, ${cString(`Error: the code returned (${this.location(node)})`)});`);
|
|
71
76
|
return undefined;
|
|
72
77
|
}
|
|
73
78
|
// A built-in ProgramError: its u64 form (the index shifted into the high 32 bits), as solana_program returns it.
|
|
74
79
|
if (ts.isPropertyAccessExpression(args[1]) && this.exportName(args[1].expression) === "ProgramError") {
|
|
75
|
-
|
|
76
|
-
if (idx < 0)
|
|
80
|
+
if (!PROGRAM_ERRORS.includes(args[1].name.text))
|
|
77
81
|
this.fail(args[1].name, `ProgramError has no ${args[1].name.text}`);
|
|
78
|
-
|
|
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
|
+
this.line(`if (!${cond.c}) ${this.programErrorFail(args[1].name.text, node)};`);
|
|
82
83
|
return undefined;
|
|
83
84
|
}
|
|
84
85
|
const err = this.errorRef(args[1]);
|
|
85
86
|
// `const ERROR_LOG_PREFIX = "AMM error: "`: the program's errors log as its native entrypoint logs them.
|
|
87
|
+
// `const ERROR_LOG_PREFIX = null`: nothing logged, only the code returned.
|
|
86
88
|
const prefix = this.model.constants.get("ERROR_LOG_PREFIX")?.value;
|
|
87
89
|
const text = typeof prefix === "string" ? `${prefix}${err.msg}` : `Error ${err.code} ${err.name}: ${err.msg} (${this.location(node)})`;
|
|
88
|
-
|
|
90
|
+
if (prefix === null)
|
|
91
|
+
this.line(`if (!${cond.c}) return ts_fail_quiet(${err.code});`);
|
|
92
|
+
else
|
|
93
|
+
this.line(`if (!${cond.c}) TS_FAIL(${err.code}, ${cString(text)});`);
|
|
89
94
|
return undefined;
|
|
90
95
|
}
|
|
91
96
|
case "panic": {
|
|
@@ -96,17 +101,57 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
96
101
|
const v = ts.isIdentifier(a) ? this.model.constants.get(a.text)?.value : undefined;
|
|
97
102
|
return typeof v === "string" ? v : undefined;
|
|
98
103
|
};
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
this
|
|
108
|
-
|
|
109
|
-
this.
|
|
104
|
+
// A null message: nothing logged, only the runtime's line (a native program whose panic handler logs nothing).
|
|
105
|
+
const silent = args.length > 0 && args[0].kind === ts.SyntaxKind.NullKeyword;
|
|
106
|
+
if (args.length > 2 || args.some((a, i) => !(i === 0 && silent) && text(a) === undefined))
|
|
107
|
+
this.fail(node, 'panic() takes an optional message (or null to log nothing) and an optional "file:line:column" location: string literals or string constants');
|
|
108
|
+
const msg = silent ? undefined : args.length ? text(args[0]) : "explicit panic";
|
|
109
|
+
if (silent && this.panicStyle())
|
|
110
|
+
this.fail(args[0], 'under PANIC_STYLE "solana-1.14" a panic logs its message, as solana_program 1.14\'s panic handler always does: pass the message');
|
|
111
|
+
// The location the runtime reports ("SBF program Panicked in <file> at <line>:<column>"), or the panic line
|
|
112
|
+
// logs: the given one, as a ported program's panic reports it, else this source line (with its column under
|
|
113
|
+
// PANIC_STYLE, as Rust always gives one).
|
|
114
|
+
const at = args.length > 1 ? text(args[1]) : this.panicStyle() ? this.locationWithColumn(node) : this.location(node);
|
|
115
|
+
for (const l of this.panicC(msg, at))
|
|
116
|
+
this.line(l);
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
case "panicsAt": {
|
|
120
|
+
// The checked arithmetic of `expression` panics as Rust's does at `location`, with Rust's messages.
|
|
121
|
+
const first = args[0];
|
|
122
|
+
const loc = first && (ts.isStringLiteralLike(first) ? first.text : ts.isIdentifier(first) ? this.model.constants.get(first.text)?.value : undefined);
|
|
123
|
+
if (args.length !== 2 || typeof loc !== "string" || !/^.+:\d+:\d+$/.test(loc))
|
|
124
|
+
this.fail(node, 'panicsAt(location, expression) takes a "file:line:column" string literal (or string constant) and the expression whose arithmetic panics there');
|
|
125
|
+
// Prettier writes an assignment argument in parentheses: `panicsAt(loc, (total += fee))`.
|
|
126
|
+
let inner = args[1];
|
|
127
|
+
while (ts.isParenthesizedExpression(inner))
|
|
128
|
+
inner = inner.expression;
|
|
129
|
+
const outer = this.panicAt;
|
|
130
|
+
this.panicAt = loc;
|
|
131
|
+
try {
|
|
132
|
+
// A statement: an assignment, a compound assignment (`total += fee`) or ++ / --.
|
|
133
|
+
const assigns = (ts.isBinaryExpression(inner) &&
|
|
134
|
+
inner.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
|
|
135
|
+
inner.operatorToken.kind <= ts.SyntaxKind.LastAssignment) ||
|
|
136
|
+
((ts.isPrefixUnaryExpression(inner) || ts.isPostfixUnaryExpression(inner)) &&
|
|
137
|
+
(inner.operator === ts.SyntaxKind.PlusPlusToken || inner.operator === ts.SyntaxKind.MinusMinusToken));
|
|
138
|
+
if (assigns) {
|
|
139
|
+
if (!ts.isExpressionStatement(node.parent))
|
|
140
|
+
this.fail(inner, "an assignment inside panicsAt is a statement of its own: panicsAt(location, total += fee);");
|
|
141
|
+
this.expressionStatement(inner, topLevel);
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
return this.expr(inner);
|
|
145
|
+
}
|
|
146
|
+
finally {
|
|
147
|
+
this.panicAt = outer;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
case "abort": {
|
|
151
|
+
// Rust's abort on SBF: the runtime's `abort` syscall ("SBF program panicked", no location, nothing logged).
|
|
152
|
+
if (args.length)
|
|
153
|
+
this.fail(node, "abort() takes no arguments; log the original's message first with log(…) where it writes one");
|
|
154
|
+
this.line(`abort();`);
|
|
110
155
|
return undefined;
|
|
111
156
|
}
|
|
112
157
|
case "log": {
|
|
@@ -175,6 +220,7 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
175
220
|
if (!isWritable(d.kind))
|
|
176
221
|
this.fail(args[1], "the destination must be writable (Mut<...>)");
|
|
177
222
|
this.line(`TS_TRY(ts_close(a_${a.name}, a_${d.name}));`);
|
|
223
|
+
this.forgetOwners();
|
|
178
224
|
return undefined;
|
|
179
225
|
}
|
|
180
226
|
case "minimumBalance": {
|
|
@@ -201,6 +247,15 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
201
247
|
this.line(`TS_TRY(ts_epoch_schedule(${{ slotsPerEpoch: 0, epochWarmup: 2, firstNormalEpoch: 3, firstNormalSlot: 4 }[builtin]}, &${t}));`);
|
|
202
248
|
return builtin === "epochWarmup" ? { c: `(${t} != 0)`, type: BOOL } : { c: t, type: U64 };
|
|
203
249
|
}
|
|
250
|
+
case "epochRewards": {
|
|
251
|
+
if (args.length !== 0)
|
|
252
|
+
this.fail(node, "epochRewards() takes no arguments");
|
|
253
|
+
// Rust's EpochRewards::get() (sol_get_epoch_rewards_sysvar): a copy of the sysvar, read where it is called.
|
|
254
|
+
const t = this.tmp("erw");
|
|
255
|
+
this.line(`TsEpochRewards ${t};`);
|
|
256
|
+
this.line(`TS_TRY(ts_epoch_rewards(&${t}));`);
|
|
257
|
+
return { c: t, type: { kind: "epochRewards" } };
|
|
258
|
+
}
|
|
204
259
|
case "currentSlot":
|
|
205
260
|
case "currentEpoch":
|
|
206
261
|
case "epochStartTimestamp":
|
|
@@ -615,6 +670,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
615
670
|
this.line(`ts_log_base64(${cString(prefix)}, ${Buffer.byteLength(prefix)}, (const uint8_t *)${place.ptr}, sizeof(TSS_${sd.name}));`);
|
|
616
671
|
return undefined;
|
|
617
672
|
}
|
|
673
|
+
case "findProgramAddressWithBump":
|
|
674
|
+
this.fail(node, "bind both results where it is called: const [address, bump] = findProgramAddressWithBump(seeds, program)");
|
|
618
675
|
case "findProgramAddress": {
|
|
619
676
|
// Pubkey::find_program_address(seeds, program).0: the canonical PDA of any program.
|
|
620
677
|
if (args.length !== 2)
|
|
@@ -667,15 +724,59 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
667
724
|
case "resizeAccount": {
|
|
668
725
|
if (args.length !== 2)
|
|
669
726
|
this.fail(node, "resizeAccount(account, newSize) takes the account and its new size");
|
|
727
|
+
this.assertNoViewAfter(this.viewAccountKey(args[0]), node, "resizeAccount()");
|
|
728
|
+
// A remaining account (or a helper's RemainingAccount): its size when the instruction started is the one the
|
|
729
|
+
// entrypoint recorded in the record's padding, as solana_program 1.14's entrypoint records it for realloc.
|
|
730
|
+
const h = this.handle(args[0]);
|
|
731
|
+
if (h) {
|
|
732
|
+
if (!this.nativeAccountWrites())
|
|
733
|
+
this.line(`TS_TRY(ts_check_writable(${h}));`);
|
|
734
|
+
const size = this.expect(this.expr(args[1], U64), U64, args[1]);
|
|
735
|
+
this.line(`TS_TRY(ts_resize_raw(${h}, ${size.c}, ts_entry_len(${h})));`);
|
|
736
|
+
return undefined;
|
|
737
|
+
}
|
|
670
738
|
if (!this.ix)
|
|
671
|
-
this.fail(node, "resizeAccount() is only available in instructions");
|
|
739
|
+
this.fail(node, "resizeAccount() is only available in instructions (or on a remaining account a helper was given)");
|
|
672
740
|
const acct = this.accountParam(args[0], "resizeAccount's account");
|
|
673
|
-
if (acct.kind.kind !== "info" || !isWritable(acct.kind))
|
|
674
|
-
this.fail(args[0], "resizeAccount needs a Mut<AccountInfo> parameter");
|
|
741
|
+
if (acct.kind.kind !== "info" || (!isWritable(acct.kind) && !this.nativeAccountWrites()))
|
|
742
|
+
this.fail(args[0], "resizeAccount needs a Mut<AccountInfo> parameter or a remaining account");
|
|
675
743
|
const size = this.expect(this.expr(args[1], U64), U64, args[1]);
|
|
676
744
|
this.line(`TS_TRY(ts_resize_raw(a_${acct.name}, ${size.c}, entry_${acct.name}));`);
|
|
677
745
|
return undefined;
|
|
678
746
|
}
|
|
747
|
+
case "closeRaw": {
|
|
748
|
+
// Phoenix's Tombstone, in its order: receiver.lamports = receiver.lamports + account.lamports;
|
|
749
|
+
// account.lamports = 0; account.assign(&system_program::id()); account.realloc(0, false). The data is not
|
|
750
|
+
// zeroed (realloc's zero_init is false): the runtime drops it with the length, and then accepts the new owner.
|
|
751
|
+
if (args.length !== 2)
|
|
752
|
+
this.fail(node, "closeRaw(account, receiver) takes the account to close and the account that gets its lamports");
|
|
753
|
+
this.assertNoViewAfter(this.viewAccountKey(args[0]), node, "closeRaw()");
|
|
754
|
+
const a = this.inPlaceAccount(args[0], "closeRaw's account", true);
|
|
755
|
+
const r = this.inPlaceAccount(args[1], "closeRaw's receiver", false);
|
|
756
|
+
// Closing an account into itself would burn its lamports (the runtime then refuses the instruction).
|
|
757
|
+
if (!this.nativeAccountWrites())
|
|
758
|
+
this.line(`if (${a} == ${r}) TS_FAIL(TS_ERR_DUPLICATE_MUT, "TypeSOL: closeRaw's receiver is the account itself");`);
|
|
759
|
+
const sum = this.tmp("sum");
|
|
760
|
+
this.line(`uint64_t ${sum};`);
|
|
761
|
+
this.line(`if (ts_add_overflow_u64(${r}->lamports, ${a}->lamports, &${sum})) TS_FAIL(TS_ERR_OVERFLOW, "TypeSOL: arithmetic overflow");`);
|
|
762
|
+
this.line(`${r}->lamports = ${sum};`);
|
|
763
|
+
this.line(`${a}->lamports = 0;`);
|
|
764
|
+
this.line(`ts_memcpy(&${a}->owner, &TS_SYSTEM_PROGRAM_ID, 32);`);
|
|
765
|
+
this.forgetOwners();
|
|
766
|
+
this.line(`${a}->data_len = 0;`);
|
|
767
|
+
return undefined;
|
|
768
|
+
}
|
|
769
|
+
case "assignOwner": {
|
|
770
|
+
// AccountInfo::assign: the owner field written in place; the runtime accepts it at the end of the instruction
|
|
771
|
+
// (or at a CPI) only for an account of this program that is writable and whose data is empty or zeroed.
|
|
772
|
+
if (args.length !== 2)
|
|
773
|
+
this.fail(node, "assignOwner(account, owner) takes the account and its new owner's address");
|
|
774
|
+
const a = this.inPlaceAccount(args[0], "assignOwner's account", true);
|
|
775
|
+
const owner = this.expect(this.expr(args[1], PUBKEY), PUBKEY, args[1]);
|
|
776
|
+
this.line(`ts_memcpy(&${a}->owner, ${owner.c}, 32);`);
|
|
777
|
+
this.forgetOwners();
|
|
778
|
+
return undefined;
|
|
779
|
+
}
|
|
679
780
|
case "bigEndian":
|
|
680
781
|
this.fail(node, "bigEndian(value) is a PDA seed: use it inside a seeds list");
|
|
681
782
|
case "loadAccount":
|
|
@@ -683,7 +784,17 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
683
784
|
case "loadRaw":
|
|
684
785
|
case "loadRawMut":
|
|
685
786
|
case "loadForeign":
|
|
787
|
+
case "loadBorsh":
|
|
686
788
|
this.fail(node, `bind ${builtin}<T>(...) to a const first: const p = ${builtin}<T>(account)`);
|
|
789
|
+
case "loadRawAt":
|
|
790
|
+
case "loadRawMutAt":
|
|
791
|
+
case "rawArrayAt":
|
|
792
|
+
case "rawArrayMutAt":
|
|
793
|
+
case "rbTreeAt":
|
|
794
|
+
case "rbTreeMutAt":
|
|
795
|
+
this.fail(node, `bind ${builtin}(…) to a const first: const v = ${builtin}<…>(account, offset${builtin.startsWith("load") ? "" : ", capacity"})`);
|
|
796
|
+
case "storeBorsh":
|
|
797
|
+
return this.storeBorsh(node);
|
|
687
798
|
case "emit":
|
|
688
799
|
return this.emitEvent(node);
|
|
689
800
|
case "emitCpi": {
|
|
@@ -702,6 +813,29 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
702
813
|
}
|
|
703
814
|
case "returnData":
|
|
704
815
|
return this.returnData(node);
|
|
816
|
+
case "setReturnData": {
|
|
817
|
+
// Rust's set_return_data(&bytes): the bytes as they are. More than 1024 is left to the syscall, which refuses
|
|
818
|
+
// it exactly as it refuses the original's call.
|
|
819
|
+
if (args.length !== 1)
|
|
820
|
+
this.fail(node, "setReturnData(bytes) takes one list of u8");
|
|
821
|
+
if (this.ix?.returns)
|
|
822
|
+
this.fail(node, `${this.ix.name} returns a value, which is its return data: return it instead of calling setReturnData (or declare the instruction void)`);
|
|
823
|
+
const what = "setReturnData takes a list of u8: a local FixedVec<u8, N>, a Vec or FixedVec in account data, or the instruction data or a slice of it";
|
|
824
|
+
const s = this.listSpan(args[0]) ?? this.fail(args[0], what);
|
|
825
|
+
if (s.elem.kind !== "int" || s.elem.name !== "u8")
|
|
826
|
+
this.fail(args[0], what);
|
|
827
|
+
this.line(`sol_set_return_data((const uint8_t *)${s.items}, ${s.count});`);
|
|
828
|
+
return undefined;
|
|
829
|
+
}
|
|
830
|
+
case "logComputeUnits": {
|
|
831
|
+
if (args.length)
|
|
832
|
+
this.fail(node, "logComputeUnits() takes no arguments");
|
|
833
|
+
this.line(`sol_log_compute_units();`);
|
|
834
|
+
return undefined;
|
|
835
|
+
}
|
|
836
|
+
case "programAt":
|
|
837
|
+
case "sysvarAt":
|
|
838
|
+
return this.programAt(node, builtin);
|
|
705
839
|
case "instructionData":
|
|
706
840
|
this.fail(node, "bind the data to a local first: const data = instructionData()");
|
|
707
841
|
case "fixedArray":
|
|
@@ -714,6 +848,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
714
848
|
case "sighash":
|
|
715
849
|
case "hex":
|
|
716
850
|
this.fail(node, `${builtin}() is only valid inside the data list of invoke()`);
|
|
851
|
+
case "named":
|
|
852
|
+
this.fail(node, "named(account, address) is only valid as a Stake CPI's sysvar or stake config argument");
|
|
717
853
|
}
|
|
718
854
|
if (builtin)
|
|
719
855
|
this.fail(callee, `${builtin} cannot be called here`);
|
|
@@ -743,22 +879,33 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
743
879
|
return this.callHelper(node, helper);
|
|
744
880
|
if (ts.isPropertyAccessExpression(callee)) {
|
|
745
881
|
const method = callee.name.text;
|
|
882
|
+
// A RedBlackTree's methods (rbTreeAt / rbTreeMutAt).
|
|
883
|
+
const onTree = this.treeCall(node);
|
|
884
|
+
if (onTree)
|
|
885
|
+
return onTree.value;
|
|
746
886
|
const introspected = this.instructionsCall(node, callee, method);
|
|
747
887
|
if (introspected)
|
|
748
888
|
return introspected;
|
|
749
889
|
// xs.some(…) and friends on a Vec, FixedArray, FixedVec or Vec argument: a loop with the callback expanded in it.
|
|
750
890
|
if (LIST_METHODS.has(method)) {
|
|
751
891
|
const l = ts.isIdentifier(callee.expression) ? this.lookup(callee.expression.text) : undefined;
|
|
752
|
-
if (l?.type.kind === "vecArg" ||
|
|
892
|
+
if (l?.type.kind === "vecArg" ||
|
|
893
|
+
l?.type.kind === "array" ||
|
|
894
|
+
this.isPipeline(callee.expression) ||
|
|
895
|
+
this.peekArray(callee.expression) ||
|
|
896
|
+
this.isVecArgView(callee.expression) ||
|
|
897
|
+
this.isInlineArray(callee.expression))
|
|
753
898
|
return this.listMethod(node, method);
|
|
754
899
|
}
|
|
755
900
|
// A map / filter chain is consumed by a list method, `.length` or for…of, or stored: const ys = xs.map(…).
|
|
756
901
|
if (this.isPipeline(node))
|
|
757
902
|
this.fail(node, `${method} builds a new list: store it (const ys = xs.${method}(…)), or use it right away with a list method, .length or for…of`);
|
|
758
|
-
// Vec<T> instruction arguments are read-only views.
|
|
759
|
-
if (
|
|
760
|
-
|
|
761
|
-
|
|
903
|
+
// Vec<T> instruction arguments (and the instruction data) are read-only views; slice gives another one.
|
|
904
|
+
if (this.isVecArgView(callee.expression)) {
|
|
905
|
+
if (method === "slice")
|
|
906
|
+
return this.vecArgView(node);
|
|
907
|
+
const l = this.vecArgView(callee.expression);
|
|
908
|
+
{
|
|
762
909
|
// Bytes (instruction data, a Vec<u8> argument): little-endian reads at a byte offset, bounds-checked (5104).
|
|
763
910
|
const le = {
|
|
764
911
|
readU8: ["uint8_t", 1, U8],
|
|
@@ -788,7 +935,7 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
788
935
|
return { c: `(((const TS_Str *)${l.c}.ptr)[${idx}])`, type: STRING };
|
|
789
936
|
}
|
|
790
937
|
if (!isScalar(elem))
|
|
791
|
-
this.fail(node, `read a field of the element: ${callee.expression.text}.get(i).field`);
|
|
938
|
+
this.fail(node, `read a field of the element: ${ts.isIdentifier(callee.expression) ? callee.expression.text : "list"}.get(i).field`);
|
|
792
939
|
const idx = this.index(args[0], `(uint64_t)${l.c}.len`);
|
|
793
940
|
const t = this.tmp("el");
|
|
794
941
|
this.line(`${scalarStorageC(elem)} ${t};`);
|
|
@@ -853,6 +1000,9 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
853
1000
|
const right = this.expect(this.expr(args[0], left.type), left.type, args[0]);
|
|
854
1001
|
return { c: `ts_key_eq(${this.settle(left, mark).c}, ${right.c})`, type: BOOL };
|
|
855
1002
|
}
|
|
1003
|
+
const at = this.programAtValue(callee.expression);
|
|
1004
|
+
if (at)
|
|
1005
|
+
return this.programAtMethod(node, at, method);
|
|
856
1006
|
if (this.accountAt(callee.expression)) {
|
|
857
1007
|
const target = this.accountAt(callee.expression);
|
|
858
1008
|
// Program accounts used through their methods (systemProgram.transfer, tokenProgram.*…) may be optional.
|
|
@@ -871,30 +1021,19 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
871
1021
|
if (target?.kind.kind === "system" && method === "transfer")
|
|
872
1022
|
return this.systemTransfer(node);
|
|
873
1023
|
if (target?.kind.kind === "system" && method === "createAccount")
|
|
874
|
-
return this.createAccount(node, target);
|
|
1024
|
+
return this.createAccount(node, this.programParam(target));
|
|
875
1025
|
if (target?.kind.kind === "system" && method === "createPda")
|
|
876
1026
|
return this.createPda(node);
|
|
877
1027
|
if (target?.kind.kind === "system" && (method === "allocate" || method === "assign"))
|
|
878
|
-
return this.allocateOrAssign(node, target, method);
|
|
1028
|
+
return this.allocateOrAssign(node, this.programParam(target), method);
|
|
879
1029
|
if (target?.kind.kind === "tokenProgram")
|
|
880
|
-
return this.tokenOp(node, target, method);
|
|
1030
|
+
return this.tokenOp(node, this.programParam(target), method);
|
|
881
1031
|
if (target?.kind.kind === "ataProgram")
|
|
882
|
-
return this.ataOp(node, target, method);
|
|
1032
|
+
return this.ataOp(node, this.programParam(target), method);
|
|
883
1033
|
if (target?.kind.kind === "memoProgram")
|
|
884
|
-
return this.memoOp(node, target, method);
|
|
885
|
-
if (target?.kind.kind === "stakeHistory")
|
|
886
|
-
|
|
887
|
-
if (!(method in fields))
|
|
888
|
-
this.fail(callee.name, "StakeHistorySysvar has has(epoch), effective(epoch), activating(epoch) and deactivating(epoch)");
|
|
889
|
-
if (args.length !== 1)
|
|
890
|
-
this.fail(node, `${method}(epoch) takes the epoch`);
|
|
891
|
-
const epoch = this.expect(this.expr(args[0], U64), U64, args[0]);
|
|
892
|
-
const f = this.tmp("shf");
|
|
893
|
-
const v = this.tmp("shv");
|
|
894
|
-
this.line(`bool ${f};`);
|
|
895
|
-
this.line(`uint64_t ${v} = ts_stake_history(a_${target.name}, ${epoch.c}, ${Math.max(1, fields[method])}, &${f});`);
|
|
896
|
-
return method === "has" ? { c: f, type: BOOL } : { c: v, type: U64 };
|
|
897
|
-
}
|
|
1034
|
+
return this.memoOp(node, this.programParam(target), method);
|
|
1035
|
+
if (target?.kind.kind === "stakeHistory")
|
|
1036
|
+
return this.stakeHistoryRead(node, `a_${target.name}`, method);
|
|
898
1037
|
if (target?.kind.kind === "sbRandomness") {
|
|
899
1038
|
if (method !== "value" && method !== "valueU64")
|
|
900
1039
|
this.fail(callee.name, "SwitchboardRandomness has value() and valueU64()");
|
|
@@ -906,7 +1045,7 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
906
1045
|
return method === "value" ? { c: `((const SolPubkey *)${t})`, type: HASH } : { c: `ts_read_le(${t}, 8)`, type: U64 };
|
|
907
1046
|
}
|
|
908
1047
|
if (target?.kind.kind === "stakeProgram")
|
|
909
|
-
return this.stakeOp(node, target, method);
|
|
1048
|
+
return this.stakeOp(node, this.programParam(target), method);
|
|
910
1049
|
if (target?.kind.kind === "metadataProgram")
|
|
911
1050
|
return this.metadataOp(node, target, method);
|
|
912
1051
|
// Each Metaplex CPI in its own C block: its data buffer's stack slot is reused by the next one.
|
|
@@ -984,6 +1123,13 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
984
1123
|
this.fail(node, "only Vecs of Mut<...> / Init<...> accounts can grow or shrink");
|
|
985
1124
|
this.line(`TS_TRY(ts_resize(params, ${payer}, a_${v.account.name}, 8 + ${info.fixed} + (${newLen}) * ${info.elemSize}, entry_${v.account.name}));`);
|
|
986
1125
|
};
|
|
1126
|
+
if (BYTE_METHODS.has(method))
|
|
1127
|
+
return this.byteListMethod(node, method, v);
|
|
1128
|
+
if (info.big !== undefined) {
|
|
1129
|
+
const done = this.bigVecMethod(node, method, v, { stageElem, needWritable, elemPaths });
|
|
1130
|
+
if (done)
|
|
1131
|
+
return done.value;
|
|
1132
|
+
}
|
|
987
1133
|
/**
|
|
988
1134
|
* The growable Vecs stored after this one move by `by` bytes (+ grows, - shrinks): where they start and how many
|
|
989
1135
|
* bytes they take, read before the resize; references into them cannot outlive this call.
|
|
@@ -1000,6 +1146,23 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1000
1146
|
return { at, n };
|
|
1001
1147
|
};
|
|
1002
1148
|
switch (method) {
|
|
1149
|
+
case "pushAll": {
|
|
1150
|
+
// Every element of another list appended in one copy (a memcpy, not a loop of pushes).
|
|
1151
|
+
if (info.cap === undefined || info.heap)
|
|
1152
|
+
this.fail(node, "pushAll(items) appends to a FixedVec; a Vec grows one push(value) at a time (for (const x of items) list.push(x, …))");
|
|
1153
|
+
if (args.length !== 1)
|
|
1154
|
+
this.fail(node, "pushAll(items) takes the list to append");
|
|
1155
|
+
needWritable();
|
|
1156
|
+
const src = this.bulkSource(args[0], vt.elem);
|
|
1157
|
+
const n = this.tmp("n");
|
|
1158
|
+
const k = this.tmp("k");
|
|
1159
|
+
this.line(`uint64_t ${n} = ${count};`);
|
|
1160
|
+
this.line(`uint64_t ${k} = ${src.count};`);
|
|
1161
|
+
this.line(`if (${k} > ${info.cap} - ${n}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: pushAll() past the FixedVec's room");`);
|
|
1162
|
+
this.line(`ts_memcpy_bulk((uint8_t *)${info.items} + ${n} * ${info.elemSize}, (const uint8_t *)${src.items}, ${k} * ${info.elemSize});`);
|
|
1163
|
+
this.line(`${info.len} = (uint32_t)(${n} + ${k});`);
|
|
1164
|
+
return undefined;
|
|
1165
|
+
}
|
|
1003
1166
|
case "set": {
|
|
1004
1167
|
if (args.length !== 2)
|
|
1005
1168
|
this.fail(node, "set(index, value) takes two arguments");
|
|
@@ -1105,6 +1268,150 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1105
1268
|
}
|
|
1106
1269
|
this.fail(node, `Vecs support get, set, push, pop, clear and .length, not ${method}()`);
|
|
1107
1270
|
}
|
|
1271
|
+
/**
|
|
1272
|
+
* The methods a BigVec adds or changes (SPL's big_vec): `push` into the account's room, `retain`, and the refusals;
|
|
1273
|
+
* undefined for the methods it shares with other lists (`set`).
|
|
1274
|
+
*/
|
|
1275
|
+
bigVecMethod(node, method, v, h) {
|
|
1276
|
+
const args = node.arguments;
|
|
1277
|
+
const info = v.vec;
|
|
1278
|
+
const vt = v.type;
|
|
1279
|
+
if (method === "set")
|
|
1280
|
+
return undefined;
|
|
1281
|
+
if (info.raw)
|
|
1282
|
+
this.fail(node, `a RawArray has get, set, .length, for … of and the list methods (its length is the capacity it was made with), not ${method}()`);
|
|
1283
|
+
if (method === "slice")
|
|
1284
|
+
this.fail(node, "use slice(start, end) right where it is read: for (const x of list.slice(a, b)), list.slice(a, b).forEach(…) or .get(i)");
|
|
1285
|
+
if (info.slice)
|
|
1286
|
+
this.fail(node, `a slice has get, set, .length, for … of and the list methods; call ${method}() on the BigVec itself`);
|
|
1287
|
+
switch (method) {
|
|
1288
|
+
case "push": {
|
|
1289
|
+
// BigVec::push: the element goes after the last one if the account has room for it, else AccountDataTooSmall.
|
|
1290
|
+
if (args.length !== 1)
|
|
1291
|
+
this.fail(node, "push(value) on a BigVec takes the value (its room is the account's, never resized)");
|
|
1292
|
+
h.needWritable();
|
|
1293
|
+
const write = h.stageElem(args[0]);
|
|
1294
|
+
const n = this.tmp("n");
|
|
1295
|
+
this.line(`uint64_t ${n} = (uint64_t)${info.len};`);
|
|
1296
|
+
this.line(`if (${n} >= ${info.big}) ${this.programErrorFail("AccountDataTooSmall", node)};`);
|
|
1297
|
+
this.line(`${info.len} = (uint32_t)(${n} + 1);`);
|
|
1298
|
+
write(this.withFixedVec({ ...v, lv: `${info.items}[${n}]`, type: vt.elem, vec: undefined, path: undefined }));
|
|
1299
|
+
return { value: undefined };
|
|
1300
|
+
}
|
|
1301
|
+
case "retain": {
|
|
1302
|
+
// BigVec::retain: one pass, the predicate reading each element where it was; each run of kept elements moves
|
|
1303
|
+
// down once (sol_memmove), when the next removal (or the end) is found. Bytes past the new end keep what they held.
|
|
1304
|
+
if (args.length !== 1)
|
|
1305
|
+
this.fail(node, "retain(fn) takes one argument: (x) => keep it");
|
|
1306
|
+
const cb = args[0];
|
|
1307
|
+
if (!ts.isArrowFunction(cb) && !ts.isFunctionExpression(cb))
|
|
1308
|
+
this.fail(cb, "pass retain an arrow function written here: xs.retain((x) => …)");
|
|
1309
|
+
if (cb.parameters.length > 1)
|
|
1310
|
+
this.fail(cb.parameters[1], "retain's callback takes the element");
|
|
1311
|
+
h.needWritable();
|
|
1312
|
+
this.assertNotAliased(h.elemPaths(), node);
|
|
1313
|
+
const size = info.elemSize;
|
|
1314
|
+
if (vt.elem.kind === "struct")
|
|
1315
|
+
return this.retainStructs(node, cb, v, vt.elem.name, size);
|
|
1316
|
+
const items = this.tmp("rt_items");
|
|
1317
|
+
const n = this.tmp("rt_n");
|
|
1318
|
+
const removed = this.tmp("rt_removed");
|
|
1319
|
+
const dst = this.tmp("rt_dst");
|
|
1320
|
+
const i = this.tmp("rt_i");
|
|
1321
|
+
const move = (count) => `sol_memmove_(${items} + ${dst} * ${size}, ${items} + (${dst} + ${removed}) * ${size}, (${count}) * ${size});`;
|
|
1322
|
+
this.line(`{`);
|
|
1323
|
+
this.block(() => {
|
|
1324
|
+
this.line(`uint8_t *${items} = (uint8_t *)${info.items};`);
|
|
1325
|
+
this.line(`uint64_t ${n} = ${vecCount(info)}, ${removed} = 0, ${dst} = 0;`);
|
|
1326
|
+
this.line(`for (uint64_t ${i} = 0; ${i} < ${n}; ${i}++) {`);
|
|
1327
|
+
this.block(() => {
|
|
1328
|
+
const f = ts.factory;
|
|
1329
|
+
const place = (x) => {
|
|
1330
|
+
ts.setTextRange(x, node);
|
|
1331
|
+
x.parent = node;
|
|
1332
|
+
return x;
|
|
1333
|
+
};
|
|
1334
|
+
const index = `__rt${this.temp++}`;
|
|
1335
|
+
this.scopes.at(-1).set(index, { c: i, type: U64, mutable: false });
|
|
1336
|
+
const list = node.expression.expression;
|
|
1337
|
+
const element = place(f.createCallExpression(place(f.createPropertyAccessExpression(list, "get")), undefined, [place(f.createIdentifier(index))]));
|
|
1338
|
+
const closure = { node: cb, name: "retain's callback", scopes: [...this.scopes], env: this.envNow(), imports: this.scope.imports };
|
|
1339
|
+
const kept = this.expandClosure(closure, [element].slice(0, cb.parameters.length), cb);
|
|
1340
|
+
if (!kept)
|
|
1341
|
+
this.fail(cb, "retain's callback returns a boolean: true keeps the element");
|
|
1342
|
+
const b = this.expect(kept, BOOL, cb);
|
|
1343
|
+
this.line(`if (!(${b.c})) {`);
|
|
1344
|
+
this.line(` if (${removed} > 0 && ${i} - ${removed} > ${dst}) ${move(`${i} - ${removed} - ${dst}`)}`);
|
|
1345
|
+
this.line(` ${dst} = ${i} - ${removed};`);
|
|
1346
|
+
this.line(` ${removed}++;`);
|
|
1347
|
+
this.line(`}`);
|
|
1348
|
+
});
|
|
1349
|
+
this.line(`}`);
|
|
1350
|
+
this.line(`if (${removed} > 0 && ${n} - ${removed} > ${dst}) ${move(`${n} - ${removed} - ${dst}`)}`);
|
|
1351
|
+
this.line(`${info.len} = (uint32_t)(${n} - ${removed});`);
|
|
1352
|
+
});
|
|
1353
|
+
this.line(`}`);
|
|
1354
|
+
return { value: undefined };
|
|
1355
|
+
}
|
|
1356
|
+
case "pop":
|
|
1357
|
+
case "clear":
|
|
1358
|
+
this.fail(node, `a BigVec has push and retain (as SPL's big_vec), not ${method}(): remove elements with retain((x) => …)`);
|
|
1359
|
+
}
|
|
1360
|
+
this.fail(node, `a BigVec supports get, set, push, retain, slice, find / findIndex and the other list methods, .length and .capacity, not ${method}()`);
|
|
1361
|
+
}
|
|
1362
|
+
/**
|
|
1363
|
+
* BigVec::retain over struct elements, walked with a pointer: the predicate gets each element in place, a kept one
|
|
1364
|
+
* costs its predicate and the step. `run` is the first element not yet moved (the run of kept ones since the last
|
|
1365
|
+
* removal), `dst` where that run goes; each run moves down once, when the next removal (or the end) is found, and
|
|
1366
|
+
* only once something before it was removed. The length is written once, at the end (the moves never reach it).
|
|
1367
|
+
*/
|
|
1368
|
+
retainStructs(node, cb, v, struct, size) {
|
|
1369
|
+
const info = v.vec;
|
|
1370
|
+
const items = this.tmp("rt_items");
|
|
1371
|
+
const end = this.tmp("rt_end");
|
|
1372
|
+
const run = this.tmp("rt_run");
|
|
1373
|
+
const dst = this.tmp("rt_dst");
|
|
1374
|
+
const p = this.tmp("rt_p");
|
|
1375
|
+
this.line(`{`);
|
|
1376
|
+
this.block(() => {
|
|
1377
|
+
this.line(`uint8_t *${items} = (uint8_t *)${info.items};`);
|
|
1378
|
+
this.line(`uint8_t *${end} = ${items} + ${vecCount(info)} * ${size}, *${run} = ${items}, *${dst} = ${items};`);
|
|
1379
|
+
this.line(`for (uint8_t *${p} = ${items}; ${p} < ${end}; ${p} += ${size}) {`);
|
|
1380
|
+
this.block(() => {
|
|
1381
|
+
const el = this.tmp("rt_el");
|
|
1382
|
+
this.line(`TSS_${struct} *${el} = (TSS_${struct} *)${p};`);
|
|
1383
|
+
const list = node.expression.expression;
|
|
1384
|
+
const id = ts.factory.createIdentifier(`__rt${this.temp++}`);
|
|
1385
|
+
ts.setTextRange(id, node);
|
|
1386
|
+
id.parent = node;
|
|
1387
|
+
// The element as list.get(i) gives it: a reference into the list, with the list's aliasing paths.
|
|
1388
|
+
this.scopes.at(-1).set(id.text, {
|
|
1389
|
+
c: el,
|
|
1390
|
+
type: { kind: "structRef", struct, writable: !!v.writable },
|
|
1391
|
+
mutable: false,
|
|
1392
|
+
paths: this.pathsOf(list)?.map((x) => `${x}[]`),
|
|
1393
|
+
});
|
|
1394
|
+
const closure = { node: cb, name: "retain's callback", scopes: [...this.scopes], env: this.envNow(), imports: this.scope.imports };
|
|
1395
|
+
const kept = this.expandClosure(closure, [id].slice(0, cb.parameters.length), cb);
|
|
1396
|
+
if (!kept)
|
|
1397
|
+
this.fail(cb, "retain's callback returns a boolean: true keeps the element");
|
|
1398
|
+
const b = this.expect(kept, BOOL, cb);
|
|
1399
|
+
const at = this.tmp("rt_at");
|
|
1400
|
+
this.line(`if (!(${b.c})) {`);
|
|
1401
|
+
// The removal's own copy of the position, so the scan loop keeps a single pointer (see ts_opaque_ptr).
|
|
1402
|
+
this.line(` uint8_t *${at} = ts_opaque_ptr(${p});`);
|
|
1403
|
+
this.line(` if (${dst} != ${run} && ${at} != ${run}) sol_memmove_(${dst}, ${run}, ${at} - ${run});`);
|
|
1404
|
+
this.line(` ${dst} += ${at} - ${run};`);
|
|
1405
|
+
this.line(` ${run} = ${at} + ${size};`);
|
|
1406
|
+
this.line(`}`);
|
|
1407
|
+
});
|
|
1408
|
+
this.line(`}`);
|
|
1409
|
+
this.line(`if (${dst} != ${run} && ${end} != ${run}) sol_memmove_(${dst}, ${run}, ${end} - ${run});`);
|
|
1410
|
+
this.line(`${info.len} = (uint32_t)((uint64_t)(${dst} + (${end} - ${run}) - ${items}) / ${size});`);
|
|
1411
|
+
});
|
|
1412
|
+
this.line(`}`);
|
|
1413
|
+
return { value: undefined };
|
|
1414
|
+
}
|
|
1108
1415
|
/** sha256(...) / keccak256(...) over strings, Pubkeys, Hashes, integers (LE) and booleans. */
|
|
1109
1416
|
hashCall(node, fn) {
|
|
1110
1417
|
if (node.arguments.length === 0 || node.arguments.length > 16)
|
|
@@ -1337,9 +1644,155 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1337
1644
|
}
|
|
1338
1645
|
this.fail(node, "a TransactionInstruction has programId, accountsLength, dataLength, accountKey/accountIsSigner/accountIsWritable(i), readU8/U16/U32/U64/readPubkey(offset) and is(program, name)");
|
|
1339
1646
|
}
|
|
1647
|
+
/** `fixedArray<T, N>(fill)` written inline (a list method, a map / filter chain or `for … of` over it). */
|
|
1648
|
+
isInlineArray(node) {
|
|
1649
|
+
if (ts.isParenthesizedExpression(node))
|
|
1650
|
+
return this.isInlineArray(node.expression);
|
|
1651
|
+
return ts.isCallExpression(node) && this.exportName(node.expression) === "fixedArray";
|
|
1652
|
+
}
|
|
1653
|
+
/**
|
|
1654
|
+
* Whether `node` is a read-only view of a Vec argument or the instruction data, without emitting code: a local or
|
|
1655
|
+
* helper parameter holding one, or `.slice(start, end?)` of such a view.
|
|
1656
|
+
*/
|
|
1657
|
+
isVecArgView(node) {
|
|
1658
|
+
if (ts.isParenthesizedExpression(node))
|
|
1659
|
+
return this.isVecArgView(node.expression);
|
|
1660
|
+
if (ts.isIdentifier(node))
|
|
1661
|
+
return this.lookup(node.text)?.type.kind === "vecArg";
|
|
1662
|
+
return (ts.isCallExpression(node) &&
|
|
1663
|
+
ts.isPropertyAccessExpression(node.expression) &&
|
|
1664
|
+
node.expression.name.text === "slice" &&
|
|
1665
|
+
this.isVecArgView(node.expression.expression));
|
|
1666
|
+
}
|
|
1667
|
+
/**
|
|
1668
|
+
* The view `node` names (see isVecArgView) as a `TS_VecArg` C expression. `.slice(start, end)` is elements start..end-1
|
|
1669
|
+
* in place (`end` defaults to the length): unlike JS's slice it does not clamp, an `end` past the length or before
|
|
1670
|
+
* `start` fails with 5104. Undefined when `node` is not such a view.
|
|
1671
|
+
*/
|
|
1672
|
+
vecArgView(node) {
|
|
1673
|
+
if (ts.isParenthesizedExpression(node))
|
|
1674
|
+
return this.vecArgView(node.expression);
|
|
1675
|
+
if (ts.isIdentifier(node)) {
|
|
1676
|
+
const l = this.lookup(node.text);
|
|
1677
|
+
return l?.type.kind === "vecArg" ? { c: l.c, type: l.type } : undefined;
|
|
1678
|
+
}
|
|
1679
|
+
if (!this.isVecArgView(node))
|
|
1680
|
+
return undefined;
|
|
1681
|
+
const call = node;
|
|
1682
|
+
const base = this.vecArgView(call.expression.expression);
|
|
1683
|
+
if (base.type.optional)
|
|
1684
|
+
this.fail(call, "check the Option argument is not null before slicing it");
|
|
1685
|
+
const elem = base.type.elem;
|
|
1686
|
+
if (elem.kind === "string")
|
|
1687
|
+
this.fail(call, "slice works on lists of fixed-size elements, not on a Vec<string>");
|
|
1688
|
+
if (call.arguments.length < 1 || call.arguments.length > 2)
|
|
1689
|
+
this.fail(call, "slice(start, end?) takes the first element's index and the index after the last one");
|
|
1690
|
+
const start = this.tmp("sl_start");
|
|
1691
|
+
const end = this.tmp("sl_end");
|
|
1692
|
+
this.line(`uint64_t ${start} = ${this.expect(this.expr(call.arguments[0], U64), U64, call.arguments[0]).c};`);
|
|
1693
|
+
this.line(`uint64_t ${end} = ${call.arguments[1] ? this.expect(this.expr(call.arguments[1], U64), U64, call.arguments[1]).c : `(uint64_t)${base.c}.len`};`);
|
|
1694
|
+
this.line(`if (${end} > (uint64_t)${base.c}.len || ${start} > ${end}) TS_FAIL(TS_ERR_INDEX, "TypeSOL: slice out of range");`);
|
|
1695
|
+
const t = this.tmp("view");
|
|
1696
|
+
this.line(`TS_VecArg ${t} = {${base.c}.ptr + ${start} * ${this.fieldBytes(elem)}, (uint32_t)(${end} - ${start})};`);
|
|
1697
|
+
return { c: t, type: { kind: "vecArg", elem } };
|
|
1698
|
+
}
|
|
1699
|
+
/**
|
|
1700
|
+
* A list's elements as one contiguous run, for a bulk copy or a CPI: a Vec argument, the instruction data or a slice
|
|
1701
|
+
* of them; a Vec, FixedVec, BigVec (slice) or FixedArray in account data or a local. Undefined for anything else.
|
|
1702
|
+
*/
|
|
1703
|
+
listSpan(e) {
|
|
1704
|
+
if (this.isVecArgView(e)) {
|
|
1705
|
+
const v = this.vecArgView(e);
|
|
1706
|
+
return { items: `${v.c}.ptr`, count: `((uint64_t)${v.c}.len)`, elem: v.type.elem, view: true };
|
|
1707
|
+
}
|
|
1708
|
+
const r = this.ref(e);
|
|
1709
|
+
if (r?.type.kind === "array")
|
|
1710
|
+
return { items: `${r.lv}`, count: `${r.type.len}ULL`, elem: r.type.elem, view: false };
|
|
1711
|
+
if (r?.vec && r.type.kind === "vec")
|
|
1712
|
+
return { items: r.vec.items, count: vecCount(r.vec), elem: r.type.elem, view: false };
|
|
1713
|
+
return undefined;
|
|
1714
|
+
}
|
|
1715
|
+
/** `pushAll(items)`'s source: a list of exactly `elem` (see listSpan). */
|
|
1716
|
+
bulkSource(e, elem) {
|
|
1717
|
+
const what = `pushAll takes a list of ${typeName(elem)}: a Vec, FixedVec or FixedArray, a Vec argument, or the instruction data or a slice of it`;
|
|
1718
|
+
const s = this.listSpan(e) ?? this.fail(e, what);
|
|
1719
|
+
if (!sameType(s.elem, elem))
|
|
1720
|
+
this.fail(e, what);
|
|
1721
|
+
// A Vec argument's booleans and enums are checked as each is read (get, for … of), not on entry.
|
|
1722
|
+
if (s.view && (elem.kind === "bool" || elem.kind === "enum"))
|
|
1723
|
+
this.fail(e, "a Vec argument's booleans and enums are checked as each is read: push them one by one (for … of)");
|
|
1724
|
+
return s;
|
|
1725
|
+
}
|
|
1726
|
+
/**
|
|
1727
|
+
* Whether `node` names one account a choice may pick, without emitting code: a remaining account (`rest.get(i)`), a
|
|
1728
|
+
* local or `RemainingAccount` helper parameter bound to one, an `AccountInfo` parameter, or a choice between those.
|
|
1729
|
+
*/
|
|
1730
|
+
looksLikeAccountHandle(node) {
|
|
1731
|
+
if (ts.isParenthesizedExpression(node))
|
|
1732
|
+
return this.looksLikeAccountHandle(node.expression);
|
|
1733
|
+
if (ts.isConditionalExpression(node))
|
|
1734
|
+
return this.looksLikeAccountHandle(node.whenTrue) && this.looksLikeAccountHandle(node.whenFalse);
|
|
1735
|
+
if (ts.isIdentifier(node)) {
|
|
1736
|
+
const l = this.lookup(node.text);
|
|
1737
|
+
if (l)
|
|
1738
|
+
return l.type.kind === "account";
|
|
1739
|
+
return this.accountAt(node)?.kind.kind === "info";
|
|
1740
|
+
}
|
|
1741
|
+
return (ts.isCallExpression(node) &&
|
|
1742
|
+
ts.isPropertyAccessExpression(node.expression) &&
|
|
1743
|
+
node.expression.name.text === "get" &&
|
|
1744
|
+
this.isRemaining(node.expression.expression));
|
|
1745
|
+
}
|
|
1746
|
+
/**
|
|
1747
|
+
* `c ? rest.get(5n) : reserve`: one of two accounts, chosen at run time (only the chosen side runs), as a `TsAccount *`
|
|
1748
|
+
* usable wherever a remaining account is. Each side is a remaining account, a local or helper parameter bound to one,
|
|
1749
|
+
* an `AccountInfo` parameter or another such choice; a `programAt` check is kept when both sides carry the same one.
|
|
1750
|
+
*/
|
|
1751
|
+
accountChoice(node) {
|
|
1752
|
+
const side = (e) => {
|
|
1753
|
+
if (ts.isParenthesizedExpression(e))
|
|
1754
|
+
return side(e.expression);
|
|
1755
|
+
if (ts.isConditionalExpression(e))
|
|
1756
|
+
return this.accountChoice(e);
|
|
1757
|
+
if (ts.isIdentifier(e)) {
|
|
1758
|
+
const l = this.lookup(e.text);
|
|
1759
|
+
if (l?.type.kind === "account")
|
|
1760
|
+
return { c: l.c, type: l.type };
|
|
1761
|
+
const a = this.accountAt(e);
|
|
1762
|
+
if (!l && a?.kind.kind === "info")
|
|
1763
|
+
return { c: `a_${this.accountParam(e, "a choice between accounts").name}`, type: { kind: "account" } };
|
|
1764
|
+
}
|
|
1765
|
+
const h = this.handle(e);
|
|
1766
|
+
if (h)
|
|
1767
|
+
return { c: h, type: { kind: "account" } };
|
|
1768
|
+
this.fail(e, "choose between accounts of the same kind: remaining accounts (rest.get(i), a local or RemainingAccount parameter bound to one) or AccountInfo parameters");
|
|
1769
|
+
};
|
|
1770
|
+
const cond = this.expect(this.expr(node.condition, BOOL), BOOL, node.condition);
|
|
1771
|
+
const t = this.tmp("acct");
|
|
1772
|
+
this.line(`TsAccount *${t};`);
|
|
1773
|
+
this.line(`if (${cond.c}) {`);
|
|
1774
|
+
let a;
|
|
1775
|
+
let b;
|
|
1776
|
+
this.block(() => {
|
|
1777
|
+
a = side(node.whenTrue);
|
|
1778
|
+
this.line(`${t} = ${a.c};`);
|
|
1779
|
+
});
|
|
1780
|
+
this.line(`} else {`);
|
|
1781
|
+
this.block(() => {
|
|
1782
|
+
b = side(node.whenFalse);
|
|
1783
|
+
this.line(`${t} = ${b.c};`);
|
|
1784
|
+
});
|
|
1785
|
+
this.line(`}`);
|
|
1786
|
+
const pa = a.type.kind === "account" ? a.type.program : undefined;
|
|
1787
|
+
const pb = b.type.kind === "account" ? b.type.program : undefined;
|
|
1788
|
+
const program = pa && pb && JSON.stringify(pa) === JSON.stringify(pb) ? pa : undefined;
|
|
1789
|
+
return { c: t, type: { kind: "account", ...(program ? { program } : {}) } };
|
|
1790
|
+
}
|
|
1340
1791
|
handle(node) {
|
|
1341
1792
|
if (ts.isParenthesizedExpression(node))
|
|
1342
1793
|
return this.handle(node.expression);
|
|
1794
|
+
if (ts.isConditionalExpression(node) && this.looksLikeAccountHandle(node))
|
|
1795
|
+
return this.accountChoice(node).c;
|
|
1343
1796
|
if (ts.isIdentifier(node)) {
|
|
1344
1797
|
const l = this.lookup(node.text);
|
|
1345
1798
|
return l?.type.kind === "account" ? l.c : undefined;
|
|
@@ -1365,6 +1818,125 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1365
1818
|
return h;
|
|
1366
1819
|
return `a_${this.accountParam(node, what).name}`;
|
|
1367
1820
|
}
|
|
1821
|
+
/**
|
|
1822
|
+
* An account argument of a typed CPI: a declared account parameter (`param`, its kind and writability checked by
|
|
1823
|
+
* the caller), or a remaining account, a local bound to one, a RemainingAccount helper parameter or a loaded struct
|
|
1824
|
+
* (no compile-time checks: the called program and the runtime check them).
|
|
1825
|
+
*/
|
|
1826
|
+
cpiAccount(node, what) {
|
|
1827
|
+
const h = this.handle(node);
|
|
1828
|
+
if (h)
|
|
1829
|
+
return { c: h };
|
|
1830
|
+
const loaded = ts.isIdentifier(node) ? this.lookup(node.text)?.loaded : undefined;
|
|
1831
|
+
if (loaded)
|
|
1832
|
+
return { c: loaded.handle };
|
|
1833
|
+
const param = this.accountParam(node, what);
|
|
1834
|
+
return { c: `a_${param.name}`, param };
|
|
1835
|
+
}
|
|
1836
|
+
/** A declared program parameter as the program of a typed CPI. */
|
|
1837
|
+
programParam(a) {
|
|
1838
|
+
return { c: `a_${a.name}`, kind: a.kind };
|
|
1839
|
+
}
|
|
1840
|
+
/**
|
|
1841
|
+
* `programAt<P>(acct)` / `sysvarAt<S>(acct)`: the account (a remaining account or an AccountInfo parameter) checked
|
|
1842
|
+
* to be that program or sysvar by its key, once, then usable with P's typed methods. A wrong program fails with
|
|
1843
|
+
* ProgramError.IncorrectProgramId and a wrong sysvar with ProgramError.InvalidArgument, as solana_program's checks do.
|
|
1844
|
+
*/
|
|
1845
|
+
programAt(node, fn) {
|
|
1846
|
+
const programs = {
|
|
1847
|
+
StakeProgram: [{ kind: "stakeProgram" }, "TS_STAKE_PROGRAM_ID", "the Stake program"],
|
|
1848
|
+
SystemProgram: [{ kind: "system" }, "TS_SYSTEM_PROGRAM_ID", "the System Program"],
|
|
1849
|
+
TokenProgram: [{ kind: "tokenProgram", flavor: "token" }, "TS_TOKEN_PROGRAM_ID", "the Token program"],
|
|
1850
|
+
Token2022Program: [{ kind: "tokenProgram", flavor: "token2022" }, "TS_TOKEN_2022_PROGRAM_ID", "the Token-2022 program"],
|
|
1851
|
+
TokenInterface: [{ kind: "tokenProgram", flavor: "tokenInterface" }, undefined, "a token program"],
|
|
1852
|
+
AssociatedTokenProgram: [{ kind: "ataProgram" }, "TS_ATA_PROGRAM_ID", "the Associated Token program"],
|
|
1853
|
+
MemoProgram: [{ kind: "memoProgram" }, "TS_MEMO_PROGRAM_ID", "the Memo program"],
|
|
1854
|
+
};
|
|
1855
|
+
const sysvars = { StakeHistorySysvar: [{ kind: "stakeHistory" }, "TS_STAKE_HISTORY_ID", "the StakeHistory sysvar"] };
|
|
1856
|
+
const table = fn === "programAt" ? programs : sysvars;
|
|
1857
|
+
const targ = node.typeArguments?.[0];
|
|
1858
|
+
const name = targ && typesolName(targ, this.scope.imports);
|
|
1859
|
+
const entry = name ? table[name] : undefined;
|
|
1860
|
+
if (!entry)
|
|
1861
|
+
this.fail(targ ?? node, fn === "programAt" ? `programAt<P>(account): P is one of ${Object.keys(programs).join(", ")}` : "sysvarAt<S>(account): S is StakeHistorySysvar");
|
|
1862
|
+
if (node.arguments.length !== 1)
|
|
1863
|
+
this.fail(node, `${fn}<${name}>(account) takes one remaining account or AccountInfo parameter`);
|
|
1864
|
+
const arg = node.arguments[0];
|
|
1865
|
+
let h = this.handle(arg);
|
|
1866
|
+
if (!h) {
|
|
1867
|
+
const acct = this.accountParam(arg, `${fn}'s account`);
|
|
1868
|
+
if (acct.kind.kind !== "info")
|
|
1869
|
+
this.fail(arg, `pass a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter; a declared parameter can be typed ${name} itself`);
|
|
1870
|
+
h = `a_${acct.name}`;
|
|
1871
|
+
}
|
|
1872
|
+
const [kind, id, what] = entry;
|
|
1873
|
+
const err = PROGRAM_ERRORS.indexOf(fn === "programAt" ? "IncorrectProgramId" : "InvalidArgument");
|
|
1874
|
+
// `const PROGRAM_ERROR_LOG_PREFIX = "Program error: "`: logged as a native entrypoint logs the error.
|
|
1875
|
+
const pre = this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value;
|
|
1876
|
+
const text = typeof pre === "string" ? `${pre}${PROGRAM_ERRORS[err]}` : `TypeSOL: not ${what}`;
|
|
1877
|
+
const bad = id ? `!ts_key_eq(&${h}->key, &${id})` : `!ts_is_token_program(&${h}->key)`;
|
|
1878
|
+
this.line(`if (${bad}) ${this.programFail(`((uint64_t)${err + 2}) << 32`, text)};`);
|
|
1879
|
+
if (kind.kind === "stakeHistory")
|
|
1880
|
+
this.line(`if (${h}->data_len < 8) TS_FAIL(TS_ERR_SYSVAR, "TypeSOL: not the StakeHistory sysvar's data");`);
|
|
1881
|
+
return { c: h, type: { kind: "account", program: kind } };
|
|
1882
|
+
}
|
|
1883
|
+
/** A value `programAt` / `sysvarAt` checked (a local bound to one, or the call itself), as the program it is. */
|
|
1884
|
+
programAtValue(node) {
|
|
1885
|
+
if (ts.isParenthesizedExpression(node))
|
|
1886
|
+
return this.programAtValue(node.expression);
|
|
1887
|
+
if (ts.isIdentifier(node)) {
|
|
1888
|
+
const l = this.lookup(node.text);
|
|
1889
|
+
return l?.type.kind === "account" && l.type.program ? { c: l.c, kind: l.type.program } : undefined;
|
|
1890
|
+
}
|
|
1891
|
+
if (!ts.isCallExpression(node))
|
|
1892
|
+
return undefined;
|
|
1893
|
+
const fn = this.exportName(node.expression);
|
|
1894
|
+
if (fn !== "programAt" && fn !== "sysvarAt")
|
|
1895
|
+
return undefined;
|
|
1896
|
+
const v = this.programAt(node, fn);
|
|
1897
|
+
return { c: v.c, kind: v.type.program };
|
|
1898
|
+
}
|
|
1899
|
+
/** `stake.split(…)` on a programAt value: the same typed methods as on a declared program parameter. */
|
|
1900
|
+
programAtMethod(node, at, method) {
|
|
1901
|
+
switch (at.kind.kind) {
|
|
1902
|
+
case "system":
|
|
1903
|
+
if (method === "transfer")
|
|
1904
|
+
return this.systemTransfer(node);
|
|
1905
|
+
if (method === "createAccount")
|
|
1906
|
+
return this.createAccount(node, at);
|
|
1907
|
+
if (method === "createPda")
|
|
1908
|
+
return this.createPda(node);
|
|
1909
|
+
if (method === "allocate" || method === "assign")
|
|
1910
|
+
return this.allocateOrAssign(node, at, method);
|
|
1911
|
+
this.fail(node.expression, `the System Program has transfer, createAccount, createPda, allocate and assign, not ${method}`);
|
|
1912
|
+
case "tokenProgram":
|
|
1913
|
+
return this.tokenOp(node, at, method);
|
|
1914
|
+
case "ataProgram":
|
|
1915
|
+
return this.ataOp(node, at, method);
|
|
1916
|
+
case "memoProgram":
|
|
1917
|
+
return this.memoOp(node, at, method);
|
|
1918
|
+
case "stakeProgram":
|
|
1919
|
+
return this.stakeOp(node, at, method);
|
|
1920
|
+
case "stakeHistory":
|
|
1921
|
+
return this.stakeHistoryRead(node, at.c, method);
|
|
1922
|
+
}
|
|
1923
|
+
this.fail(node.expression, `unsupported call: ${method}`);
|
|
1924
|
+
}
|
|
1925
|
+
/** StakeHistorySysvar's has / effective / activating / deactivating(epoch), on the sysvar account `h`. */
|
|
1926
|
+
stakeHistoryRead(node, h, method) {
|
|
1927
|
+
const args = node.arguments;
|
|
1928
|
+
const fields = { has: 0, effective: 1, activating: 2, deactivating: 3 };
|
|
1929
|
+
if (!(method in fields))
|
|
1930
|
+
this.fail(node.expression.name, "StakeHistorySysvar has has(epoch), effective(epoch), activating(epoch) and deactivating(epoch)");
|
|
1931
|
+
if (args.length !== 1)
|
|
1932
|
+
this.fail(node, `${method}(epoch) takes the epoch`);
|
|
1933
|
+
const epoch = this.expect(this.expr(args[0], U64), U64, args[0]);
|
|
1934
|
+
const f = this.tmp("shf");
|
|
1935
|
+
const v = this.tmp("shv");
|
|
1936
|
+
this.line(`bool ${f};`);
|
|
1937
|
+
this.line(`uint64_t ${v} = ts_stake_history(${h}, ${epoch.c}, ${Math.max(1, fields[method])}, &${f});`);
|
|
1938
|
+
return method === "has" ? { c: f, type: BOOL } : { c: v, type: U64 };
|
|
1939
|
+
}
|
|
1368
1940
|
/** `readData<T>(account, offset)`: a bounds-checked little-endian read of any account's data. */
|
|
1369
1941
|
readData(node) {
|
|
1370
1942
|
const targ = node.typeArguments?.[0];
|
|
@@ -1452,38 +2024,212 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1452
2024
|
const fn = mut ? "loadRawMut" : "loadRaw";
|
|
1453
2025
|
const targ = node.typeArguments?.[0];
|
|
1454
2026
|
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)
|
|
2027
|
+
if (!s || s.size === undefined || (s.vec && !s.bigVec))
|
|
1456
2028
|
this.fail(node, `${fn} needs a fixed-size struct type: ${fn}<MyStruct>(account)`);
|
|
1457
2029
|
if (s.layout === "borsh")
|
|
1458
2030
|
this.fail(node, `${s.name} is @layout borsh: ${fn} reads fixed layouts only`);
|
|
1459
2031
|
if (node.arguments.length !== 1)
|
|
1460
2032
|
this.fail(node, `${fn}<T>(account) takes one remaining account or AccountInfo parameter`);
|
|
1461
|
-
|
|
1462
|
-
|
|
2033
|
+
const { h, param } = this.rawAccount(node, fn, mut);
|
|
2034
|
+
this.line(this.viewOwnerCheck(h));
|
|
2035
|
+
this.line(`if (${h}->data_len < sizeof(TSS_${s.name})) TS_FAIL(TS_ERR_ACCOUNT_TOO_SMALL, "TypeSOL: account data too small");`);
|
|
2036
|
+
// A BigVec's stored length must fit in the account. Its capacity is kept in a local: every access is clamped to it
|
|
2037
|
+
// (the length may be written again after this), without a division each time.
|
|
2038
|
+
let bigCap;
|
|
2039
|
+
if (s.bigVec) {
|
|
2040
|
+
bigCap = this.tmp("bv_cap");
|
|
2041
|
+
this.line(`uint64_t ${bigCap} = (${h}->data_len - sizeof(TSS_${s.name})) / ${s.bigVec.elemSize};`);
|
|
2042
|
+
this.line(`if ((uint64_t)((TSS_${s.name} *)(${h}->data))->${s.bigVec.name}__len > ${bigCap}) ${this.programErrorFail("AccountDataTooSmall", node)};`);
|
|
2043
|
+
// Named in scope, so a loop moved into a function of its own is given it (see outlinedLoop).
|
|
2044
|
+
this.scopes.at(-1).set(`__${bigCap}`, { c: bigCap, type: U64, mutable: false });
|
|
2045
|
+
}
|
|
2046
|
+
if (mut)
|
|
2047
|
+
this.claimRawMut(node, h, param);
|
|
2048
|
+
return { c: `((TSS_${s.name} *)(${h}->data))`, type: { kind: "structRef", struct: s.name, writable: mut }, ...(bigCap ? { bigCap } : {}) };
|
|
2049
|
+
}
|
|
2050
|
+
/**
|
|
2051
|
+
* A native account view's owner check (3007). In a program that makes such views the check goes through ts_owned: the
|
|
2052
|
+
* last account found this program's passes with a pointer compare until a CPI or an owner write forgets it.
|
|
2053
|
+
*/
|
|
2054
|
+
viewOwnerCheck(h) {
|
|
2055
|
+
const fail = `TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: account not owned by this program")`;
|
|
2056
|
+
return this.model.ownerCache ? `if (!ts_owned(params, ${h})) ${fail};` : `if (!ts_key_eq(&${h}->owner, params->program_id)) ${fail};`;
|
|
2057
|
+
}
|
|
2058
|
+
/** An owner write or a CPI: the owner checks' cache (viewOwnerCheck) is forgotten. */
|
|
2059
|
+
forgetOwners() {
|
|
2060
|
+
if (this.model.ownerCache)
|
|
2061
|
+
this.line(`TS_OWNER_FORGET(params);`);
|
|
2062
|
+
}
|
|
2063
|
+
/**
|
|
2064
|
+
* The account a loadRaw-style view reads (its first argument): a remaining account, or an AccountInfo parameter of
|
|
2065
|
+
* the instruction (`param`: its position, for the claim). `fn` names the call in messages.
|
|
2066
|
+
*/
|
|
2067
|
+
rawAccount(node, fn, mut) {
|
|
2068
|
+
const h = this.handle(node.arguments[0]);
|
|
2069
|
+
if (h)
|
|
2070
|
+
return { h };
|
|
2071
|
+
const acct = this.accountParam(node.arguments[0], "the account");
|
|
2072
|
+
if (acct.kind.kind !== "info")
|
|
2073
|
+
this.fail(node.arguments[0], "pass a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter");
|
|
2074
|
+
if (mut && !isWritable(acct.kind) && !this.nativeAccountWrites())
|
|
2075
|
+
this.fail(node.arguments[0], `${acct.name} must be Mut<AccountInfo> to load it with ${fn} (or declare const NATIVE_ACCOUNT_WRITES = true to leave writability to the runtime, as a native program does)`);
|
|
2076
|
+
if (!this.ix)
|
|
2077
|
+
this.fail(node, `load ${acct.name} in the instruction and pass the struct on`);
|
|
2078
|
+
return { h: `a_${acct.name}`, param: this.ix.accounts.indexOf(acct) };
|
|
2079
|
+
}
|
|
2080
|
+
/**
|
|
2081
|
+
* A writable view's checks: the account is writable and loaded mutably once in the instruction (2040).
|
|
2082
|
+
* NATIVE_ACCOUNT_WRITES: no writability check and no claim. The view writes in place; the runtime refuses the
|
|
2083
|
+
* instruction if a read-only account's data changed, and two views of one account share its bytes (the loader
|
|
2084
|
+
* gives a duplicate the same record), as two AccountInfos of one account share one buffer in Rust.
|
|
2085
|
+
*/
|
|
2086
|
+
claimRawMut(node, h, param) {
|
|
2087
|
+
if (this.nativeAccountWrites())
|
|
2088
|
+
return;
|
|
2089
|
+
this.line(`TS_TRY(ts_check_writable(${h}));`);
|
|
2090
|
+
const slot = this.claimSlots.get(node);
|
|
2091
|
+
if (slot)
|
|
2092
|
+
this.line(param === undefined ? `TS_TRY(ts_claim_mut_rec(params, ${h}, &${slot}, params->ka_num));` : `TS_TRY(ts_claim_mut_at_rec(params, ${param}, &${slot}));`);
|
|
2093
|
+
else
|
|
2094
|
+
this.line(param === undefined ? `TS_TRY(ts_claim_mut(params, ${h}));` : `TS_TRY(ts_claim_mut_at(params, ${param}));`);
|
|
2095
|
+
}
|
|
2096
|
+
/**
|
|
2097
|
+
* `const v = loadBorsh<T>(acct)`: the account's data from byte 0 decoded as Borsh into a local `T` (a copy), as
|
|
2098
|
+
* `try_from_slice_unchecked` reads it: no owner check, no discriminator, trailing bytes ignored; bytes that are not
|
|
2099
|
+
* a valid `T` (too short, an Option tag or bool not 0/1, an enum tag out of range) fail with BorshIoError.
|
|
2100
|
+
*/
|
|
2101
|
+
loadBorsh(node, c, declared) {
|
|
2102
|
+
const s = this.borshNativeStruct(node, node.typeArguments?.[0], declared, "loadBorsh");
|
|
2103
|
+
if (node.arguments.length !== 1)
|
|
2104
|
+
this.fail(node, "loadBorsh<T>(account) takes one remaining account or AccountInfo parameter");
|
|
2105
|
+
const h = this.borshAccount(node.arguments[0], "loadBorsh", false);
|
|
2106
|
+
this.line(`TSS_${s.name} ${c}__v;`);
|
|
2107
|
+
this.line(`if (ts_bdec_${s.name}(${h}->data, ${h}->data_len, &${c}__v, NULL)) ${this.programErrorFail("BorshIoError", node)};`);
|
|
2108
|
+
this.line(`TSS_${s.name} *${c} = &${c}__v;`);
|
|
2109
|
+
return s;
|
|
2110
|
+
}
|
|
2111
|
+
/**
|
|
2112
|
+
* `storeBorsh(acct, value)`: `value` encoded as Borsh into the account's data from byte 0, as Rust's
|
|
2113
|
+
* `value.serialize(&mut &mut data[..])` writes it: only the encoded bytes (the rest of the account is left as it
|
|
2114
|
+
* was), BorshIoError when they do not fit. The account must be writable.
|
|
2115
|
+
*/
|
|
2116
|
+
storeBorsh(node) {
|
|
2117
|
+
if (node.arguments.length !== 2)
|
|
2118
|
+
this.fail(node, "storeBorsh(account, value) takes the account and the struct value to write");
|
|
2119
|
+
const h = this.borshAccount(node.arguments[0], "storeBorsh", true);
|
|
2120
|
+
const valueNode = node.arguments[1];
|
|
2121
|
+
const targ = node.typeArguments?.[0];
|
|
2122
|
+
let ptr;
|
|
2123
|
+
let s;
|
|
2124
|
+
const inner = ts.isParenthesizedExpression(valueNode) ? valueNode.expression : valueNode;
|
|
2125
|
+
if (ts.isObjectLiteralExpression(inner)) {
|
|
2126
|
+
if (!targ)
|
|
2127
|
+
this.fail(valueNode, "storeBorsh needs the struct type for an object literal: storeBorsh<MyStruct>(account, { … })");
|
|
2128
|
+
s = this.borshNativeStruct(node, targ, undefined, "storeBorsh");
|
|
2129
|
+
const t = this.tmp("bval");
|
|
2130
|
+
this.line(`TSS_${s.name} ${t};`);
|
|
2131
|
+
this.writeAggregate({ lv: t, type: { kind: "struct", name: s.name }, writable: true }, inner, true);
|
|
2132
|
+
ptr = `(&${t})`;
|
|
2133
|
+
}
|
|
2134
|
+
else {
|
|
2135
|
+
const place = this.structPlace(valueNode);
|
|
2136
|
+
if (!place)
|
|
2137
|
+
this.fail(valueNode, "storeBorsh writes a struct value: a local (const pool = loadBorsh<Pool>(acct)), a struct field or an object literal");
|
|
2138
|
+
const want = targ ? this.borshNativeStruct(node, targ, undefined, "storeBorsh") : undefined;
|
|
2139
|
+
if (want && want.name !== place.struct)
|
|
2140
|
+
this.fail(valueNode, `expected a ${want.name}, got a ${place.struct}`);
|
|
2141
|
+
s = this.borshNativeStruct(node, undefined, this.model.structs.get(place.struct), "storeBorsh");
|
|
2142
|
+
ptr = place.ptr;
|
|
2143
|
+
}
|
|
2144
|
+
this.line(`if (ts_benc_${s.name}(${ptr}, ${h}->data, ${h}->data_len, NULL)) ${this.programErrorFail("BorshIoError", node)};`);
|
|
2145
|
+
return undefined;
|
|
2146
|
+
}
|
|
2147
|
+
/** The struct loadBorsh / storeBorsh decodes or encodes: from the type argument, else the declared type. */
|
|
2148
|
+
borshNativeStruct(node, targ, declared, fn) {
|
|
2149
|
+
let s = declared;
|
|
2150
|
+
if (targ) {
|
|
2151
|
+
const named = ts.isTypeReferenceNode(targ) && ts.isIdentifier(targ.typeName) ? this.model.structs.get(targ.typeName.text) : undefined;
|
|
2152
|
+
if (!named)
|
|
2153
|
+
this.fail(targ, `${fn} needs a struct type: ${fn === "loadBorsh" ? "loadBorsh<MyStruct>(account)" : "storeBorsh<MyStruct>(account, value)"}`);
|
|
2154
|
+
if (declared && declared.name !== named.name)
|
|
2155
|
+
this.fail(node, `loadBorsh<${named.name}> is bound to a ${declared.name}`);
|
|
2156
|
+
s = named;
|
|
2157
|
+
}
|
|
2158
|
+
if (!s)
|
|
2159
|
+
this.fail(node, `${fn} needs a struct type: ${fn === "loadBorsh" ? "const pool = loadBorsh<MyStruct>(account)" : "storeBorsh<MyStruct>(account, value)"}`);
|
|
2160
|
+
const why = borshNativeStructUnsupported(s, this.model);
|
|
2161
|
+
if (why)
|
|
2162
|
+
this.fail(targ ?? node, `${fn} cannot take ${s.name}: ${why}`);
|
|
2163
|
+
this.model.borshNative.add(s.name);
|
|
2164
|
+
return s;
|
|
2165
|
+
}
|
|
2166
|
+
/** The account loadBorsh reads or storeBorsh writes (writable: checked at run time, or Mut<AccountInfo>). */
|
|
2167
|
+
borshAccount(node, fn, write) {
|
|
2168
|
+
const h = this.handle(node);
|
|
2169
|
+
// NATIVE_ACCOUNT_WRITES: written as Rust's serialize writes it, the runtime judging writability afterwards.
|
|
2170
|
+
const native = this.nativeAccountWrites();
|
|
2171
|
+
// Without the flag, a write also needs the account passed once: given again (as another declared account or a
|
|
2172
|
+
// remaining one), what the program reads through the other would not be what it wrote here.
|
|
2173
|
+
if (h) {
|
|
2174
|
+
if (write && !native) {
|
|
2175
|
+
this.line(`TS_TRY(ts_check_writable(${h}));`);
|
|
2176
|
+
this.line(`TS_TRY(ts_check_unaliased(params, ${h}));`);
|
|
2177
|
+
}
|
|
2178
|
+
return h;
|
|
2179
|
+
}
|
|
2180
|
+
const acct = this.accountParam(node, `${fn}'s account`);
|
|
2181
|
+
if (acct.kind.kind !== "info")
|
|
2182
|
+
this.fail(node, `${fn} takes a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter`);
|
|
2183
|
+
if (write && !isWritable(acct.kind) && !native)
|
|
2184
|
+
this.fail(node, `${acct.name} must be Mut<AccountInfo> to write it with storeBorsh (or declare const NATIVE_ACCOUNT_WRITES = true to leave writability to the runtime, as a native program does)`);
|
|
2185
|
+
if (write && !native)
|
|
2186
|
+
this.line(`TS_TRY(ts_check_unaliased(params, a_${acct.name}));`);
|
|
2187
|
+
return `a_${acct.name}`;
|
|
2188
|
+
}
|
|
2189
|
+
/**
|
|
2190
|
+
* An account `closeRaw` / `assignOwner` writes in place: a remaining account (a helper's RemainingAccount, a ternary
|
|
2191
|
+
* between them) or an AccountInfo parameter. Without NATIVE_ACCOUNT_WRITES it is checked as the other writes to
|
|
2192
|
+
* accounts the compiler cannot see are: writable (3006; a parameter must be Mut<AccountInfo>), passed once (2040), and
|
|
2193
|
+
* for `owned` this program's (3007). With the flag nothing is checked: the runtime judges the result, as it judges a
|
|
2194
|
+
* native program's.
|
|
2195
|
+
*/
|
|
2196
|
+
inPlaceAccount(node, what, owned) {
|
|
2197
|
+
const native = this.nativeAccountWrites();
|
|
2198
|
+
let h = this.handle(node);
|
|
1463
2199
|
if (!h) {
|
|
1464
|
-
const acct = this.accountParam(node
|
|
2200
|
+
const acct = this.accountParam(node, what);
|
|
1465
2201
|
if (acct.kind.kind !== "info")
|
|
1466
|
-
this.fail(node
|
|
1467
|
-
if (
|
|
1468
|
-
this.fail(node
|
|
1469
|
-
if (!this.ix)
|
|
1470
|
-
this.fail(node, `load ${acct.name} in the instruction and pass the struct on`);
|
|
2202
|
+
this.fail(node, `${what} is a remaining account (remainingAccounts().get(i)) or an AccountInfo parameter`);
|
|
2203
|
+
if (!isWritable(acct.kind) && !native)
|
|
2204
|
+
this.fail(node, `${acct.name} must be Mut<AccountInfo> to change it in place (or declare const NATIVE_ACCOUNT_WRITES = true to leave writability to the runtime, as a native program does)`);
|
|
1471
2205
|
h = `a_${acct.name}`;
|
|
1472
|
-
param = this.ix.accounts.indexOf(acct);
|
|
1473
2206
|
}
|
|
1474
|
-
|
|
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) {
|
|
2207
|
+
else if (!native)
|
|
1477
2208
|
this.line(`TS_TRY(ts_check_writable(${h}));`);
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
2209
|
+
if (native)
|
|
2210
|
+
return h;
|
|
2211
|
+
this.line(`TS_TRY(ts_check_unaliased(params, ${h}));`);
|
|
2212
|
+
if (owned)
|
|
2213
|
+
this.line(`if (!ts_key_eq(&${h}->owner, params->program_id)) TS_FAIL(TS_ERR_WRONG_OWNER, "TypeSOL: account not owned by this program");`);
|
|
2214
|
+
return h;
|
|
2215
|
+
}
|
|
2216
|
+
/** `TS_FAIL` with a built-in ProgramError (no custom code), logged as `require(…, ProgramError.X)` logs it. */
|
|
2217
|
+
programErrorFail(name, node) {
|
|
2218
|
+
const idx = PROGRAM_ERRORS.indexOf(name);
|
|
2219
|
+
// `const PROGRAM_ERROR_LOG_PREFIX = "Program error: "`: the log line a native entrypoint writes for it.
|
|
2220
|
+
const pre = this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value;
|
|
2221
|
+
const text = typeof pre === "string" ? `${pre}${name}` : `Error: ${name} (${this.location(node)})`;
|
|
2222
|
+
return this.programFail(`((uint64_t)${idx + 2}) << 32`, text);
|
|
2223
|
+
}
|
|
2224
|
+
/** A failure with a built-in ProgramError's code: logged with `text`, or nothing under `PROGRAM_ERROR_LOG_PREFIX = null`. */
|
|
2225
|
+
programFail(code, text) {
|
|
2226
|
+
if (this.model.constants.get("PROGRAM_ERROR_LOG_PREFIX")?.value === null)
|
|
2227
|
+
return `return ts_fail_quiet(${code})`;
|
|
2228
|
+
return `TS_FAIL(${code}, ${cString(text)})`;
|
|
2229
|
+
}
|
|
2230
|
+
/** `const ERROR_LOG_PREFIX = null`: the program's own errors (and codes returned by its helpers) log nothing. */
|
|
2231
|
+
quietErrors() {
|
|
2232
|
+
return this.model.constants.get("ERROR_LOG_PREFIX")?.value === null;
|
|
1487
2233
|
}
|
|
1488
2234
|
/** `loadAccount<T>(acct)` / `loadAccountMut<T>(acct)`: checked view of a program account. */
|
|
1489
2235
|
loadAccount(node, mut) {
|
|
@@ -1503,6 +2249,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1503
2249
|
this.fail(node, `${s.name}'s discriminator is shorter than 8 bytes: take it as Owner<Account<${s.name}>, "…">`);
|
|
1504
2250
|
if (s.layout === "borsh")
|
|
1505
2251
|
this.fail(node, `${s.name} is @layout borsh: declare it as an instruction parameter (remaining accounts are read in place)`);
|
|
2252
|
+
if (s.bigVec)
|
|
2253
|
+
this.fail(node, `${s.name} ends in a BigVec, a native program's list (no discriminator): read it with loadRaw / loadRawMut`);
|
|
1506
2254
|
if (node.arguments.length !== 1)
|
|
1507
2255
|
this.fail(node, "loadAccount<T>(account) takes one remaining account or AccountInfo parameter");
|
|
1508
2256
|
let h = this.handle(node.arguments[0]);
|
|
@@ -1598,6 +2346,39 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1598
2346
|
visit(body);
|
|
1599
2347
|
return found;
|
|
1600
2348
|
}
|
|
2349
|
+
/** Whether a helper's body (or a helper it calls) closes or resizes an account: closeRaw / resizeAccount. */
|
|
2350
|
+
helperResizes(body) {
|
|
2351
|
+
return this.helperCalls(body, ["closeRaw", "resizeAccount"]);
|
|
2352
|
+
}
|
|
2353
|
+
/** Whether a helper's body (or a helper it calls) makes a writable tree view, which may change a tree's structure. */
|
|
2354
|
+
helperMakesMutTree(body) {
|
|
2355
|
+
return this.helperCalls(body, ["rbTreeMutAt"]);
|
|
2356
|
+
}
|
|
2357
|
+
/** Whether a helper's body (or a helper it calls) calls one of these built-ins. */
|
|
2358
|
+
helperCalls(body, builtins, seen = new Set()) {
|
|
2359
|
+
if (seen.has(body))
|
|
2360
|
+
return false;
|
|
2361
|
+
seen.add(body);
|
|
2362
|
+
let found = false;
|
|
2363
|
+
const visit = (n) => {
|
|
2364
|
+
if (found)
|
|
2365
|
+
return;
|
|
2366
|
+
if (ts.isCallExpression(n) && ts.isIdentifier(n.expression)) {
|
|
2367
|
+
const fn = this.exportName(n.expression);
|
|
2368
|
+
if (fn && builtins.includes(fn))
|
|
2369
|
+
found = true;
|
|
2370
|
+
else {
|
|
2371
|
+
const name = calleeName(n.expression, this.model.helperDecls, this.checker);
|
|
2372
|
+
const callee = name ? (this.model.generics.get(name)?.node ?? this.model.helpers.get(name)?.node) : undefined;
|
|
2373
|
+
if (callee && this.helperCalls(callee, builtins, seen))
|
|
2374
|
+
found = true;
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
2377
|
+
ts.forEachChild(n, visit);
|
|
2378
|
+
};
|
|
2379
|
+
visit(body);
|
|
2380
|
+
return found;
|
|
2381
|
+
}
|
|
1601
2382
|
/**
|
|
1602
2383
|
* A helper given a closure (a function that reads the caller's variables) for a function parameter: a closure only
|
|
1603
2384
|
* runs where it is declared, so the helper is expanded here, like a closure, with the closure bound to the
|
|
@@ -1607,6 +2388,9 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1607
2388
|
const g = this.givenClosure(node);
|
|
1608
2389
|
if (!g)
|
|
1609
2390
|
return undefined;
|
|
2391
|
+
const tagged = [g.node, ...(ts.isVariableDeclaration(g.node.parent) ? [g.node.parent] : [])];
|
|
2392
|
+
if (tagged.some((n) => ts.getJSDocTags(n).some((t) => t.tagName.text === "noinline")))
|
|
2393
|
+
this.fail(node, `${g.display}() is @noinline, but given a closure it is expanded where it is called: pass a named function`);
|
|
1610
2394
|
// Type parameters: bound from the call (as an instance would be) while the body is expanded.
|
|
1611
2395
|
const saved = this.scope;
|
|
1612
2396
|
if (g.typeParams.length) {
|
|
@@ -1719,6 +2503,12 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1719
2503
|
// A helper that takes accounts may change account data, so account text it gets is copied first.
|
|
1720
2504
|
// A RemainingAccount(s) parameter counts: the helper may load and write a struct through it.
|
|
1721
2505
|
const takesAccounts = h.params.some((p) => p.account || p.type.kind === "account" || p.type.kind === "remaining");
|
|
2506
|
+
// A helper that closes or resizes an account it is given ends the caller's views of it (any account it may be).
|
|
2507
|
+
if (takesAccounts && this.helperResizes(h.node))
|
|
2508
|
+
this.assertNoViewAfter("?", node, `${h.display}() (it may close or resize an account it is given)`);
|
|
2509
|
+
// Nor may a helper change a tree of an account a for … of is walking.
|
|
2510
|
+
if (takesAccounts && this.iteratingTrees.size && this.helperMakesMutTree(h.node))
|
|
2511
|
+
this.fail(node, `${h.display}() takes accounts and makes an rbTreeMutAt view, so it may change the tree a for … of is walking (${[...this.iteratingTrees.values()].map((w) => w.name).join(", ")}): collect what it needs in the loop, then call it after`);
|
|
1722
2512
|
const values = [];
|
|
1723
2513
|
const pieces = [];
|
|
1724
2514
|
h.params.forEach((p, i) => {
|
|
@@ -1734,6 +2524,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1734
2524
|
values.push(takesAccounts ? this.ownedString(raw) : raw);
|
|
1735
2525
|
}
|
|
1736
2526
|
});
|
|
2527
|
+
if (h.params.some((p) => p.inout))
|
|
2528
|
+
this.checkInoutCall(node, h, argNodes, pieces.map((x) => (typeof x === "string" ? x : undefined)));
|
|
1737
2529
|
// A helper that takes a writable struct account may replace anything stored in it (see assertNotAliased).
|
|
1738
2530
|
for (const [i, p] of h.params.entries())
|
|
1739
2531
|
if (p.account && p.account.kind === "account" && p.account.mut && ts.isIdentifier(argNodes[i]))
|
|
@@ -1773,6 +2565,14 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1773
2565
|
this.fail(n, `${h.name}() takes ${p.name} as Mut<${l.loaded.struct}>: load it with loadAccountMut`);
|
|
1774
2566
|
return l.loaded.handle;
|
|
1775
2567
|
}
|
|
2568
|
+
// A program or sysvar programAt / sysvarAt checked: as that kind of account.
|
|
2569
|
+
const at = this.programAtValue(n);
|
|
2570
|
+
if (at) {
|
|
2571
|
+
const why = accountMismatch(at.kind, p.account);
|
|
2572
|
+
if (why)
|
|
2573
|
+
this.fail(n, `${h.name}() takes ${p.name} as ${why}`);
|
|
2574
|
+
return at.c;
|
|
2575
|
+
}
|
|
1776
2576
|
const acct = this.accountParam(n, `${h.name}()'s ${p.name}`);
|
|
1777
2577
|
const why = accountMismatch(acct.kind, p.account);
|
|
1778
2578
|
if (why)
|
|
@@ -1784,6 +2584,8 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1784
2584
|
return `a_${acct.name}, entry_${acct.name}`;
|
|
1785
2585
|
return `a_${acct.name}`;
|
|
1786
2586
|
}
|
|
2587
|
+
if (p.inout)
|
|
2588
|
+
return this.inoutArg(h, p, n);
|
|
1787
2589
|
switch (p.type.kind) {
|
|
1788
2590
|
case "signerSeeds": {
|
|
1789
2591
|
const seeds = this.signerSeedsArg(n);
|
|
@@ -1792,6 +2594,9 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1792
2594
|
case "structRef":
|
|
1793
2595
|
case "arrayArg": {
|
|
1794
2596
|
const want = p.type.kind === "structRef" ? { kind: "struct", name: p.type.struct } : p.type.array;
|
|
2597
|
+
const built = this.literalArg(n, want);
|
|
2598
|
+
if (built)
|
|
2599
|
+
return built;
|
|
1795
2600
|
let r = this.ref(n);
|
|
1796
2601
|
// A narrowed Option<Struct> / Option<FixedArray> place (`c.opt !== null` before it): its value.
|
|
1797
2602
|
if (r && r.type.kind === "option" && sameType(r.type.inner, want))
|
|
@@ -1801,23 +2606,235 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1801
2606
|
return this.snapshotPlace(r.lv, want, h, n);
|
|
1802
2607
|
}
|
|
1803
2608
|
case "dataEnumArg": {
|
|
2609
|
+
const built = this.literalArg(n, { kind: "dataEnum", name: p.type.name });
|
|
2610
|
+
if (built)
|
|
2611
|
+
return built;
|
|
1804
2612
|
const r = this.ref(n);
|
|
1805
2613
|
if (!r || r.type.kind !== "dataEnum" || r.type.name !== p.type.name)
|
|
1806
2614
|
this.fail(n, `expected a ${p.type.name}`);
|
|
1807
2615
|
return this.snapshotPlace(r.lv, { kind: "dataEnum", name: p.type.name }, h, n);
|
|
1808
2616
|
}
|
|
1809
2617
|
case "vecArg": {
|
|
2618
|
+
// A slice of a Vec argument or the instruction data: a view of its own, passed like the list.
|
|
2619
|
+
if (!ts.isIdentifier(n) && this.isVecArgView(n)) {
|
|
2620
|
+
const v = this.vecArgView(n);
|
|
2621
|
+
if (!sameType(v.type, p.type))
|
|
2622
|
+
this.fail(n, `expected a ${typeName(p.type)}`);
|
|
2623
|
+
return v.c;
|
|
2624
|
+
}
|
|
1810
2625
|
const l = ts.isIdentifier(n) ? this.lookup(n.text) : undefined;
|
|
1811
2626
|
// An Option<Vec<T>> argument passes as its list once checked against null (TypeScript narrows it).
|
|
1812
2627
|
const t = l?.type.kind === "vecArg" && l.type.optional ? { ...l.type, optional: undefined } : l?.type;
|
|
1813
|
-
if (
|
|
1814
|
-
|
|
1815
|
-
|
|
2628
|
+
if (l && t && sameType(t, p.type))
|
|
2629
|
+
return l.c;
|
|
2630
|
+
// A list of the caller's (a local FixedVec or FixedArray, a field of a local struct, or one in account data): a
|
|
2631
|
+
// read-only view of its elements, passed by pointer.
|
|
2632
|
+
const view = this.listViewArg(n, p.type, h);
|
|
2633
|
+
if (view)
|
|
2634
|
+
return view;
|
|
2635
|
+
const what = p.type.elem.kind === "int" && p.type.elem.name === "u8" && p.type.cap === undefined ? "list of u8" : `list of ${typeName(p.type.elem)}`;
|
|
2636
|
+
this.fail(n, `expected a ${what}: an instruction argument, the instruction data or a slice of it, or a FixedVec / FixedArray of ${typeName(p.type.elem)} (a local, a field)`);
|
|
1816
2637
|
}
|
|
1817
2638
|
default:
|
|
1818
2639
|
return this.expect(this.expr(n, p.type), p.type, n);
|
|
1819
2640
|
}
|
|
1820
2641
|
}
|
|
2642
|
+
/**
|
|
2643
|
+
* An `Inout<T>` argument: a pointer to the caller's place itself (never a copy), which must be writable. A literal
|
|
2644
|
+
* (`f({ … })`, `fixedArray(…)`) is built in a local of its own, as JS passes a fresh object; a ternary must pick
|
|
2645
|
+
* between two places (a literal branch would be a copy the helper's writes never reach).
|
|
2646
|
+
*/
|
|
2647
|
+
inoutArg(h, p, n) {
|
|
2648
|
+
const want = p.inout;
|
|
2649
|
+
const what = `Inout<${typeName(want)}>`;
|
|
2650
|
+
let bare = n;
|
|
2651
|
+
while (ts.isParenthesizedExpression(bare))
|
|
2652
|
+
bare = bare.expression;
|
|
2653
|
+
if (want.kind !== "vec" && (ts.isObjectLiteralExpression(bare) || (ts.isCallExpression(bare) && this.exportName(bare.expression) === "fixedArray")))
|
|
2654
|
+
return this.literalArg(n, want);
|
|
2655
|
+
if (ts.isConditionalExpression(bare)) {
|
|
2656
|
+
if (want.kind !== "struct")
|
|
2657
|
+
this.fail(n, `${h.display}() takes ${p.name} as ${what}: pass the list itself, not a choice between lists`);
|
|
2658
|
+
const place = this.structPlace(bare);
|
|
2659
|
+
if (!place)
|
|
2660
|
+
this.fail(n, `${h.display}() takes ${p.name} as ${what}: both branches must be ${want.name} places (a local, a field, a list element), not values`);
|
|
2661
|
+
if (place.struct !== want.name)
|
|
2662
|
+
this.fail(n, `${h.display}() takes ${p.name} as ${what}; this is a ${place.struct}`);
|
|
2663
|
+
if (!place.writable)
|
|
2664
|
+
this.fail(n, `${h.display}() changes ${p.name} (Inout), and a branch of this choice is read-only`);
|
|
2665
|
+
return place.ptr;
|
|
2666
|
+
}
|
|
2667
|
+
let r = this.ref(n);
|
|
2668
|
+
// A narrowed Option<Struct> / Option<FixedArray> place (`c.opt !== null` before it): the value inside it.
|
|
2669
|
+
if (r && r.type.kind === "option" && sameType(r.type.inner, want))
|
|
2670
|
+
r = this.someValue(r);
|
|
2671
|
+
if (!r || !sameType(r.type, want)) {
|
|
2672
|
+
const l = ts.isIdentifier(n) ? this.lookup(n.text) : undefined;
|
|
2673
|
+
if (l?.type.kind === "vecArg" || l?.type.kind === "optionArg")
|
|
2674
|
+
this.fail(n, `${h.display}() changes ${p.name} (Inout): instruction arguments are read-only; copy the value into a local first`);
|
|
2675
|
+
this.fail(n, `${h.display}() takes ${p.name} as ${what}: pass a ${typeName(want)} place of yours (a local, a field, a list element) for it to change`);
|
|
2676
|
+
}
|
|
2677
|
+
if (!r.writable)
|
|
2678
|
+
this.fail(n, `${h.display}() changes ${p.name} (Inout): ${this.readOnly(r)}`);
|
|
2679
|
+
if (r.vec?.slice)
|
|
2680
|
+
this.fail(n, `${h.display}() takes ${p.name} as ${what}: pass the list, not a slice of it`);
|
|
2681
|
+
return `(&${r.lv})`;
|
|
2682
|
+
}
|
|
2683
|
+
/**
|
|
2684
|
+
* The rules of a call with `Inout<T>` arguments, so the helper's pointer is the only way to the place while it runs
|
|
2685
|
+
* (Rust's one `&mut` at a time) and stays valid: no other argument may share storage with an Inout one (two places,
|
|
2686
|
+
* one inside the other, the same list's elements whatever their indexes, an account and a place in it); a place in
|
|
2687
|
+
* a list whose elements can move is refused when the call may move them; a reference into the place read after the
|
|
2688
|
+
* call is refused (the helper may replace what it points at). Places whose roots differ but may be the same bytes at
|
|
2689
|
+
* run time (two `Dup<…>` accounts, two loadRawMut views under NATIVE_ACCOUNT_WRITES, a helper's account parameters)
|
|
2690
|
+
* are compared at run time (2040).
|
|
2691
|
+
*/
|
|
2692
|
+
checkInoutCall(node, h, argNodes, passed) {
|
|
2693
|
+
const show = (e) => {
|
|
2694
|
+
try {
|
|
2695
|
+
return e.getText();
|
|
2696
|
+
}
|
|
2697
|
+
catch {
|
|
2698
|
+
return "this argument";
|
|
2699
|
+
}
|
|
2700
|
+
};
|
|
2701
|
+
const fresh = (e) => {
|
|
2702
|
+
while (ts.isParenthesizedExpression(e))
|
|
2703
|
+
e = e.expression;
|
|
2704
|
+
// A literal, or a struct a helper returns: a value of its own that nothing else reaches.
|
|
2705
|
+
if (ts.isObjectLiteralExpression(e))
|
|
2706
|
+
return true;
|
|
2707
|
+
if (!ts.isCallExpression(e))
|
|
2708
|
+
return false;
|
|
2709
|
+
return this.exportName(e.expression) === "fixedArray" || this.helperOf(e)?.returns?.kind === "struct";
|
|
2710
|
+
};
|
|
2711
|
+
// Each argument passed by reference (Inout, read-only structs and lists, accounts, loaded structs) and its storage.
|
|
2712
|
+
const refs = [];
|
|
2713
|
+
h.params.forEach((p, i) => {
|
|
2714
|
+
const n = argNodes[i];
|
|
2715
|
+
if (p.inout) {
|
|
2716
|
+
const paths = this.pathsOf(n);
|
|
2717
|
+
if (!paths && !fresh(n))
|
|
2718
|
+
this.fail(n, `${h.display}() changes ${p.name} (Inout): pass a local, a field path or a list element (bind anything else to a const first)`);
|
|
2719
|
+
if (paths)
|
|
2720
|
+
refs.push({ i, inout: true, paths });
|
|
2721
|
+
return;
|
|
2722
|
+
}
|
|
2723
|
+
const byRef = p.account || p.type.kind === "structRef" || p.type.kind === "arrayArg" || p.type.kind === "dataEnumArg" || p.type.kind === "vecArg";
|
|
2724
|
+
const paths = byRef ? this.pathsOf(n) : undefined;
|
|
2725
|
+
if (paths)
|
|
2726
|
+
refs.push({ i, inout: false, paths });
|
|
2727
|
+
});
|
|
2728
|
+
for (let a = 0; a < refs.length; a++)
|
|
2729
|
+
for (let b = a + 1; b < refs.length; b++) {
|
|
2730
|
+
const x = refs[a];
|
|
2731
|
+
const y = refs[b];
|
|
2732
|
+
if ((!x.inout && !y.inout) || !this.placesOverlap(x.paths, y.paths))
|
|
2733
|
+
continue;
|
|
2734
|
+
const [w, o] = x.inout ? [x, y] : [y, x];
|
|
2735
|
+
const wn = show(argNodes[w.i]);
|
|
2736
|
+
const on = show(argNodes[o.i]);
|
|
2737
|
+
const op = h.params[o.i];
|
|
2738
|
+
const why = `${wn} and ${on} share storage, and ${h.display}() changes ${h.params[w.i].name} (Inout) in place: while it runs, its parameter must be the only way to that place`;
|
|
2739
|
+
if (op.inout)
|
|
2740
|
+
this.fail(argNodes[Math.max(w.i, o.i)], `${why}. Two elements of one list count as one place whatever their indexes; pass what holds both, or copy one into a local and store it back after the call`);
|
|
2741
|
+
if (op.account)
|
|
2742
|
+
this.fail(argNodes[o.i], `${why}. Pass the account alone and reach ${wn} through it in the helper, or pass only ${wn}`);
|
|
2743
|
+
this.fail(argNodes[o.i], `${why}. Copy ${on} into a local first (const copy: T = ${on}) and pass the copy`);
|
|
2744
|
+
}
|
|
2745
|
+
for (const r of refs) {
|
|
2746
|
+
if (!r.inout)
|
|
2747
|
+
continue;
|
|
2748
|
+
const n = argNodes[r.i];
|
|
2749
|
+
if (this.throughMovableList(n) && this.mayResizeVecs(node))
|
|
2750
|
+
this.fail(n, `${show(n)} is in a list whose elements move when it grows, shrinks or is filtered (a Vec or BigVec), and ${h.display}() may do that (it takes writable or remaining accounts) while it holds ${show(n)}; copy the element into a local (const e: T = …), pass the local and store it back after the call`);
|
|
2751
|
+
this.assertNothingInside(r.paths, node, h.display, show(n));
|
|
2752
|
+
}
|
|
2753
|
+
// Different roots that may still be the same bytes: compared at run time.
|
|
2754
|
+
const root = (p) => p.split(/[.[]/)[0];
|
|
2755
|
+
const local = (c) => {
|
|
2756
|
+
for (const s of [...this.scopes, this.args])
|
|
2757
|
+
for (const l of s.values())
|
|
2758
|
+
if (l.c === c)
|
|
2759
|
+
return l;
|
|
2760
|
+
return undefined;
|
|
2761
|
+
};
|
|
2762
|
+
const mayShare = (a, b) => {
|
|
2763
|
+
if (a === b)
|
|
2764
|
+
return false;
|
|
2765
|
+
const acct = (r) => (r.startsWith("@") ? undefined : this.accounts.get(r));
|
|
2766
|
+
const view = (r) => (r.startsWith("@") && local(r.slice(1))?.view ? r : undefined);
|
|
2767
|
+
const [aa, ba] = [acct(a), acct(b)];
|
|
2768
|
+
if (aa && ba)
|
|
2769
|
+
return aa.index === -1 || ba.index === -1 || !!aa.constraints.dup || !!ba.constraints.dup;
|
|
2770
|
+
if (!this.nativeAccountWrites())
|
|
2771
|
+
return false;
|
|
2772
|
+
return !!((aa || view(a)) && (ba || view(b)));
|
|
2773
|
+
};
|
|
2774
|
+
// A read-only argument beside an Inout one may also be the same bytes: an account the runtime does not keep apart
|
|
2775
|
+
// from a writable one (a read-only parameter is not checked against the writable ones).
|
|
2776
|
+
const readOnlyAccount = (r) => {
|
|
2777
|
+
const a = r.startsWith("@") ? undefined : this.accounts.get(r);
|
|
2778
|
+
return !!a && !isWritable(a.kind);
|
|
2779
|
+
};
|
|
2780
|
+
const mayShareRead = (a, b) => mayShare(a, b) || (a !== b && !!this.accounts.get(a) && !!this.accounts.get(b) && (readOnlyAccount(a) || readOnlyAccount(b)));
|
|
2781
|
+
// The bytes an argument is passed as, when they are the caller's own: a place's pointer, an account's data, a list
|
|
2782
|
+
// view's elements. A copy taken for the call (a helper that takes accounts gets one) shares nothing.
|
|
2783
|
+
const bytes = (r) => {
|
|
2784
|
+
const v = passed[r.i];
|
|
2785
|
+
if (!v)
|
|
2786
|
+
return undefined;
|
|
2787
|
+
const p = h.params[r.i];
|
|
2788
|
+
if (r.inout || (v.startsWith("(&") && (p.type.kind === "structRef" || p.type.kind === "arrayArg" || p.type.kind === "dataEnumArg")))
|
|
2789
|
+
return { lo: `(uint8_t *)${v}`, hi: `(uint8_t *)${v} + sizeof(*${v})` };
|
|
2790
|
+
if (p.account && /^\w+$/.test(v))
|
|
2791
|
+
return { lo: `${v}->data`, hi: `${v}->data + ${v}->data_len` };
|
|
2792
|
+
if (p.type.kind === "vecArg" && /^\w+$/.test(v) && !h.params.some((q) => q.account || q.type.kind === "account" || q.type.kind === "remaining"))
|
|
2793
|
+
return { lo: `${v}.ptr`, hi: `${v}.ptr + (uint64_t)${v}.len * ${this.fieldBytes(p.type.elem)}` };
|
|
2794
|
+
return undefined;
|
|
2795
|
+
};
|
|
2796
|
+
for (let a = 0; a < refs.length; a++)
|
|
2797
|
+
for (let b = a + 1; b < refs.length; b++) {
|
|
2798
|
+
const x = refs[a];
|
|
2799
|
+
const y = refs[b];
|
|
2800
|
+
if (!x.inout && !y.inout)
|
|
2801
|
+
continue;
|
|
2802
|
+
const share = x.inout && y.inout ? mayShare : mayShareRead;
|
|
2803
|
+
if (!x.paths.some((p) => y.paths.some((q) => share(root(p), root(q)))))
|
|
2804
|
+
continue;
|
|
2805
|
+
const [bx, by] = [bytes(x), bytes(y)];
|
|
2806
|
+
if (!bx || !by)
|
|
2807
|
+
continue;
|
|
2808
|
+
this.line(`if (${bx.lo} < ${by.hi} && ${by.lo} < ${bx.hi}) TS_FAIL(TS_ERR_DUPLICATE_MUT, ${cString(`TypeSOL: ${h.display}() was given ${show(argNodes[x.i])} and ${show(argNodes[y.i])}, which share storage`)});`);
|
|
2809
|
+
}
|
|
2810
|
+
}
|
|
2811
|
+
/**
|
|
2812
|
+
* A struct, array or data-enum helper argument written as a literal (`f({ a: 1n, b: { c } })`, `g([1n, 2n])`, or a
|
|
2813
|
+
* ternary with a literal branch): built in a local of its own, as `const x: T = { … }; f(x)` would, and passed by
|
|
2814
|
+
* pointer (the helper cannot change it, and nothing else sees it). Undefined for anything else.
|
|
2815
|
+
*/
|
|
2816
|
+
literalArg(n, want) {
|
|
2817
|
+
const literal = (e) => {
|
|
2818
|
+
while (ts.isParenthesizedExpression(e))
|
|
2819
|
+
e = e.expression;
|
|
2820
|
+
if (ts.isConditionalExpression(e))
|
|
2821
|
+
return literal(e.whenTrue) || literal(e.whenFalse);
|
|
2822
|
+
if (want.kind === "array")
|
|
2823
|
+
return ts.isCallExpression(e) && this.exportName(e.expression) === "fixedArray";
|
|
2824
|
+
return ts.isObjectLiteralExpression(e);
|
|
2825
|
+
};
|
|
2826
|
+
if (!literal(n))
|
|
2827
|
+
return undefined;
|
|
2828
|
+
if (want.kind === "struct") {
|
|
2829
|
+
const s = this.model.structs.get(want.name);
|
|
2830
|
+
if (s.size === undefined || s.vec)
|
|
2831
|
+
this.fail(n, `${s.name} has variable-size fields and cannot be built as an argument`);
|
|
2832
|
+
}
|
|
2833
|
+
const t = this.tmp("larg");
|
|
2834
|
+
this.line(`${want.kind === "array" ? storageDecl(want, t) : `${fieldC(want)} ${t}`};`);
|
|
2835
|
+
this.writeAggregate({ lv: t, type: want, writable: true }, n, true);
|
|
2836
|
+
return `(&${t})`;
|
|
2837
|
+
}
|
|
1821
2838
|
/**
|
|
1822
2839
|
* A struct/array/data-enum helper argument. Helpers that take accounts may change account data, so they get a
|
|
1823
2840
|
* copy taken at the call (JS passes the object as it was); other helpers cannot write, so a pointer is enough.
|
|
@@ -1832,12 +2849,84 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1832
2849
|
const n = this.fieldBytes(type);
|
|
1833
2850
|
// One buffer per call site, allocated on first use: a call in a loop must not take new heap every pass.
|
|
1834
2851
|
const t = this.tmp("argc");
|
|
1835
|
-
|
|
1836
|
-
this.hoisted.push(` ${decl} = NULL;`);
|
|
2852
|
+
this.hoistLazy(t, (n) => (type.kind === "array" ? storageDecl(type, `(*${n})`) : `${fieldC(type)} *${n}`));
|
|
1837
2853
|
this.line(`if (${t} == NULL) TS_TRY(ts_alloc(${n}, (uint8_t **)&${t}));`);
|
|
1838
2854
|
this.line(`ts_memcpy(${t}, &${lv}, ${n});`);
|
|
1839
2855
|
return t;
|
|
1840
2856
|
}
|
|
2857
|
+
/**
|
|
2858
|
+
* A FixedVec or FixedArray of `elem` given for a read-only list parameter: a `TS_VecArg` view of its elements (the
|
|
2859
|
+
* length as it is at the call). A list this function holds (a local, a field of a struct it owns) is read in place;
|
|
2860
|
+
* one in account data is copied first when the helper takes accounts, as a struct argument is (the helper may write
|
|
2861
|
+
* the account). Undefined when `n` is not such a list.
|
|
2862
|
+
*/
|
|
2863
|
+
listViewArg(n, want, h) {
|
|
2864
|
+
const r = this.probe(() => this.ref(n));
|
|
2865
|
+
if (!r)
|
|
2866
|
+
return undefined;
|
|
2867
|
+
const elem = want.elem;
|
|
2868
|
+
// A FixedVec<T, N> parameter holds at most N elements: a list with room for more is refused here, as an
|
|
2869
|
+
// instruction argument with more is refused when decoded.
|
|
2870
|
+
const holds = r.type.kind === "vec" ? r.type.cap : r.type.kind === "array" ? r.type.len : undefined;
|
|
2871
|
+
if (want.cap !== undefined && holds !== undefined && holds > want.cap && (r.type.kind === "vec" || r.type.kind === "array") && sameType(r.type.elem, elem))
|
|
2872
|
+
this.fail(n, `${h.display}() takes at most ${want.cap} elements here (FixedVec<${typeName(elem)}, ${want.cap}>) and this list holds up to ${holds}: declare the parameter FixedVec<${typeName(elem)}, ${holds}> (or InstructionBytes / Vec<${typeName(elem)}>, no limit)`);
|
|
2873
|
+
let items;
|
|
2874
|
+
let count;
|
|
2875
|
+
let room;
|
|
2876
|
+
if (r.type.kind === "vec" && r.type.cap !== undefined && !r.type.heap && !r.type.big && !r.type.raw && r.vec && !r.vec.slice) {
|
|
2877
|
+
if (!sameType(r.type.elem, elem))
|
|
2878
|
+
return undefined;
|
|
2879
|
+
const fresh = this.ref(n);
|
|
2880
|
+
items = fresh.vec.items;
|
|
2881
|
+
count = vecCount(fresh.vec);
|
|
2882
|
+
room = r.type.cap;
|
|
2883
|
+
}
|
|
2884
|
+
else if (r.type.kind === "array") {
|
|
2885
|
+
if (!sameType(r.type.elem, elem))
|
|
2886
|
+
return undefined;
|
|
2887
|
+
items = this.ref(n).lv;
|
|
2888
|
+
count = String(r.type.len);
|
|
2889
|
+
room = r.type.len;
|
|
2890
|
+
}
|
|
2891
|
+
else
|
|
2892
|
+
return undefined;
|
|
2893
|
+
const size = this.fieldBytes(elem);
|
|
2894
|
+
const t = this.tmp("lview");
|
|
2895
|
+
if (h.params.some((p) => p.account || p.type.kind === "account" || p.type.kind === "remaining") && !this.callerHoldsList(n)) {
|
|
2896
|
+
// One buffer per call site, allocated on first use: a call in a loop must not take new heap every pass.
|
|
2897
|
+
const buf = this.tmp("argl");
|
|
2898
|
+
this.hoistLazy(buf, (v) => `uint8_t *${v}`);
|
|
2899
|
+
this.line(`if (${buf} == NULL) TS_TRY(ts_alloc(${room * size}, &${buf}));`);
|
|
2900
|
+
this.line(`TS_VecArg ${t} = {${buf}, (uint32_t)${count}};`);
|
|
2901
|
+
this.line(`ts_memcpy_bulk(${buf}, (const uint8_t *)${items}, (uint64_t)${t}.len * ${size});`);
|
|
2902
|
+
return t;
|
|
2903
|
+
}
|
|
2904
|
+
this.line(`TS_VecArg ${t} = {(const uint8_t *)${items}, (uint32_t)${count}};`);
|
|
2905
|
+
return t;
|
|
2906
|
+
}
|
|
2907
|
+
/** Whether `node` is a list this function holds on its stack (a local list, a field of a struct it owns), not account data. */
|
|
2908
|
+
callerHoldsList(node) {
|
|
2909
|
+
let n = node;
|
|
2910
|
+
for (;;) {
|
|
2911
|
+
if (ts.isParenthesizedExpression(n))
|
|
2912
|
+
n = n.expression;
|
|
2913
|
+
else if (ts.isPropertyAccessExpression(n))
|
|
2914
|
+
n = n.expression;
|
|
2915
|
+
else if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression) && n.expression.name.text === "get")
|
|
2916
|
+
n = n.expression.expression;
|
|
2917
|
+
else
|
|
2918
|
+
break;
|
|
2919
|
+
}
|
|
2920
|
+
if (!ts.isIdentifier(n))
|
|
2921
|
+
return false;
|
|
2922
|
+
const l = this.lookup(n.text);
|
|
2923
|
+
if (!l)
|
|
2924
|
+
return false;
|
|
2925
|
+
// A declared list local has no storage paths; an Inout parameter's (`@p_x`) may be account data.
|
|
2926
|
+
if ((l.type.kind === "vec" || l.type.kind === "array") && !l.paths && !l.readonly)
|
|
2927
|
+
return true;
|
|
2928
|
+
return !!l.owned;
|
|
2929
|
+
}
|
|
1841
2930
|
/** Whether `node` is (part of) a struct value this function owns: `h`, `h.inner`, `h.list.get(i)`. */
|
|
1842
2931
|
ownedRoot(node) {
|
|
1843
2932
|
let n = node;
|
|
@@ -1921,27 +3010,27 @@ export class CallEmitter extends ExpressionEmitter {
|
|
|
1921
3010
|
this.fail(node, "returnData needs an explicit type: returnData<u64>(program)");
|
|
1922
3011
|
if (node.arguments.length !== 1)
|
|
1923
3012
|
this.fail(node, "returnData<T>(program) takes the program that returned it");
|
|
1924
|
-
const program = this.
|
|
3013
|
+
const program = this.anyAccount(node.arguments[0], "returnData's program");
|
|
1925
3014
|
const out = this.tmp("rd");
|
|
1926
3015
|
if (t.kind === "pubkey") {
|
|
1927
3016
|
this.line(`SolPubkey ${out};`);
|
|
1928
|
-
this.line(`TS_TRY(ts_return_data(
|
|
3017
|
+
this.line(`TS_TRY(ts_return_data(${program}, (uint8_t *)&${out}, 32));`);
|
|
1929
3018
|
return { c: `(&${out})`, type: t };
|
|
1930
3019
|
}
|
|
1931
3020
|
if (t.kind === "bool") {
|
|
1932
3021
|
this.line(`uint8_t ${out};`);
|
|
1933
|
-
this.line(`TS_TRY(ts_return_data(
|
|
3022
|
+
this.line(`TS_TRY(ts_return_data(${program}, &${out}, 1));`);
|
|
1934
3023
|
this.line(`if (${out} > 1) TS_FAIL(TS_ERR_RETURN_DATA, "TypeSOL: invalid bool return data");`);
|
|
1935
3024
|
return { c: `(${out} == 1)`, type: BOOL };
|
|
1936
3025
|
}
|
|
1937
3026
|
if (t.kind === "enum") {
|
|
1938
3027
|
this.line(`uint8_t ${out};`);
|
|
1939
|
-
this.line(`TS_TRY(ts_return_data(
|
|
3028
|
+
this.line(`TS_TRY(ts_return_data(${program}, &${out}, 1));`);
|
|
1940
3029
|
this.line(`if (${out} >= ${this.model.enums.get(t.name).variants.length}) TS_FAIL(TS_ERR_RETURN_DATA, "TypeSOL: invalid enum return data");`);
|
|
1941
3030
|
return { c: out, type: t };
|
|
1942
3031
|
}
|
|
1943
3032
|
this.line(`${INT_INFO[t.name].c} ${out};`);
|
|
1944
|
-
this.line(`TS_TRY(ts_return_data(
|
|
3033
|
+
this.line(`TS_TRY(ts_return_data(${program}, (uint8_t *)&${out}, ${INT_INFO[t.name].bytes}));`);
|
|
1945
3034
|
return { c: out, type: t };
|
|
1946
3035
|
}
|
|
1947
3036
|
}
|