js-component-bindgen 1.16.5

JS component bindgen for transpiling WebAssembly components into JavaScript
Documentation
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
//! Intrinsics that represent helpers that enable Lower integration

use crate::intrinsics::Intrinsic;
use crate::intrinsics::component::ComponentIntrinsic;
use crate::intrinsics::p3::{async_stream::AsyncStreamIntrinsic, error_context::ErrCtxIntrinsic};
use crate::intrinsics::string::StringIntrinsic;
use crate::source::Source;

use super::conversion::ConversionIntrinsic;

/// This enum contains intrinsics that enable Lower
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum LowerIntrinsic {
    /// Lower a boolean into provided storage, given a core type
    ///
    /// This function is of the form:
    ///
    /// ```ts
    /// type u32 = number;
    /// (coreVals: u32[], ptr: u32, len: u32) => void;
    /// ```
    ///
    /// In this case, coreVals is expected to contain precisely *one* numerical (u32-equivalent) value.
    LowerFlatBool,

    /// Lower a s8 into provided storage given core type(s)
    ///
    /// This function is of the form:
    ///
    /// ```ts
    /// type u32 = number;
    /// (coreVals: u32[], ptr: u32, len: u32) => void;
    /// ```
    ///
    /// In this case, coreVals is expected to contain precisely *one* numerical (u32-equivalent) value,
    /// which is bounded from -128 to 127.
    LowerFlatS8,

    /// Lower a u8 into provided storage given core type(s)
    ///
    /// This function is of the form:
    ///
    /// ```ts
    /// type u32 = number;
    /// (coreVals: u32[], ptr: u32, len: u32) => void;
    /// ```
    ///
    /// In this case, coreVals is expected to contain precisely *one* numerical (u32-equivalent) value,
    /// which is bounded from 0 to 255.
    LowerFlatU8,

    /// Lower a s16 into provided storage given core type(s)
    ///
    /// This function is of the form:
    ///
    /// ```ts
    /// type u32 = number;
    /// (coreVals: u32[], ptr: u32, len: u32) => void;
    /// ```
    ///
    /// In this case, coreVals is expected to contain precisely *one* numerical (u32-equivalent) value,
    /// which is bounded from -32,768 to 32,767.
    LowerFlatS16,

    /// Lower a u16 into provided storage given core type(s)
    ///
    /// This function is of the form:
    ///
    /// ```ts
    /// type u32 = number;
    /// (coreVals: u32[], ptr: u32, len: u32) => void;
    /// ```
    ///
    /// In this case, coreVals is expected to contain precisely *one* numerical (u32-equivalent) value,
    /// which is bounded from 0 to 65,535.
    LowerFlatU16,

    /// Lower a s32 into provided storage given core type(s)
    ///
    /// This function is of the form:
    ///
    /// ```ts
    /// type u32 = number;
    /// (coreVals: u32[], ptr: u32, len: u32) => void;
    /// ```
    ///
    /// In this case, coreVals is expected to contain precisely *one* numerical (u32-equivalent) value,
    /// which is bounded from -2,147,483,648 to 2,147,483,647.
    LowerFlatS32,

    /// Lower a u32 into provided storage given core type(s)
    ///
    /// This function is of the form:
    ///
    /// ```ts
    /// type u32 = number;
    /// (coreVals: u32[], ptr: u32, len: u32) => void;
    /// ```
    ///
    /// In this case, coreVals is expected to contain precisely *one* numerical (u32-equivalent) value,
    /// which is bounded from 0 to 4,294,967,295.
    LowerFlatU32,

    /// Lower a s64 into provided storage given core type(s)
    ///
    /// This function is of the form:
    ///
    /// ```ts
    /// type u32 = number;
    /// (coreVals: u32[], ptr: u32, len: u32) => void;
    /// ```
    ///
    /// In this case, coreVals is expected to contain precisely *one* numerical (u32-equivalent) value,
    /// which is bounded from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
    LowerFlatS64,

    /// Lower a u64 into provided storage given core type(s)
    ///
    /// This function is of the form:
    ///
    /// ```ts
    /// type u32 = number;
    /// (coreVals: u32[], ptr: u32, len: u32) => void;
    /// ```
    ///
    /// In this case, coreVals is expected to contain precisely *one* numerical (u32-equivalent) value,
    /// which is bounded from 0 to 18,446,744,073,709,551,615.
    LowerFlatU64,

    /// Lower a f32 into provided storage given core type(s)
    ///
    /// This function is of the form:
    ///
    /// ```ts
    /// type u32 = number;
    /// (coreVals: u32[], ptr: u32, len: u32) => void;
    /// ```
    LowerFlatFloat32,

    /// Lower a f64 into provided storage given core type(s)
    ///
    /// This function is of the form:
    ///
    /// ```ts
    /// type u32 = number;
    /// (coreVals: u32[], ptr: u32, len: u32) => void;
    /// ```
    LowerFlatFloat64,

    /// Lower a char into provided storage given core type(s)
    LowerFlatChar,

    /// Lower a UTF8 string into provided storage given core type(s)
    LowerFlatStringUtf8,

    /// Lower a UTF16 string into provided storage given core type(s)
    LowerFlatStringUtf16,

    /// Lower a record into provided storage given core type(s)
    LowerFlatRecord,

    /// Lower a variant into provided storage given core type(s)
    LowerFlatVariant,

    /// Lower a list into provided storage given core type(s)
    LowerFlatList,

    /// Lower a tuple into provided storage given core type(s)
    LowerFlatTuple,

    /// Lower flags into provided storage given core type(s)
    LowerFlatFlags,

    /// Lower flags into provided storage given core type(s)
    LowerFlatEnum,

    /// Lower an option into provided storage given core type(s)
    LowerFlatOption,

    /// Lower a result into provided storage given core type(s)
    LowerFlatResult,

    /// Lower a owned resource into provided storage given core type(s)
    LowerFlatOwn,

    /// Lower a borrowed resource into provided storage given core type(s)
    LowerFlatBorrow,

    /// Lower a future into provided storage given core type(s)
    LowerFlatFuture,

    /// Lower a stream into provided storage given core type(s)
    LowerFlatStream,

    /// Lower an error-context into provided storage given core type(s)
    LowerFlatErrorContext,
}

