-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalues.ts
More file actions
903 lines (866 loc) · 29.3 KB
/
Copy pathvalues.ts
File metadata and controls
903 lines (866 loc) · 29.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
// Bidirectional value-shape adaptation (contracts/embedder-api.md
// §"Value mapping").
//
// FROM: the runtime's raw boundary, which mirrors the definitions.py
// interpreter's SEMANTICS in its own representation — `{kind, value}`
// variants (`{ kind: "circle", value: 1.5 }`; cabi/types.ts
// `VariantValue`), likewise option and result, tuple-as-record
// (`{ "0": …, "1": … }`)
// (note: the internal despecialization labels result's err case
// `"error"`, not `"err"` — cabi/types.ts `despecialize`), kebab-case
// record keys, resource handles as bare reps.
// TO: the conventions: `{ kind, value? }` for variants and nested results,
// outermost-option-as-`undefined` with nested boxing, real tuples,
// camelCase record fields, flags objects, enum strings verbatim,
// `Uint8Array` for `list<u8>`, class instances for resources,
// `Stream`/`Future`/`ErrorContext` handles.
//
// The adapter is driven entirely by the plan's `ValType`s — no generated code
// participates in value conversion. Generated wrappers can verify types and
// delegate instantiation; this adapter also serves untyped callers.
import type {
CaseType,
ComponentValue,
EnumType,
FlagsType,
RecordType,
ValType,
VariantValue,
} from "../cabi/types.ts";
import { despecialize } from "../cabi/types.ts";
import { ERROR_CONTEXT, hasBrand } from "@polyengine/protocol";
import { describeCrossCopy } from "./copy.ts";
import { ErrorContext as InternalErrorContext } from "../task/mod.ts";
import { dropSharedForTeardown } from "../task/mod.ts";
import { camelCase } from "./casing.ts";
import { NameCollisionError } from "./errors.ts";
import {
type ElemCodec,
ErrorContext,
Future,
lowerFutureSource,
lowerStreamSource,
Stream,
} from "./streams.ts";
import {
type PreparedCustody,
type PreparedTransfer,
PreparedValues,
TransferFreeValues,
} from "../cabi/values.ts";
import { borrowedBytes } from "../cabi/memory.ts";
/**
* The parts of adaptation that need instance state: resources (identity
* mapping, ownership) and the borrow scope of the call in flight.
* @internal — value-adapter wiring, supplied by the runtime's instance
* state.
*/
export interface ValueBridge {
/** A guest handed the host an `own<R>`; the host now owns it. */
liftOwn(rep: number, t: ValType & { kind: "own" }): unknown;
/** A guest handed the host a `borrow<R>`, valid only for this call. */
liftBorrow(
rep: number,
t: ValType & { kind: "borrow" },
scope: BorrowScope,
): unknown;
/** The host is passing an `own<R>` (transfer). */
lowerOwn(
v: unknown,
t: ValType & { kind: "own" },
checkpoint?: () => void,
): number;
/** The host is passing a `borrow<R>` (no transfer). */
lowerBorrow(
v: unknown,
t: ValType & { kind: "borrow" },
checkpoint?: () => void,
releases?: (() => void)[],
): number;
/**
* Destroy a LOWERED `own<R>` the guest will never receive (a resource
* stream element the producer lowered but the reader never took).
* Runs the resource's destructor — for a host-implemented R the
* instance's `[Symbol.dispose]`, for a guest-implemented R the guest
* dtor — exactly as if the guest had taken the handle and dropped it.
*/
dropOwn(rep: number, t: ValType & { kind: "own" }): void;
}
/**
* Wrappers materialized for `borrow<R>` arguments of one call. The contract:
* "instance valid **only during the call** (retention throws)", so the scope
* invalidates them when the call returns.
*
* @internal — the runtime materializes and invalidates these per call; a
* host never constructs or names one.
*/
export class BorrowScope {
readonly #invalidate: (() => void)[] = [];
add(f: () => void): void {
this.#invalidate.push(f);
}
end(): void {
for (const f of this.#invalidate) f();
this.#invalidate.length = 0;
}
}
/** A no-op scope for positions where no borrow can appear. */
export const NO_BORROWS = new BorrowScope();
/**
* Label sets already checked for camelCase collisions. `ValType` objects are
* stable for the lifetime of a loaded plan, so this is a one-time cost per
* record/flags type rather than a per-call one.
*/
const checkedLabels = new WeakSet<object>();
/**
* Refuse two labels in one scope that camelCase to the same JS name.
*
* `read-only` and `readOnly` are distinct WIT labels but one JS property, so
* one would silently shadow the other at the boundary — values corrupted with
* no diagnostic anywhere. Contract principle 2: footguns are design defects.
*/
export function checkNoCollisions(
key: object,
labels: string[],
what: string,
): void {
if (checkedLabels.has(key)) return;
const seen = new Map<string, string>();
for (const l of labels) {
const js = camelCase(l);
const held = seen.get(js);
if (held !== undefined) {
throw new NameCollisionError(
`${what}: the labels '${held}' and '${l}' both map to the JS name ` +
`'${js}'. Rename one in the WIT; the conventions layer will not ` +
`guess which one wins.`,
);
}
seen.set(js, l);
}
checkedLabels.add(key);
}
// ---------------------------------------------------------------------------
// Per-type adapter tables
// ---------------------------------------------------------------------------
//
// Both directions share immutable type-derived tables, cached by ValType
// identity. Weak keys let the tables die with the loaded plan.
interface RecordField {
/** The WIT label — the key of the internal record object. */
label: string;
/** The camelCased JS name — the key of the host object. */
js: string;
type: ValType;
isOption: boolean;
/** The option's payload type when `isOption`, else null. */
optionInner: ValType | null;
}
interface RecordTable {
/** The labels in source order, for `checkNoCollisions`. */
labels: string[];
fields: RecordField[];
}
const recordTables = new WeakMap<RecordType, RecordTable>();
function recordTable(t: RecordType): RecordTable {
const hit = recordTables.get(t);
if (hit !== undefined) return hit;
const table: RecordTable = {
labels: t.fields.map((f) => f.label),
fields: t.fields.map((f) => ({
label: f.label,
js: camelCase(f.label),
type: f.type,
isOption: f.type.kind === "option",
optionInner: f.type.kind === "option" ? f.type.type : null,
})),
};
recordTables.set(t, table);
return table;
}
/**
* Label -> first matching case, memoized on the cases array. Unlike the CABI
* caseIndexOf helper, duplicate labels select the first rather than fail.
*/
const variantTables = new WeakMap<CaseType[], Map<string, CaseType>>();
function variantTable(cases: CaseType[]): Map<string, CaseType> {
const hit = variantTables.get(cases);
if (hit !== undefined) return hit;
const m = new Map<string, CaseType>();
for (const c of cases) if (!m.has(c.label)) m.set(c.label, c);
variantTables.set(cases, m);
return m;
}
/** Membership set for enum labels. */
const enumTables = new WeakMap<EnumType, Set<string>>();
function enumTable(t: EnumType): Set<string> {
const hit = enumTables.get(t);
if (hit !== undefined) return hit;
const s = new Set(t.labels);
enumTables.set(t, s);
return s;
}
/** Flags labels paired with their JS names, in source order. */
const flagsTables = new WeakMap<FlagsType, { label: string; js: string }[]>();
function flagsTable(t: FlagsType): { label: string; js: string }[] {
const hit = flagsTables.get(t);
if (hit !== undefined) return hit;
const table = t.labels.map((label) => ({ label, js: camelCase(label) }));
flagsTables.set(t, table);
return table;
}
/** @internal — value-adapter wiring. */
export interface AdapterOptions {
bridge: ValueBridge;
/** Names the site in error messages (`import 'wasi:x/y'.f`, param 2). */
where: string;
/** The executor store values lowered through this adapter will enter. */
destinationStore?: unknown;
}
// ---------------------------------------------------------------------------
// internal -> conventions
// ---------------------------------------------------------------------------
/**
* Adapt one lifted value to its conventions shape.
*
* `inOption` implements the contract's option rule: the *outermost* option in
* a chain maps to `T | undefined`; an option nested **directly inside another
* option** boxes as `{ kind: "some", value } | { kind: "none" }`. Only option maps
* to `undefined`, so this is the only ambiguity, and the flag is set only when
* descending through an option's payload — every other constructor resets it.
* @internal — value-adapter internals; the facade adapts values at the
* boundary.
*/
export function toHost(
v: ComponentValue,
t: ValType,
o: AdapterOptions,
scope: BorrowScope = NO_BORROWS,
inOption = false,
): unknown {
switch (t.kind) {
case "bool":
case "s8":
case "u8":
case "s16":
case "u16":
case "s32":
case "u32":
case "s64":
case "u64":
case "f32":
case "f64":
case "char":
case "string":
return v;
case "error-context":
return new ErrorContext(v as unknown as InternalErrorContext);
case "list": {
const elem = despecialize(t.element);
if (elem.kind === "u8") {
// Already a Uint8Array from the raw boundary (docs/architecture.md §7); copy defensively
// only if the interpreter handed back a plain array (fixed-length lists
// take the Uint8Array path too, but be tolerant).
return v instanceof Uint8Array ? v : Uint8Array.from(v as number[]);
}
return (v as ComponentValue[]).map((e) => toHost(e, t.element, o, scope));
}
case "record": {
const table = recordTable(t);
checkNoCollisions(t, table.labels, `${o.where}: record`);
const src = v as Record<string, ComponentValue>;
const out: Record<string, unknown> = {};
for (const f of table.fields) {
// "fields of option type are optional properties (`field?: T`)": a
// `none` field is *absent*, not `undefined`-valued, so the object has
// one canonical shape rather than two indistinguishable ones.
if (f.isOption) {
const inner = src[f.label] as VariantValue;
if (inner.kind === "none") continue;
out[f.js] = toHost(
inner.value,
f.optionInner!,
o,
scope,
true,
);
continue;
}
out[f.js] = toHost(src[f.label], f.type, o, scope);
}
return out;
}
case "tuple": {
const src = v as Record<string, ComponentValue>;
return t.elements.map((et, i) => toHost(src[String(i)], et, o, scope));
}
case "variant": {
const { kind: label, value: payload } = internalTag(v, o);
const c = variantTable(t.cases).get(label);
if (c === undefined) {
throw new TypeError(`${o.where}: unknown variant case '${label}'`);
}
return c.type === null
? { kind: label }
: { kind: label, value: toHost(payload, c.type, o, scope) };
}
case "enum": {
// Enum values are data: kebab-case verbatim, never camelCased.
// Asymmetry (contracts/embedder-api.md §"Implementation strategy"):
// internal is a variant value, this layer's enum is a bare string.
return internalTag(v, o).kind;
}
case "option": {
const { kind: label, value: payload } = internalTag(v, o);
if (inOption) {
return label === "none"
? { kind: "none" }
: { kind: "some", value: toHost(payload, t.type, o, scope, true) };
}
return label === "none"
? undefined
: toHost(payload, t.type, o, scope, true);
}
case "result": {
const { kind: label, value: payload } = internalTag(v, o);
// Internal despecialization names the err case "error"; the contract's
// kind is "err" (cabi/types.ts `despecialize`).
const kind = label === "error" ? "err" : "ok";
const ct = label === "error" ? t.error : t.ok;
return ct === null
? { kind }
: { kind, value: toHost(payload, ct, o, scope) };
}
case "flags": {
checkNoCollisions(t, t.labels, `${o.where}: flags`);
const src = v as Record<string, ComponentValue>;
const out: Record<string, boolean> = {};
for (const f of flagsTable(t)) out[f.js] = Boolean(src[f.label]);
return out;
}
case "map": {
// `map<K,V>` despecializes to `list<tuple<K,V>>`; keep that shape.
return toHost(v, despecialize(t), o, scope);
}
case "own":
return o.bridge.liftOwn(v as number, t);
case "borrow":
return o.bridge.liftBorrow(v as number, t, scope);
case "stream":
return Stream.fromLifted(v, elemCodec(t.element, o));
case "future":
return Future.fromLifted(v, elemCodec(t.element, o));
}
}
/**
* Read an INTERNAL variant-family value (cabi/types.ts `VariantValue`):
* `value` always present, result's err case spelled `"error"`, every option
* boxed. Its host-side counterpart is `hostTag` below — the two shapes are
* near-identical and not interchangeable, so the layer is in the name.
*/
function internalTag(v: ComponentValue, o: AdapterOptions): VariantValue {
if (v === null || typeof v !== "object" || Array.isArray(v)) {
throw new TypeError(
`${o.where}: expected a { kind, value } case object, got ${describe(v)}`,
);
}
const rec = v as VariantValue;
if (typeof rec.kind !== "string") {
throw new TypeError(
`${o.where}: expected a { kind, value } case object, got ${describe(v)}`,
);
}
return rec;
}
// ---------------------------------------------------------------------------
// conventions -> internal
// ---------------------------------------------------------------------------
/**
* @internal — value-adapter internals; the facade adapts values at the
* boundary.
*/
export function prepareHostValue(
v: unknown,
t: ValType,
o: AdapterOptions,
inOption = false,
): ComponentValue {
switch (t.kind) {
case "bool":
return Boolean(v);
case "u8":
return int(v, t.kind, 0, 0xff, o);
case "u16":
return int(v, t.kind, 0, 0xffff, o);
case "u32":
return int(v, t.kind, 0, 0xffffffff, o);
case "s8":
return int(v, t.kind, -0x80, 0x7f, o);
case "s16":
return int(v, t.kind, -0x8000, 0x7fff, o);
case "s32":
return int(v, t.kind, -0x80000000, 0x7fffffff, o);
case "u64":
return big(v, t.kind, 0n, (1n << 64n) - 1n, o);
case "s64":
return big(v, t.kind, -(1n << 63n), (1n << 63n) - 1n, o);
case "f32":
case "f64":
if (typeof v !== "number") {
throw new TypeError(`${o.where}: ${t.kind} expects a number`);
}
return v;
case "char": {
if (typeof v !== "string" || [...v].length !== 1) {
throw new TypeError(
`${o.where}: char expects a single-code-point string`,
);
}
// A lone surrogate has `[...v].length === 1` but is not a Unicode
// scalar value, so `char` cannot hold it. Reject here, where the site is
// known: the interpreter's own check reports only "not a valid char".
const cp = v.codePointAt(0)!;
if (cp >= 0xd800 && cp <= 0xdfff) {
throw new TypeError(
`${o.where}: char expects a Unicode scalar value, got the lone ` +
`surrogate U+${cp.toString(16).toUpperCase()}`,
);
}
return v;
}
case "string":
if (typeof v !== "string") {
throw new TypeError(`${o.where}: string expects a string`);
}
return v;
case "error-context": {
if (v instanceof ErrorContext) {
return v.internal as unknown as ComponentValue;
}
if (v instanceof InternalErrorContext) {
return v as unknown as ComponentValue;
}
// realm boundary (contracts/embedder-api.md §"Error-context is message-valued";
// issue #131; definitions.py — an error-context's state is exactly
// its debug message): a branded carrier of a string `message`, from
// any copy (or hand-rolled), is accepted by minting a FRESH local
// context — never "the same" one, since there is nothing to alias.
if (
hasBrand(v, ERROR_CONTEXT) &&
typeof (v as { message?: unknown }).message === "string"
) {
return new InternalErrorContext(
(v as { message: string }).message,
) as unknown as ComponentValue;
}
// A foreign brand without a public string message cannot be
// reconstructed by value; report the copy boundary explicitly.
if (hasBrand(v, ERROR_CONTEXT)) {
throw new TypeError(
`${o.where}: ${describeCrossCopy("this error-context")}`,
);
}
throw new TypeError(`${o.where}: expected an ErrorContext`);
}
case "list": {
const elem = despecialize(t.element);
if (elem.kind === "u8") {
if (v instanceof Uint8Array) return borrowedBytes(v);
if (Array.isArray(v)) return Uint8Array.from(v as number[]);
throw new TypeError(`${o.where}: list<u8> expects a Uint8Array`);
}
if (!Array.isArray(v)) {
throw new TypeError(`${o.where}: list expects an array`);
}
const out = new Array<ComponentValue>(v.length);
for (let i = 0; i < v.length; i++) {
out[i] = prepareHostValue(v[i], t.element, o);
}
return out;
}
case "record": {
if (v === null || typeof v !== "object") {
throw new TypeError(`${o.where}: record expects an object`);
}
const table = recordTable(t);
checkNoCollisions(t, table.labels, `${o.where}: record`);
const src = v as Record<string, unknown>;
const out: Record<string, ComponentValue> = {};
for (const f of table.fields) {
const key = f.js;
if (f.isOption) {
// Absent and `undefined` both mean `none` — the two spellings of an
// optional property.
const inner = src[key];
out[f.label] = inner === undefined ? { kind: "none", value: null } : {
kind: "some",
value: prepareHostValue(inner, f.optionInner!, o, true),
};
continue;
}
if (!(key in src)) {
throw new TypeError(`${o.where}: record field '${key}' is missing`);
}
out[f.label] = prepareHostValue(src[key], f.type, o);
}
return out;
}
case "tuple": {
if (!Array.isArray(v) || v.length !== t.elements.length) {
throw new TypeError(
`${o.where}: tuple expects an array of ${t.elements.length}`,
);
}
const out: Record<string, ComponentValue> = {};
t.elements.forEach((et, i) => {
out[String(i)] = prepareHostValue(v[i], et, o);
});
return out;
}
case "variant": {
const { kind, value, has } = hostTag(v, o);
const c = variantTable(t.cases).get(kind);
if (c === undefined) {
throw new TypeError(`${o.where}: unknown variant case '${kind}'`);
}
if (c.type === null) return { kind, value: null };
if (!has) {
throw new TypeError(
`${o.where}: variant case '${kind}' needs a 'value'`,
);
}
return { kind, value: prepareHostValue(value, c.type, o) };
}
case "enum": {
if (typeof v !== "string" || !enumTable(t).has(v)) {
throw new TypeError(
`${o.where}: enum expects one of ${t.labels.join(" | ")}, got ` +
describe(v),
);
}
return { kind: v, value: null };
}
case "option": {
if (inOption) {
const { kind, value, has } = hostTag(v, o);
if (kind === "none") return { kind: "none", value: null };
if (kind !== "some") {
throw new TypeError(
`${o.where}: a nested option must be { kind: "some" | "none" }`,
);
}
return {
kind: "some",
value: has ? prepareHostValue(value, t.type, o, true) : null,
};
}
return v === undefined
? { kind: "none", value: null }
: { kind: "some", value: prepareHostValue(v, t.type, o, true) };
}
case "result": {
const { kind, value, has } = hostTag(v, o);
if (kind !== "ok" && kind !== "err") {
throw new TypeError(
`${o.where}: a result value must be { kind: "ok" | "err" }`,
);
}
const label = kind === "err" ? "error" : "ok";
const ct = kind === "err" ? t.error : t.ok;
if (ct === null) return { kind: label, value: null };
// Symmetric with the variant path above: a case that carries a payload
// must be given one. Silently lowering `null` would put a zero where the
// guest expects data.
if (!has) {
throw new TypeError(
`${o.where}: result case '${kind}' carries a payload and needs a 'value'`,
);
}
return { kind: label, value: prepareHostValue(value, ct, o) };
}
case "flags": {
if (v === null || typeof v !== "object") {
throw new TypeError(`${o.where}: flags expects an object`);
}
checkNoCollisions(t, t.labels, `${o.where}: flags`);
const src = v as Record<string, unknown>;
const out: Record<string, ComponentValue> = {};
// "lower: absent = false" — an omitted flag is not an error.
for (const f of flagsTable(t)) out[f.label] = Boolean(src[f.js]);
return out;
}
case "map":
return prepareHostValue(v, despecialize(t), o);
case "own":
case "borrow":
case "stream":
case "future":
// Opaque and unvalidated until transfer. In particular, no wrapper state
// or producer protocol is touched by structural preparation.
return v as ComponentValue;
}
}
const transferKinds = new WeakMap<object, boolean>();
const borrowKinds = new WeakMap<object, boolean>();
/** Whether guest-to-host lifting can materialize a call-scoped borrow wrapper. */
export function needsBorrowScope(t: ValType): boolean {
const key = t as object;
const hit = borrowKinds.get(key);
if (hit !== undefined) return hit;
borrowKinds.set(key, false);
const d = despecialize(t);
const answer = d.kind === "borrow" ||
(d.kind === "list" && needsBorrowScope(d.element)) ||
(d.kind === "record" && d.fields.some((f) => needsBorrowScope(f.type))) ||
(d.kind === "variant" &&
d.cases.some((c) => c.type !== null && needsBorrowScope(c.type)));
borrowKinds.set(key, answer);
return answer;
}
function needsTransfer(t: ValType): boolean {
const key = t as object;
const hit = transferKinds.get(key);
if (hit !== undefined) return hit;
// Break recursive aliases conservatively; plans are finite after
// despecialization, but resource metadata can contain identity cycles.
transferKinds.set(key, false);
const d = despecialize(t);
const answer = d.kind === "own" || d.kind === "borrow" ||
d.kind === "stream" || d.kind === "future" ||
(d.kind === "list" && needsTransfer(d.element)) ||
(d.kind === "record" && d.fields.some((f) => needsTransfer(f.type))) ||
(d.kind === "variant" &&
d.cases.some((c) => c.type !== null && needsTransfer(c.type)));
transferKinds.set(key, answer);
return answer;
}
function transferPreparedValue(
v: ComponentValue,
t: ValType,
o: AdapterOptions,
custody: PreparedCustody,
checkpoint: () => void,
releases: (() => void)[],
): ComponentValue {
if (!needsTransfer(t)) return v;
const d = despecialize(t);
switch (d.kind) {
case "own": {
checkpoint();
const rep = o.bridge.lowerOwn(v, d, checkpoint);
// Acquisition is recorded before any later leaf or CABI callback.
custody.acquire(() => o.bridge.dropOwn(rep, d));
checkpoint();
return rep;
}
case "borrow":
checkpoint();
return o.bridge.lowerBorrow(v, d, checkpoint, releases);
case "stream": {
checkpoint();
const source = v as unknown;
const lowered = lowerStreamSource(
source as never,
elemCodec(d.element, o),
o.destinationStore,
(start) => custody.deferStart(start),
checkpoint,
);
custody.acquire(() => dropSharedForTeardown(lowered as never));
return lowered;
}
case "future": {
checkpoint();
const source = v as unknown;
const lowered = lowerFutureSource(
source as never,
elemCodec(d.element, o),
o.destinationStore,
(start) => custody.deferStart(start),
checkpoint,
);
custody.acquire(() => dropSharedForTeardown(lowered as never));
return lowered;
}
case "list": {
const values = v as ComponentValue[];
for (let i = 0; i < values.length; i++) {
values[i] = transferPreparedValue(
values[i],
d.element,
o,
custody,
checkpoint,
releases,
);
}
return values;
}
case "record": {
const values = v as Record<string, ComponentValue>;
for (const f of d.fields) {
values[f.label] = transferPreparedValue(
values[f.label],
f.type,
o,
custody,
checkpoint,
releases,
);
}
return values;
}
case "variant": {
const tagged = v as VariantValue;
const c = d.cases.find((x) => x.label === tagged.kind);
if (c?.type !== null && c !== undefined) {
tagged.value = transferPreparedValue(
tagged.value,
c.type,
o,
custody,
checkpoint,
releases,
);
}
return tagged;
}
default:
return v;
}
}
/** Snapshot a complete facade argument/result list before acquiring ownership. */
export function prepareHostValues(
vs: unknown[],
ts: ValType[],
o: AdapterOptions,
releases: (() => void)[] = [],
): PreparedTransfer {
const values = new Array<ComponentValue>(ts.length);
for (let i = 0; i < ts.length; i++) {
values[i] = prepareHostValue(vs[i], ts[i], o);
}
const transfer = ts.some(needsTransfer)
? (
prepared: ComponentValue[],
types: ValType[],
custody: PreparedCustody,
checkpoint: () => void,
) => {
for (let i = 0; i < types.length; i++) {
prepared[i] = transferPreparedValue(
prepared[i],
types[i],
o,
custody,
checkpoint,
releases,
);
}
}
: undefined;
return transfer === undefined
? new TransferFreeValues(values, ts)
: new PreparedValues(values, ts, transfer);
}
/** Scalar/transfer-free result fast path: validate without list/envelope work. */
export function prepareHostScalar(
value: unknown,
type: ValType,
o: AdapterOptions,
): ComponentValue {
return prepareHostValue(value, type, o);
}
/** Compatibility/internal one-shot API. New boundary paths use prepareHostValues. */
export function fromHost(
v: unknown,
t: ValType,
o: AdapterOptions,
): ComponentValue {
const prepared = prepareHostValues([v], [t], o);
try {
const value = prepared.transfer(() => {})[0];
prepared.delivered();
return value;
} catch (e) {
prepared.cleanup(e);
throw e;
}
}
/**
* Read a HOST variant-family value (contracts/embedder-api.md §"Value
* mapping"): `value` absent for payloadless cases — hence `has` — and result's
* err case spelled `"err"`. The internal-side counterpart is `internalTag`.
*/
function hostTag(
v: unknown,
o: AdapterOptions,
): { kind: string; value: unknown; has: boolean } {
if (v === null || typeof v !== "object" || !("kind" in v)) {
throw new TypeError(
`${o.where}: expected a { kind, value? } value, got ${describe(v)}`,
);
}
const rec = v as { kind: unknown; value?: unknown };
if (typeof rec.kind !== "string") {
throw new TypeError(`${o.where}: 'kind' must be a string`);
}
return { kind: rec.kind, value: rec.value, has: "value" in rec };
}
function int(
v: unknown,
kind: string,
lo: number,
hi: number,
o: AdapterOptions,
): number {
if (typeof v !== "number" || !Number.isInteger(v)) {
throw new TypeError(`${o.where}: ${kind} expects an integer number`);
}
if (v < lo || v > hi) {
throw new TypeError(`${o.where}: ${kind} out of range: ${v}`);
}
// Keep signed values signed; lowerFlatSigned32 performs lane conversion.
return v;
}
function big(
v: unknown,
kind: string,
lo: bigint,
hi: bigint,
o: AdapterOptions,
): bigint {
if (typeof v !== "bigint") {
throw new TypeError(`${o.where}: ${kind} expects a bigint`);
}
if (v < lo || v > hi) {
throw new TypeError(`${o.where}: ${kind} out of range: ${v}`);
}
return v;
}
/** Per-element codec for a `stream<T>` / `future<T>`. */
export function elemCodec(
element: ValType | null,
o: AdapterOptions,
): ElemCodec<unknown> {
return {
element,
where: o.where,
toHost: (v) => element === null ? undefined : toHost(v, element, o),
fromHost: (v) => element === null ? null : fromHost(v, element, o),
prepareHost: element === null
? undefined
: (v) => prepareHostValues([v], [element], o),
// Release untaken top-level own elements. This codec does not recursively
// clean up owned resources nested in composite elements.
release: element !== null && element.kind === "own"
? (v) => o.bridge.dropOwn(v as number, element)
: undefined,
};
}
export function describe(v: unknown): string {
if (v === null) return "null";
if (v === undefined) return "undefined";
if (typeof v === "object") return `a ${v.constructor?.name ?? "object"}`;
return `a ${typeof v} (${String(v)})`;
}