impl LowerIntrinsic {
    /// Retrieve dependencies for this intrinsic
    pub fn deps() -> &'static [&'static Intrinsic] {
        &[]
    }

    /// Retrieve global names for
    pub fn get_global_names() -> impl IntoIterator<Item = &'static str> {
        []
    }

    /// Get the name for the intrinsic
    pub fn name(&self) -> &'static str {
        match self {
            Self::LowerFlatBool => "_lowerFlatBool",
            Self::LowerFlatS8 => "_lowerFlatS8",
            Self::LowerFlatU8 => "_lowerFlatU8",
            Self::LowerFlatS16 => "_lowerFlatS16",
            Self::LowerFlatU16 => "_lowerFlatU16",
            Self::LowerFlatS32 => "_lowerFlatS32",
            Self::LowerFlatU32 => "_lowerFlatU32",
            Self::LowerFlatS64 => "_lowerFlatS64",
            Self::LowerFlatU64 => "_lowerFlatU64",
            Self::LowerFlatFloat32 => "_lowerFlatFloat32",
            Self::LowerFlatFloat64 => "_lowerFlatFloat64",
            Self::LowerFlatChar => "_lowerFlatChar",
            Self::LowerFlatStringUtf8 => "_lowerFlatStringUTF8",
            Self::LowerFlatStringUtf16 => "_lowerFlatStringUTF16",
            Self::LowerFlatRecord => "_lowerFlatRecord",
            Self::LowerFlatVariant => "_lowerFlatVariant",
            Self::LowerFlatList => "_lowerFlatList",
            Self::LowerFlatTuple => "_lowerFlatTuple",
            Self::LowerFlatFlags => "_lowerFlatFlags",
            Self::LowerFlatEnum => "_lowerFlatEnum",
            Self::LowerFlatOption => "_lowerFlatOption",
            Self::LowerFlatResult => "_lowerFlatResult",
            Self::LowerFlatOwn => "_lowerFlatOwn",
            Self::LowerFlatBorrow => "_lowerFlatBorrow",
            Self::LowerFlatFuture => "_lowerFlatFuture",
            Self::LowerFlatStream => "_lowerFlatStream",
            Self::LowerFlatErrorContext => "_lowerFlatErrorContext",
        }
    }

    /// Render an intrinsic to a string
    pub fn render(&self, output: &mut Source) {
        match self {
            Self::LowerFlatBool => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatBool(memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatBool()] args', {{ memory, vals, storagePtr, storageLen }});
                        if (vals.length !== 1) {{
                            throw new Error('unexpected number (' + vals.length + ') of core vals (expected 1)');
                        }}
                        if (vals[0] !== 0 && vals[0] !== 1) {{ throw new Error('invalid value for core value representing bool'); }}
                        new DataView(memory.buffer).setUint32(storagePtr, vals[0], true);
                        return 1;
                    }}
                "));
            }

            Self::LowerFlatS8 => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatS8(memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatS8()] args', {{ memory, vals, storagePtr, storageLen }});
                        if (vals.length !== 1) {{
                            throw new Error('unexpected number (' + vals.length + ') of core vals (expected 1)');
                        }}
                        if (vals[0] > 127 || vals[0] < -128) {{ throw new Error('invalid value for core value representing s8'); }}
                        new DataView(memory.buffer).setInt32(storagePtr, vals[0], true);
                        return 8;
                    }}
                "));
            }

            Self::LowerFlatU8 => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!(r#"
                    function _lowerFlatU8(ctx) {{
                        {debug_log_fn}('[_lowerFlatU8()] args', ctx);
                        const {{ memory, realloc, vals, storagePtr, storageLen }} = ctx;
                        if (vals.length !== 1) {{
                            throw new Error('unexpected number (' + vals.length + ') of core vals (expected 1)');
                        }}
                        if (vals[0] > 255 || vals[0] < 0) {{ throw new Error('invalid value for core value representing u8'); }}
                        if (!memory) {{ throw new Error("missing memory for lower"); }}
                        new DataView(memory.buffer).setUint32(storagePtr, vals[0], true);

                        // TODO: ALIGNMENT IS WRONG?

                        return 1;
                    }}
                "#));
            }

            // TODO: alignment checks
            Self::LowerFlatS16 => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatS16(memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatS16()] args', {{ memory, vals, storagePtr, storageLen }});
                        if (vals.length !== 1) {{
                            throw new Error('unexpected number (' + vals.length + ') of core vals (expected 1)');
                        }}
                        if (vals[0] > 32_767 || vals[0] < -32_768) {{ throw new Error('invalid value for core value representing s16'); }}
                        new DataView(memory.buffer).setInt16(storagePtr, vals[0], true);
                        return 2;
                    }}
                "));
            }

            Self::LowerFlatU16 => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatU16(memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatU16()] args', {{ memory, vals, storagePtr, storageLen }});
                        if (vals.length !== 1) {{
                            throw new Error('unexpected number (' + vals.length + ') of core vals (expected 1)');
                        }}
                        if (vals[0] > 65_535 || vals[0] < 0) {{ throw new Error('invalid value for core value representing u16'); }}
                        new DataView(memory.buffer).setUint16(storagePtr, vals[0], true);
                        return 2;
                    }}
                "));
            }

            Self::LowerFlatS32 => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let lower_flat_s32_fn = self.name();
                output.push_str(&format!("
                    function {lower_flat_s32_fn}(ctx) {{
                        {debug_log_fn}('[{lower_flat_s32_fn}()] args', {{ ctx }});
                        const {{ memory, realloc, vals, storagePtr, storageLen }} = ctx;

                        if (vals.length !== 1) {{
                            throw new Error('unexpected number (' + vals.length + ') of core vals (expected 1)');
                        }}
                        if (vals[0] > 2_147_483_647 || vals[0] < -2_147_483_648) {{ throw new Error('invalid value for core value representing s32'); }}

                        // TODO(refactor): fail loudly on misaligned flat lowers?
                        const rem = ctx.storagePtr % 4;
                        if (rem !== 0) {{ ctx.storagePtr += (4 - rem); }}

                        new DataView(memory.buffer).setInt32(storagePtr, vals[0], true);
                        return 4;


                    }}
                "));
            }

            // TODO(fix) can u32s be lowered indirectly? maybe never?
            // discrepancy of indirect values and indirect params (where to get storagePtr/len)
            // to the function versus params that actually indicate where to write!
            Self::LowerFlatU32 => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!(r#"
                    function _lowerFlatU32(ctx) {{
                        {debug_log_fn}('[_lowerFlatU32()] args', {{ ctx }});
                        const {{ memory, realloc, vals, storagePtr, storageLen }} = ctx;
                        if (vals.length !== 1) {{ throw new Error('expected single value to lower, got (' + vals.length + ')'); }}
                        if (vals[0] > 4_294_967_295 || vals[0] < 0) {{ throw new Error('invalid value for core value representing u32'); }}

                        // TODO(refactor): fail loudly on misaligned flat lowers?
                        const rem = ctx.storagePtr % 4;
                        if (rem !== 0) {{ ctx.storagePtr += (4 - rem); }}

                        new DataView(memory.buffer).setUint32(storagePtr, vals[0], true);

                        return 4;
                    }}
                "#));
            }

            Self::LowerFlatS64 => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatS64(memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatS64()] args', {{ memory, vals, storagePtr, storageLen }});
                        if (vals.length !== 1) {{ throw new Error('unexpected number of core vals'); }}
                        if (vals[0] > 9_223_372_036_854_775_807n || vals[0] < -9_223_372_036_854_775_808n) {{ throw new Error('invalid value for core value representing s64'); }}
                        new DataView(memory.buffer).setBigInt64(storagePtr, vals[0], true);
                        return 8;
                    }}
                "));
            }

            Self::LowerFlatU64 => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatU64(memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatU64()] args', {{ memory, vals, storagePtr, storageLen }});
                        if (vals.length !== 1) {{ throw new Error('unexpected number of core vals'); }}
                        if (vals[0] > 18_446_744_073_709_551_615n || vals[0] < 0n) {{ throw new Error('invalid value for core value representing u64'); }}
                        new DataView(memory.buffer).setBigUint64(storagePtr, vals[0], true);
                        return 8;
                    }}
                "));
            }

            Self::LowerFlatFloat32 => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatFloat32(memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatFloat32()] args', {{ memory, vals, storagePtr, storageLen }});
                        if (vals.length !== 1) {{ throw new Error('unexpected number of core vals'); }}
                        new DataView(memory.buffer).setFloat32(storagePtr, vals[0], true);
                        return 4;
                    }}
                "));
            }

            Self::LowerFlatFloat64 => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatFloat64(memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatFloat64()] args', {{ memory, vals, storagePtr, storageLen }});
                        if (vals.length !== 1) {{ throw new Error('unexpected number of core vals'); }}
                        new DataView(memory.buffer).setFloat64(storagePtr, vals[0], true);
                        return 8;
                    }}
                "));
            }

            Self::LowerFlatChar => {
                let i32_to_char_fn = Intrinsic::Conversion(ConversionIntrinsic::I32ToChar).name();
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatChar(memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatChar()] args', {{ memory, vals, storagePtr, storageLen }});
                        if (vals.length !== 1) {{ throw new Error('unexpected number of core vals'); }}
                        new DataView(memory.buffer).setUint32(storagePtr, {i32_to_char_fn}(vals[0]), true);
                        return 4;
                    }}
                "));
            }

            Self::LowerFlatStringUtf16 => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatStringUTF16(memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatStringUTF16()] args', {{ memory, vals, storagePtr, storageLen }});
                        const start = new DataView(memory.buffer).getUint32(storagePtr, vals[0], true);
                        const codeUnits = new DataView(memory.buffer).getUint32(storagePtr, vals[0] + 4, true);
                        var bytes = new Uint16Array(memory.buffer, start, codeUnits);
                        if (memory.buffer.byteLength < start + bytes.byteLength) {{
                            throw new Error('memory out of bounds');
                        }}
                        if (storageLen !== undefined && storageLen !== bytes.byteLength) {{
                            throw new Error('storage length (' + storageLen + ') != (' + bytes.byteLength + ')');
                        }}
                        new Uint16Array(memory.buffer, storagePtr).set(bytes);
                        return bytes.byteLength;
                    }}
                "));
            }

            Self::LowerFlatStringUtf8 => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let utf8_encode_fn = Intrinsic::String(StringIntrinsic::Utf8Encode).name();
                output.push_str(&format!("
                    function _lowerFlatStringUTF8(ctx) {{
                        {debug_log_fn}('[_lowerFlatStringUTF8()] args', ctx);

                        const {{ memory, realloc, vals, storagePtr, storageLen }} = ctx;

                        const s = vals[0];
                        const {{ ptr, len, codepoints }} = {utf8_encode_fn}(vals[0], realloc, memory);

                        const view = new DataView(memory.buffer);
                        view.setUint32(storagePtr, ptr, true);
                        view.setUint32(storagePtr + 4, codepoints, true);

                        return len;
                    }}
                "));
            }

            Self::LowerFlatRecord => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatRecord(fieldMetas) {{
                        return (size, memory, vals, storagePtr, storageLen) => {{
                            const params = [...arguments].slice(5);
                            {debug_log_fn}('[_lowerFlatRecord()] args', {{
                                size,
                                memory,
                                vals,
                                storagePtr,
                                storageLen,
                                params,
                                fieldMetas
                            }});

                            const [start] = vals;
                            if (storageLen !== undefined && size !== undefined && size > storageLen) {{
                                throw new Error('not enough storage remaining for record flat lower');
                            }}
                            const data = new Uint8Array(memory.buffer, start, size);
                            new Uint8Array(memory.buffer, storagePtr, size).set(data);
                            return data.byteLength;
                        }}
                    }}
                "));
            }

            Self::LowerFlatVariant => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let lower_flat_variant_fn = self.name();
                let lower_u8_fn = Self::LowerFlatU8.name();
                let lower_u16_fn = Self::LowerFlatU16.name();
                let lower_u32_fn = Self::LowerFlatU32.name();

                output.push_str(&format!(r#"
                    function {lower_flat_variant_fn}(lowerMetas) {{
                        return function {lower_flat_variant_fn}Inner(ctx) {{
                            {debug_log_fn}('[{lower_flat_variant_fn}()] args', ctx);

                            const {{ memory, realloc, vals, storageLen, componentIdx }} = ctx;
                            let storagePtr = ctx.storagePtr;

                            const {{ tag, val }} = vals[0];
                            const disc = lowerMetas.findIndex(m => m[0] === tag);
                            if (disc === -1) {{
                                throw new Error(`invalid variant tag/discriminant [${{tag}}] (valid tags: ${{variantMetas.map(m => m[0])}})`);
                            }}

                            const [ _tag, lowerFn, size32, align32, payloadOffset32 ] = lowerMetas[disc];

                            const originalPtr = ctx.resultPtr;
                            ctx.vals = [disc];
                            let discLowerRes;
                            if (lowerMetas.length < 256) {{
                                discLowerRes = {lower_u8_fn}(ctx);
                            }} else if (lowerMetas.length >= 256 && lowerMetas.length < 65536) {{
                                discLowerRes = {lower_u16_fn}(ctx);
                            }} else if (lowerMetas.length >= 65536 && lowerMetas.length < 4_294_967_296) {{
                                discLowerRes = {lower_u32_fn}(ctx);
                            }} else {{
                                throw new Error('unsupported number of cases [' + lowerMetas.legnth + ']');
                            }}

                            ctx.resultPtr = originalPtr + payloadOffset32;

                            let payloadBytesWritten = 0;
                            if (lowerFn) {{
                                lowerFn({{
                                    memory,
                                    realloc,
                                    vals: [val],
                                    storagePtr,
                                    storageLen,
                                    componentIdx,
                                }});
                            }}
                            let bytesWritten = payloadOffset + payloadBytesWritten;

                            const rem = ctx.storagePtr % align32;
                            if (rem !== 0) {{
                                const pad = align32 - rem;
                                ctx.storagePtr += pad;
                                bytesWritten += pad;
                            }}

                            return bytesWritten;
                        }}
                    }}
                "#));
            }

            Self::LowerFlatList => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let lower_flat_list_fn = self.name();
                output.push_str(&format!(r#"
                    function {lower_flat_list_fn}(args) {{
                        const {{ elemLowerFn }} = args;
                        if (!elemLowerFn) {{ throw new TypeError("missing/invalid element lower fn for list"); }}

                        return function {lower_flat_list_fn}Inner(ctx) {{
                            {debug_log_fn}('[_lowerFlatList()] args', {{ ctx }});

                            if (ctx.params.length < 2) {{ throw new Error('insufficient params left to lower list'); }}
                            const storagePtr = ctx.params[0];
                            const elemCount = ctx.params[1];
                            ctx.params = ctx.params.slice(2);

                            if (ctx.useDirectParams) {{
                                const list = ctx.vals[0];
                                if (!list) {{ throw new Error("missing direct param value"); }}

                                const elemLowerCtx = {{ storagePtr, memory: ctx.memory }};
                                for (let idx = 0; idx < list.length; idx++) {{
                                    elemLowerCtx.vals = list.slice(idx, idx+1);
                                    elemLowerCtx.storagePtr += elemLowerFn(elemLowerCtx);
                                }}

                                const bytesLowered = elemLowerCtx.storagePtr - ctx.storagePtr;
                                ctx.storagePtr = elemLowerCtx.storagePtr;
                                return bytesLowered;
                            }}

                            if (ctx.vals.length !== 2) {{
                                throw new Error('indirect parameter loading must have a pointer and length as vals');
                            }}
                            let [valStartPtr, valLen] = ctx.vals;
                            const totalSizeBytes = valLen * size;
                            if (ctx.storageLen !== undefined && totalSizeBytes > ctx.storageLen) {{
                                throw new Error('not enough storage remaining for list flat lower');
                            }}

                            const data = new Uint8Array(memory.buffer, valStartPtr, totalSizeBytes);
                            new Uint8Array(memory.buffer, storagePtr, totalSizeBytes).set(data);

                            return totalSizeBytes;
                        }}
                    }}
                "#));
            }

            Self::LowerFlatTuple => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatTuple(size, memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatTuple()] args', {{ size, memory, vals, storagePtr, storageLen }});
                        let [start, len] = vals;
                        if (storageLen !== undefined && len > storageLen) {{
                            throw new Error('not enough storage remaining for tuple flat lower');
                        }}
                        const data = new Uint8Array(memory.buffer, start, len);
                        new Uint8Array(memory.buffer, storagePtr, len).set(data);
                        return data.byteLength;
                    }}
                "));
            }

            Self::LowerFlatFlags => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatFlags(memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatFlags()] args', {{ size, memory, vals, storagePtr, storageLen }});
                        if (vals.length !== 1) {{ throw new Error('unexpected number of core vals'); }}
                        new DataView(memory.buffer).setInt32(storagePtr, vals[0], true);
                        return 4;
                    }}
                "));
            }

            Self::LowerFlatEnum => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatEnum(size, memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatEnum()] args', {{ size, memory, vals, storagePtr, storageLen }});
                        let [start] = vals;
                        if (storageLen !== undefined && size !== undefined && size > storageLen) {{
                            throw new Error('not enough storage remaining for enum flat lower');
                        }}
                        const data = new Uint8Array(memory.buffer, start, size);
                        new Uint8Array(memory.buffer, storagePtr, size).set(data);
                        return data.byteLength;
                    }}
                "));
            }

            Self::LowerFlatOption => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let lower_flat_option_fn = self.name();
                let lower_variant_fn = Self::LowerFlatVariant.name();
                output.push_str(&format!(
                    "
                    function {lower_flat_option_fn}(lowerMetas) {{
                        function {lower_flat_option_fn}Inner(ctx) {{
                            {debug_log_fn}('[{lower_flat_option_fn}()] args', {{ ctx }});
                            return {lower_variant_fn}(lowerMetas)(ctx);
                        }}
                    }}
                "
                ));
            }

            // Results are just a special case of lowering variants
            Self::LowerFlatResult => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let lower_flat_result_fn = self.name();
                let lower_variant_fn = Self::LowerFlatVariant.name();
                output.push_str(&format!(
                    r#"
                    function {lower_flat_result_fn}(lowerMetas) {{
                       return function {lower_flat_result_fn}Inner(ctx) {{
                           {debug_log_fn}('[{lower_flat_result_fn}()] args', {{ lowerMetas }});
                           return {lower_variant_fn}(lowerMetas)(ctx);
                       }};
                    }}
                    "#
                ));
            }

            Self::LowerFlatOwn => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatOwn(size, memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatOwn()] args', {{ size, memory, vals, storagePtr, storageLen }});
                        throw new Error('flat lower for owned resources not yet implemented!');
                    }}
                "));
            }

            Self::LowerFlatBorrow => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatBorrow(size, memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatBorrow()] args', {{ size, memory, vals, storagePtr, storageLen }});
                        throw new Error('flat lower for borrowed resources not yet implemented!');
                    }}
                "));
            }

            Self::LowerFlatFuture => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                output.push_str(&format!("
                    function _lowerFlatFuture(memory, vals, storagePtr, storageLen) {{
                        {debug_log_fn}('[_lowerFlatFuture()] args', {{ size, memory, vals, storagePtr, storageLen }});
                        throw new Error('flat lower for futures not yet implemented!');
                    }}
                "));
            }

            Self::LowerFlatStream => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let global_stream_map = AsyncStreamIntrinsic::GlobalStreamMap.name();
                let external_stream_class = AsyncStreamIntrinsic::ExternalStreamClass.name();
                let internal_stream_class = AsyncStreamIntrinsic::InternalStreamClass.name();

                // TODO: fix writable is getting dropped before it can be read!!
                // We need to do some waiting?
                // Last write should have been triggering the reader to progress...
                // Then the last reads return all the data???

                output.push_str(&format!(
                    r#"
                    function _lowerFlatStream(streamTableIdx, ctx) {{
                        {debug_log_fn}('[_lowerFlatStream()] args', {{ streamTableIdx, ctx }});
                        const {{
                            memory,
                            realloc,
                            vals,
                            storagePtr: resultPtr,
                        }} = ctx;

                        const externalStream = vals[0];
                        if (!externalStream || !(externalStream instanceof {external_stream_class})) {{
                            throw new Error("invalid external stream value");
                        }}

                        const globalRep = externalStream.globalRep();
                        const internalStream = {global_stream_map}.get(globalRep);
                        if (!internalStream || !(internalStream instanceof {internal_stream_class})) {{
                            throw new Error(`failed to find internal stream with rep [${{globalRep}}]`);
                        }}

                        const readEnd = internalStream.readEnd();
                        const waitableIdx = readEnd.waitableIdx();

                        // Write the idx of the waitable to memory (a waiting async task or caller)
                        if (resultPtr) {{
                            new DataView(memory.buffer).setUint32(resultPtr, waitableIdx, true);
                        }}

                        // TODO: if we flat lower another way (host -> guest async) we need to actually
                        // modify the guests table's afresh, we can't just use the global rep!
                        // (can detect this by whether the external stream has a rep or not)

                        return waitableIdx
                    }}
                "#
                ));
            }

            // When a component-model level error context is lowered, it contains the global error-context
            // and not a component-local handle value (as it did pre-lift).
            //
            // By lowering the error context into a given component (w/ a given error context table)
            // we translate the global component model level rep into a local handle.
            //
            // see: `LiftIntrinsic::LiftFlatErrorContext`
            Self::LowerFlatErrorContext => {
                let debug_log_fn = Intrinsic::DebugLog.name();
                let lower_u32_fn = Self::LowerFlatU32.name();
                let create_local_handle_fn = ErrCtxIntrinsic::CreateLocalHandle.name();
                let err_ctx_global_ref_count_add_fn = ErrCtxIntrinsic::GlobalRefCountAdd.name();
                let get_or_create_async_state_fn = ComponentIntrinsic::GetOrCreateAsyncState.name();
                let global_tbl = ErrCtxIntrinsic::ComponentGlobalTable.name();
                let get_local_tbl_fn = ErrCtxIntrinsic::GetLocalTable.name();

                // NOTE: at this point the error context has already been lowered into the appropriate
                // place for us via error context transfer.
                output.push_str(&format!(r#"
                    function _lowerFlatErrorContext(errCtxTableIdx, ctx) {{
                        {debug_log_fn}('[_lowerFlatErrorContext()] args', {{ errCtxTableIdx, ctx }});
                        const {{ memory, realloc, vals, storagePtr, storageLen, componentIdx }} = ctx;

                        const errCtxGlobalRep = vals[0];

                        const globalTable = {global_tbl}.get();
                        const globalErrCtx = globalTable.get(errCtxGlobalRep);

                        // Clean up the previous error context, if necessary
                        const prevComponentState = {get_or_create_async_state_fn}(globalErrCtx.componentIdx);
                        const prevLocalErrCtx = prevComponentState.handles.get(globalErrCtx.waitableIdx);
                        if (prevLocalErrCtx.refCount === 0) {{
                            const removed = prevComponentState.remove(globalErrCtx.waitableIdx);
                            if (!removed) {{
                                throw new Error(`failed to remove err ctx [${{globalErrCtx.waitableIdx}}], component [${{globalErrCtx.componentIdx}}]`);
                            }}
                            const prevLocalErrCtxTable = {get_local_tbl_fn}(globalErrCtx.componentIdx, globalErrCtx.localTableIdx);
                            prevLocalErrCtxTable.remove(globalErrCtx.localIdx)
                        }}

                        // Insert the error context into the destination tables
                        const localErrCtxTable = {get_local_tbl_fn}(componentIdx, errCtxTableIdx, {{ upsert: true }});

                        let handle = localErrCtxTable.get(componentIdx, errCtxTableIdx, );
                        if (handle === undefined) {{
                            const {{ waitableIdx, localIdx }} = {create_local_handle_fn}(
                                componentIdx,
                                localErrCtxTable,
                                errCtxGlobalRep,
                            );
                            handle = waitableIdx;
                        }} else {{
                            const cstate = {get_or_create_async_state_fn}(componentIdx);
                            const localErrCtx = cstate.handles.get(handle);
                            localErrCtx.refCount += 1;
                            localErrCtx.componentIdx = componentIdx;
                            localErrCtx.localIdx = errCtx.localIdx;
                            localErrCtx.localTableIdx = errCtxTableIdx;
                        }}

                        {err_ctx_global_ref_count_add_fn}(errCtxGlobalRep, -1);

                        {lower_u32_fn}({{ memory, realloc, vals: [handle], storagePtr, storageLen, componentIdx }});
                    }}
                "#));
            }
        }
    }
}