hyperlight-component-util 0.18.0

Shared implementation for the procedural macros that generate Hyperlight host and guest bindings from component types
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
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
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
// SPDX-License-Identifier: Apache-2.0
// Copyright 2025 The Hyperlight Authors.

//! The Rust representation of a component type (etype)

use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::vec::Vec;

use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::Ident;

use crate::emit::{
    FnName, ResourceItemName, State, WitName, find_colliding_import_names, import_member_names,
    kebab_to_cons, kebab_to_exports_name, kebab_to_flags_const, kebab_to_fn, kebab_to_getter,
    kebab_to_imports_name, kebab_to_namespace, kebab_to_type, kebab_to_var, split_wit_name,
};
use crate::etypes::{
    self, Component, Defined, ExternDecl, ExternDesc, Func, Handleable, ImportExport, Instance,
    Param, TypeBound, Tyvar, Value,
};

#[derive(Clone, Copy, Debug)]
pub(crate) enum EmitPositivity {
    Same,
    Opposite,
}
impl EmitPositivity {
    fn invert(self) -> Self {
        match self {
            EmitPositivity::Same => EmitPositivity::Opposite,
            EmitPositivity::Opposite => EmitPositivity::Same,
        }
    }
}

/// When referring to an instance or resource trait, emit a token
/// stream that instantiates any types it is parametrized by with our
/// own best understanding of how to name the relevant type variables
fn emit_tvis(s: &mut State, ep: EmitPositivity, tvs: Vec<u32>) -> TokenStream {
    let tvs = tvs
        .iter()
        .map(|tv| emit_var_ref_noff(s, *tv, false))
        .collect::<Vec<_>>();
    let p = s.positivity_param.clone().unwrap_or(quote! { P });
    match ep {
        EmitPositivity::Same => quote! { <#p #(,#tvs)*> },
        EmitPositivity::Opposite => {
            quote! { <<#p as ::hyperlight_common::component::Positivity>::NegativeOfThis #(,#tvs)*> }
        }
    }
}

/// Construct a token stream referencing a trait at a given trait path
pub(crate) fn trait_ref(
    s: &mut State,
    ep: EmitPositivity,
    absolute: bool,
    path: &[Ident],
) -> TokenStream {
    let rp = if absolute {
        s.root_path()
    } else {
        TokenStream::new()
    };
    let t = s.resolve_trait_immut(absolute, path);
    let tvis = emit_tvis(s, ep, t.tv_idxs());
    quote! { #rp #(#path)::* #tvis }
}

/// Emit a token stream that references the type of a particular resource
///
/// - `n`: the absolute index (i.e. ignoring [`State::var_offset`]) of
///   the component tyvar being referenced
/// - `path`: the origin path between the module where we are and the
///   module where the resource is defined.  The existence of this
///   path implies that the var is "locally defined".
fn emit_resource_ref(s: &mut State, n: u32, path: Vec<ImportExport>) -> TokenStream {
    // todo: when the guest codegen is split into generic and wasm,
    // this can go away, since an appropriate impl for the imports
    // trait will be there
    if s.is_guest && s.is_impl {
        // Morally, this should check that the var is imported, but
        // that information is gone by now (in the common prefix of
        // the path that was chopped off), and we won't support
        // resources exported from the guest until this whole special
        // case is gone, so ignore it.
        let id = format_ident!("HostResource{}", n);
        return quote! { #id };
    }
    let Some(resource) = path.last() else {
        panic!("resource reference path must contain the resource type");
    };
    let rtrait = kebab_to_type(resource.name());

    // Deal specially with being in the local instance, where there is
    // no instance type & so it is not easy to resolve the
    // path-from-the-root to the resource type trait in question
    if path.len() == 1 {
        let helper = s.cur_helper_mod.clone().unwrap();
        let rtrait = kebab_to_type(path[0].name());
        let trait_ref = trait_ref(
            s,
            EmitPositivity::Same,
            false,
            &[helper.clone(), rtrait.clone()],
        );
        let mut sv = quote! { Self };
        if let Some(s) = &s.self_param_var {
            sv = quote! { #s };
        };
        return quote! { <#sv as #trait_ref>::T };
    };

    // Generally speaking, the structure that we expect to see in
    // `path` ends in an instance that exports the resource type,
    // followed by the resource type itself.

    let mut toks = quote! { Self };
    if path[0].imported() {
        if let Some(iv) = &s.import_param_var {
            toks = quote! { #iv }
        }
    } else if let Some(s) = &s.self_param_var {
        toks = quote! { #s }
    }
    // todo: this will need a bit of adjustment to work well with
    // plainname externs, which may require keeping track of the last
    // interfacename we saw
    let mut ep = EmitPositivity::Same;
    for (i, p) in path[0..path.len() - 1].iter().enumerate() {
        // Don't update ep if the import is the first item on the path
        // and we don't have a var pointing at a different imports
        // trait instance, since that means we are in an `Imports`
        // trait, and our `P` has already been negative'd.
        if p.imported() && (i != 0 || s.import_param_var.is_some()) {
            ep = ep.invert();
        }
        let iwn = split_wit_name(p.name());
        let export_name = if p.imported() {
            import_member_names(&iwn, &s.colliding_import_names).0
        } else {
            kebab_to_type(iwn.name)
        };

        // The final item in the path will be referring to the
        // relevant resource trait, while the others will be referring
        // instance traits on the way there. So, we need to treat them
        // separately.
        let namespace_suffix = if i == path.len() - 2 {
            &[kebab_to_namespace(iwn.name), rtrait.clone()] as &[Ident]
        } else {
            &[kebab_to_type(iwn.name)] as &[Ident]
        };
        let trait_path = iwn
            .namespace_idents()
            .iter()
            .chain(namespace_suffix.iter())
            .cloned()
            .collect::<Vec<_>>();
        let trait_ref = trait_ref(s, ep, true, &trait_path);

        toks = quote! { <#toks::#export_name as #trait_ref> };
    }
    quote! { #toks::T }
}

/// Try to find a way to refer to the given type variable from the
/// current module/trait. If this fails, the type must be coming from
/// a sibling package, so we will have to emit a parametrization that
/// the root (or at least someone higher up the tree) can instantiate.
/// - `n`: the absolute index (i.e. ignoring [`State::var_offset`]) of
///   the component tyvar being referenced
fn try_find_local_var_id(
    s: &mut State,
    // this should be an absolute var number (no noff)
    n: u32,
) -> Option<TokenStream> {
    if let Some((path, bound)) = s.is_noff_var_local(n) {
        let var_is_helper = match bound {
            TypeBound::Eq(_) => true,
            TypeBound::SubResource => false,
        };
        if !var_is_helper {
            // it is a resource type
            if s.is_helper {
                // but we're in that resource type, so that's ok
                if path.len() == 1 && s.cur_trait == Some(kebab_to_type(path[0].name())) {
                    return Some(quote! { Self::T });
                }
                // otherwise, there is no way to reference that from here
                return None;
            } else {
                let mut path_strs = vec!["".to_string(); path.len()];
                for (i, p) in path.iter().enumerate() {
                    path_strs[i] = p.name().to_string();
                }
                let path = path
                    .into_iter()
                    .enumerate()
                    .map(|(i, p)| match p {
                        ImportExport::Import(_) => ImportExport::Import(&path_strs[i]),
                        ImportExport::Export(_) => ImportExport::Export(&path_strs[i]),
                    })
                    .collect::<Vec<_>>();
                return Some(emit_resource_ref(s, n, path));
            }
        }
        tracing::debug!("path is {:?}\n", path);
        let mut path = path.iter().rev();
        let name = kebab_to_type(path.next().unwrap().name());
        let owner = path.next();
        if let Some(owner) = owner {
            // if we have an instance type, use it
            let wn = split_wit_name(owner.name());
            let rp = s.root_path();
            let tns = wn.namespace_path();
            let helper = kebab_to_namespace(wn.name);
            if tns.is_empty() {
                Some(quote! { #rp #helper::#name })
            } else {
                Some(quote! { #rp #tns::#helper::#name })
            }
        } else {
            let hp = s.helper_path();
            Some(quote! { #hp #name })
        }
    } else {
        None
    }
}

/// Emit a token stream that references the given type variable in a
/// type context, either directly if it is locally defined or by
/// adding a parameter to the current type/trait/etc if necessary.
/// - `tv`: the variable to reference
///
/// Precondition: `tv` must be a [`Tyvar::Bound`] tyvar
pub fn emit_var_ref(s: &mut State, tv: &Tyvar) -> TokenStream {
    let Tyvar::Bound(n) = tv else {
        panic!("free tyvar in rust emit")
    };
    emit_var_ref_noff(s, n + s.var_offset as u32, false)
}
/// Emit a token stream that references the given type variable in a
/// value context (e.g. a constructor), either directly if it is
/// locally defined or by adding a parameter to the current
/// type/trait/etc if necessary.
/// - `tv`: the variable to reference
///
/// Precondition: `tv` must be a [`Tyvar::Bound`] tyvar
pub fn emit_var_ref_value(s: &mut State, tv: &Tyvar) -> TokenStream {
    let Tyvar::Bound(n) = tv else {
        panic!("free tyvar in rust emit")
    };
    emit_var_ref_noff(s, n + s.var_offset as u32, true)
}
/// Emit a token stream that references the given bound type variable,
/// either directly if it is locally defined or by adding a parameter
/// to the current type/trait/etc if necessary.
/// - `n`: the absolute index (i.e. ignoring [`State::var_offset`]) of
///   the bound variable being referenced
/// - `is_value`: whether this is a value (e.g. constructor) or type context.
pub fn emit_var_ref_noff(s: &mut State, n: u32, is_value: bool) -> TokenStream {
    tracing::debug!("var_ref {:?} {:?}", &s.bound_vars[n as usize], s.origin);
    // if the variable was defined locally, try to reference it directly
    let id = try_find_local_var_id(s, n);
    let id = match id {
        Some(id) => {
            // if we are referencing the local one, we need to give it
            // the variables it wants
            let vs = s.get_noff_var_refs(n);
            let vs = vs
                .iter()
                .map(|n| emit_var_ref_noff(s, *n, false))
                .collect::<Vec<_>>();
            let vs_toks = if !vs.is_empty() {
                if is_value {
                    quote! { ::<#(#vs),*> }
                } else {
                    quote! { <#(#vs),*> }
                }
            } else {
                TokenStream::new()
            };

            quote! { #id #vs_toks }
        }
        None => {
            // otherwise, record that whatever type is referencing it needs to
            // have it in scope
            s.need_noff_var(n);
            let id = s.noff_var_id(n);
            quote! { #id }
        }
    };
    quote! { #id }
}

/// Format the name of the rust type corresponding to a component
/// numeric type.
///
/// Precondition: `vt` is a numeric type (`S`, `U`, `F`)
pub fn numeric_rtype(vt: &Value) -> (Ident, u8) {
    match vt {
        Value::S(w) => (format_ident!("i{}", w.width()), w.width()),
        Value::U(w) => (format_ident!("u{}", w.width()), w.width()),
        Value::F(w) => (format_ident!("f{}", w.width()), w.width()),
        _ => panic!("numeric_rtype: internal invariant violation"),
    }
}

/// Emit a Rust type corresponding to a given value type. The
/// resultant token stream will parse as a Rust type.
///
/// Precondition: `vt` is an inline-able value type.
pub fn emit_value(s: &mut State, vt: &Value) -> TokenStream {
    match vt {
        Value::Bool => quote! { bool },
        Value::S(_) | Value::U(_) | Value::F(_) => {
            let (id, _) = numeric_rtype(vt);
            quote! { #id }
        }
        Value::Char => quote! { char },
        Value::String => quote! { alloc::string::String },
        Value::List(vt) => {
            let vt = emit_value(s, vt);
            quote! { alloc::vec::Vec<#vt> }
        }
        Value::FixList(vt, size) => {
            let vt = emit_value(s, vt);
            let size = *size as usize;
            quote! { [#vt; #size] }
        }
        Value::Record(_) => panic!("record not at top level of valtype"),
        Value::Tuple(vts) => {
            let vts = vts.iter().map(|vt| emit_value(s, vt)).collect::<Vec<_>>();
            quote! { (#(#vts),*) }
        }
        Value::Flags(_) => panic!("flags not at top level of valtype"),
        Value::Variant(_) => panic!("flags not at top level of valtype"),
        Value::Enum(_) => panic!("enum not at top level of valtype"),
        Value::Option(vt) => {
            let vt = emit_value(s, vt);
            quote! { ::core::option::Option<#vt> }
        }
        Value::Result(vt1, vt2) => {
            let unit = Value::Tuple(Vec::new());
            let vt1 = emit_value(s, vt1.as_ref().as_ref().unwrap_or(&unit));
            let vt2 = emit_value(s, vt2.as_ref().as_ref().unwrap_or(&unit));
            quote! { ::core::result::Result<#vt1, #vt2> }
        }
        Value::Own(ht) => match ht {
            Handleable::Resource(_) => panic!("bare resource in type"),
            Handleable::Var(tv) => {
                if s.is_guest {
                    let wrap = if s.is_wasmtime_guest {
                        |toks| quote! { ::wasmtime::component::Resource<#toks> }
                    } else {
                        |toks| toks
                    };
                    if !s.is_impl {
                        wrap(emit_var_ref(s, tv))
                    } else {
                        let n = crate::hl::resolve_handleable_to_resource(s, ht);
                        tracing::debug!("resolved ht to r (4) {:?} {:?}", ht, n);
                        let id = format_ident!("HostResource{}", n);
                        wrap(quote! { #id })
                    }
                } else {
                    emit_var_ref(s, tv)
                }
            }
        },
        Value::Borrow(ht) => match ht {
            Handleable::Resource(_) => panic!("bare resource in type"),
            Handleable::Var(tv) => {
                if s.is_guest {
                    let wrap = if s.is_wasmtime_guest {
                        |toks| quote! { ::wasmtime::component::Resource<#toks> }
                    } else {
                        |toks| quote! { &#toks }
                    };
                    if !s.is_impl {
                        wrap(emit_var_ref(s, tv))
                    } else {
                        let n = crate::hl::resolve_handleable_to_resource(s, ht);
                        tracing::debug!("resolved ht to r (5) {:?} {:?}", ht, n);
                        let id = format_ident!("HostResource{}", n);
                        wrap(quote! { #id })
                    }
                } else {
                    let vr = emit_var_ref(s, tv);
                    let p = s.positivity_param.clone().unwrap_or(quote! { P });
                    quote! { <#p as ::hyperlight_common::component::Positivity>::Borrow<'_, #vr> }
                }
            }
        },
        Value::Var(Some(tv), _) => emit_var_ref(s, tv),
        Value::Var(None, _) => panic!("value type with recorded but unknown var"),
    }
}

/// Emit a Rust type corresponding to a given toplevel value type. The
/// resultant token stream will parse as a Rust type declaration that
/// defines a type named `id`.
fn emit_value_toplevel(s: &mut State, v: Option<u32>, id: Ident, vt: &Value) -> TokenStream {
    let is_wasmtime_guest = s.is_wasmtime_guest;
    match vt {
        Value::Record(rfs) => {
            let (vs, toks) = gather_needed_vars(s, v, |s| {
                let rfs = rfs
                    .iter()
                    .map(|rf| {
                        let orig_name = rf.name.name;
                        let id = kebab_to_var(orig_name);
                        let derives = if s.is_wasmtime_guest {
                            quote! { #[component(name = #orig_name)] }
                        } else {
                            TokenStream::new()
                        };
                        let ty = emit_value(s, &rf.ty);
                        quote! { #derives pub #id: #ty }
                    })
                    .collect::<Vec<_>>();
                quote! { #(#rfs),* }
            });
            let vs = emit_type_defn_var_list(s, vs);
            let derives = if s.is_wasmtime_guest {
                quote! {
                    #[derive(::wasmtime::component::ComponentType)]
                    #[derive(::wasmtime::component::Lift)]
                    #[derive(::wasmtime::component::Lower)]
                    #[component(record)]
                }
            } else {
                TokenStream::new()
            };
            quote! {
                #derives
                #[derive(Debug)]
                pub struct #id #vs { #toks }
            }
        }
        Value::Flags(ns) => {
            if s.is_wasmtime_guest {
                let flags = ns
                    .iter()
                    .map(|n| {
                        let orig_name = n.name;
                        let const_name = kebab_to_flags_const(orig_name);
                        quote! {
                            #[component(name = #orig_name)]
                            const #const_name;
                        }
                    })
                    .collect::<Vec<_>>();
                quote! {
                    ::wasmtime::component::flags! {
                        #id {
                            #(#flags)*
                        }
                    }
                }
            } else {
                let (vs, toks) = gather_needed_vars(s, v, |_| {
                    let ns = ns
                        .iter()
                        .map(|n| {
                            let id = kebab_to_var(n.name);
                            quote! { pub #id: bool }
                        })
                        .collect::<Vec<_>>();
                    quote! { #(#ns),* }
                });
                let vs = emit_type_defn_var_list(s, vs);
                quote! {
                    #[derive(Debug, Clone, PartialEq)]
                    pub struct #id #vs { #toks }
                }
            }
        }
        Value::Variant(vcs) => {
            let (vs, toks) = gather_needed_vars(s, v, |s| {
                let vcs = vcs
                    .iter()
                    .map(|vc| {
                        let orig_name = vc.name.name;
                        let id = kebab_to_cons(orig_name);
                        let derives = if s.is_wasmtime_guest {
                            quote! { #[component(name = #orig_name)] }
                        } else {
                            TokenStream::new()
                        };
                        match &vc.ty {
                            Some(ty) => {
                                let ty = emit_value(s, ty);
                                quote! { #derives #id(#ty) }
                            }
                            None => quote! { #derives #id },
                        }
                    })
                    .collect::<Vec<_>>();
                quote! { #(#vcs),* }
            });
            let vs = emit_type_defn_var_list(s, vs);
            let derives = if s.is_wasmtime_guest {
                quote! {
                    #[derive(::wasmtime::component::ComponentType)]
                    #[derive(::wasmtime::component::Lift)]
                    #[derive(::wasmtime::component::Lower)]
                    #[component(variant)]
                }
            } else {
                TokenStream::new()
            };
            quote! {
                #derives
                #[derive(Debug)]
                pub enum #id #vs { #toks }
            }
        }
        Value::Enum(ns) => {
            let (vs, toks) = gather_needed_vars(s, v, |_| {
                let ns = ns
                    .iter()
                    .map(|n| {
                        let orig_name = n.name;
                        let id = kebab_to_cons(orig_name);
                        let derives = if is_wasmtime_guest {
                            quote! { #[component(name = #orig_name)] }
                        } else {
                            TokenStream::new()
                        };
                        quote! { #derives #id }
                    })
                    .collect::<Vec<_>>();
                quote! { #(#ns),* }
            });
            let vs = emit_type_defn_var_list(s, vs);
            let derives = if s.is_wasmtime_guest {
                quote! {
                    #[derive(::wasmtime::component::ComponentType)]
                    #[derive(::wasmtime::component::Lift)]
                    #[derive(::wasmtime::component::Lower)]
                    #[component(enum)]
                    #[repr(u8)] // todo: should this always be u8?
                }
            } else {
                TokenStream::new()
            };
            quote! {
                #derives
                #[derive(Debug, Copy, Clone, PartialEq)]
                pub enum #id #vs { #toks }
            }
        }
        _ => emit_type_alias(s, v, id, |s| emit_value(s, vt)),
    }
}

/// Emit a Rust type corresponding to a defined type. The token stream
/// will parse as a Rust type declaration that defines a type named `id`.
///
/// Precondition: `dt` is not an instance or component, which we
/// cannot deal with as first-class at the moment, or a bare resource
/// type.
fn emit_defined(s: &mut State, v: Option<u32>, id: Ident, dt: &Defined) -> TokenStream {
    match dt {
        // the lack of trait aliases makes emitting a name for an
        // instance/component difficult in rust
        Defined::Instance(_) | Defined::Component(_) => TokenStream::new(),
        // toplevel vars should have been handled elsewhere
        Defined::Handleable(Handleable::Resource(_)) => panic!("bare resource in type"),
        Defined::Handleable(Handleable::Var(tv)) => {
            emit_type_alias(s, v, id, |s| emit_var_ref(s, tv))
        }
        Defined::Value(vt) => emit_value_toplevel(s, v, id, vt),
        Defined::Func(ft) => emit_type_alias(s, v, id, |s| emit_func(s, ft)),
    }
}

/// Emit a Rust argument declaration, suitable for placing in the
/// argument list of a function, for a given component function type
/// parameter.
pub fn emit_func_param(s: &mut State, p: &Param) -> TokenStream {
    let name = kebab_to_var(p.name.name);
    let ty = emit_value(s, &p.ty);
    quote! { #name: #ty }
}

/// Emit a Rust version of a component function return type.
///
/// Precondition: the result type must only be a named result if there
/// are no names in it (i.e. a unit type)
pub fn emit_func_result(s: &mut State, r: &etypes::Result<'_>) -> TokenStream {
    let inner = match r {
        Some(vt) => emit_value(s, vt),
        None => quote! { () },
    };
    let p = s.positivity_param.clone().unwrap_or(quote! { P });
    quote! { <#p as ::hyperlight_common::component::Positivity>::CallResult<#inner> }
}

/// Emit a Rust typeversion of a component function type. This is only
/// used for defining certain type aliases of functions, and so it
/// truly is a Rust type-level function type, not a value-level
/// declaration.
fn emit_func(s: &mut State, ft: &Func) -> TokenStream {
    let params = ft
        .params
        .iter()
        .map(|p| emit_func_param(s, p))
        .collect::<Vec<_>>();
    let result = emit_func_result(s, &ft.result);
    quote! { fn(#(#params),*) -> #result }
}

/// Gather the vars that are referenced when running `f`. If `v` is
/// [`Some(vn)`], also record this as the set of vars needed by the
/// bound tyvar with absolute index `vn`.
fn gather_needed_vars<F: Fn(&mut State) -> TokenStream>(
    s: &mut State,
    v: Option<u32>,
    f: F,
) -> (BTreeSet<u32>, TokenStream) {
    let mut needs_vars = BTreeSet::new();
    let mut sv = s.with_needs_vars(&mut needs_vars);
    let toks = f(&mut sv);
    if let Some(vn) = v {
        sv.record_needs_vars(vn);
    }
    drop(sv);
    (needs_vars, toks)
}
/// Emit a Rust type parameter list that can be affixed to a type
/// definition, given a set `vs` of the component-level bound tyvars
/// that the type references but are not locally-defined.
fn emit_type_defn_var_list(s: &mut State, vs: BTreeSet<u32>) -> TokenStream {
    if vs.is_empty() {
        TokenStream::new()
    } else {
        let vs = vs
            .iter()
            .map(|n| {
                if s.is_guest {
                    let t = s.noff_var_id(*n);
                    quote! { #t: 'static }
                } else {
                    let t = s.noff_var_id(*n);
                    quote! { #t }
                }
            })
            .collect::<Vec<_>>();
        quote! { <#(#vs),*> }
    }
}
/// Emit a type alias declaration, allowing one to name an anonymous
/// Rust type without creating a new nominal type.
///
/// - `v`: If [`Some(vn)`], the component-level bound tyvar absolute
///   index that this declaration corresponds to
/// - `id`: The name of the alias to produce
/// - `f`: A function which produces a token stream that parses as a
///   Rust type, to use as the body of the alias
fn emit_type_alias<F: Fn(&mut State) -> TokenStream>(
    s: &mut State,
    v: Option<u32>,
    id: Ident,
    f: F,
) -> TokenStream {
    let (vs, toks) = gather_needed_vars(s, v, f);
    let vs = emit_type_defn_var_list(s, vs);
    quote! { pub type #id #vs = #toks; }
}

/// Emit (via returning) a Rust trait item corresponding to this
/// extern decl
fn emit_extern_decl<'a, 'b, 'c>(
    origin_was_export: bool,
    s: &'c mut State<'a, 'b>,
    ed: &'c ExternDecl<'b>,
) -> TokenStream {
    tracing::debug!("  emitting decl {:?}", ed.kebab_name);
    match &ed.desc {
        ExternDesc::CoreModule(_) => panic!("core module (im/ex)ports are not supported"),
        ExternDesc::Func(ft) => {
            let mut s = s.push_origin(origin_was_export, ed.kebab_name);
            match kebab_to_fn(ed.kebab_name) {
                FnName::Plain(n) => {
                    let params = ft
                        .params
                        .iter()
                        .map(|p| emit_func_param(&mut s, p))
                        .collect::<Vec<_>>();
                    let result = emit_func_result(&mut s, &ft.result);
                    quote! {
                        fn #n(&mut self, #(#params),*) -> #result;
                    }
                }
                FnName::Associated(r, n) => {
                    let mut s = s.helper();
                    s.cur_trait = Some(r.clone());
                    let mut needs_vars = BTreeSet::new();
                    let mut sv = s.with_needs_vars(&mut needs_vars);
                    let params = ft
                        .params
                        .iter()
                        .map(|p| emit_func_param(&mut sv, p))
                        .collect::<Vec<_>>();
                    match n {
                        ResourceItemName::Constructor => {
                            sv.cur_trait().items.extend(quote! {
                                fn new(&mut self, #(#params),*) -> Self::T;
                            });
                        }
                        ResourceItemName::Method(n) => {
                            let result = emit_func_result(&mut sv, &ft.result);
                            sv.cur_trait().items.extend(quote! {
                                fn #n(&mut self, #(#params),*) -> #result;
                            });
                        }
                        ResourceItemName::Static(n) => {
                            let result = emit_func_result(&mut sv, &ft.result);
                            sv.cur_trait().items.extend(quote! {
                                fn #n(&mut self, #(#params),*) -> #result;
                            });
                        }
                    }
                    for v in needs_vars {
                        let id = s.noff_var_id(v);
                        s.cur_trait().tvs.insert(id, (Some(v), TokenStream::new()));
                    }
                    quote! {}
                }
            }
        }
        ExternDesc::Type(t) => {
            fn go_defined<'a, 'b, 'c>(
                s: &'c mut State<'a, 'b>,
                ed: &'c ExternDecl<'b>,
                t: &'c Defined<'b>,
                v: Option<u32>,
            ) -> TokenStream {
                let id = kebab_to_type(ed.kebab_name);
                let mut s = s.helper();

                let t = emit_defined(&mut s, v, id, t);
                s.cur_mod().items.extend(t);
                TokenStream::new()
            }
            let edn: &'b str = ed.kebab_name;
            let mut s: State<'_, 'b> = s.push_origin(origin_was_export, edn);
            if let Some((n, bound)) = s.is_var_defn(t) {
                match bound {
                    TypeBound::Eq(t) => {
                        // ensure that when go_defined() looks up vars
                        // that might occur in the type, they resolve
                        // properly
                        let noff = s.var_offset as u32 + n;
                        s.var_offset += n as usize + 1;
                        go_defined(&mut s, ed, &t, Some(noff))
                    }
                    TypeBound::SubResource => {
                        let rn = kebab_to_type(ed.kebab_name);
                        s.add_helper_supertrait(rn.clone());
                        let mut s = s.helper();
                        s.cur_trait = Some(rn.clone());
                        s.cur_trait().items.extend(quote! {
                            type T: ::core::marker::Send;
                        });
                        quote! {}
                    }
                }
            } else {
                go_defined(&mut s, ed, t, None)
            }
        }
        ExternDesc::Instance(it) => {
            let mut s = s.push_origin(origin_was_export, ed.kebab_name);
            let wn = split_wit_name(ed.kebab_name);
            emit_instance(&mut s, wn.clone(), it);

            let (member_tn, member_getter) = if origin_was_export {
                (kebab_to_type(wn.name), kebab_to_getter(wn.name))
            } else {
                import_member_names(&wn, &s.colliding_import_names)
            };
            let trait_path = wn
                .namespace_idents()
                .iter()
                .chain(&[kebab_to_type(wn.name)])
                .cloned()
                .collect::<Vec<_>>();
            let trait_ref = trait_ref(&mut s, EmitPositivity::Same, true, &trait_path);
            quote! {
                type #member_tn: #trait_ref;
                fn #member_getter(&mut self) -> impl ::core::borrow::BorrowMut<Self::#member_tn>;
            }
        }
        ExternDesc::Component(_) => {
            panic!("nested components not yet supported in rust bindings");
        }
    }
}

/// Emit (via mutating `s`) a Rust trait declaration corresponding to
/// this instance type
fn emit_instance<'a, 'b, 'c>(s: &'c mut State<'a, 'b>, wn: WitName, it: &'c Instance<'b>) {
    tracing::debug!("emitting instance {:?}", wn);
    let mut s = s.with_cursor(wn.namespace_idents());

    let name = kebab_to_type(wn.name);

    s.cur_helper_mod = Some(kebab_to_namespace(wn.name));
    s.cur_trait = Some(name.clone());

    // Temporary hack: if some items have already been generated for
    // this wit:package/instance, implying that we have visited it
    // before, we use [`State::for_var_effects_only`] to avoid adding
    // duplicates of everything. We still bother running it, instead
    // of bailing out entirely, to, as the name implies, get the
    // effects on the variable tracking---otherwise the "second copy"
    // of some Eq-bounded type variables will not properly acquire
    // dependency tracking information.
    //
    // Since we don't really have strong semantic guarantees that the
    // exact same contents will be in each occurrence of a
    // wit:package/instance (and indeed they may well be stripped down
    // to the essentials in each occurrence), this is NOT sound, and
    // will need to be revisited. The really proper approach here is
    // probably to properly spec some unification/principle type at
    // the component level and preemptively run it on everything with
    // the same extern name.
    fn run_normally<'a, 'b, 'c>(
        s: &'c mut State<'a, 'b>,
        f: impl for<'d> FnOnce(&mut State<'d, 'b>),
    ) {
        f(s)
    }
    fn run_for_var_effects_only<'a, 'b, 'c>(
        s: &'c mut State<'a, 'b>,
        f: impl for<'d> FnOnce(&mut State<'d, 'b>),
    ) {
        s.for_var_effects_only(f)
    }
    let run = if s.cur_trait().items.is_empty() {
        run_normally
    } else {
        run_for_var_effects_only
    };
    run(&mut s, &mut |s: &mut State<'_, 'b>| {
        let mut needs_vars = BTreeSet::new();
        let mut sv = s.with_needs_vars(&mut needs_vars);

        let exports = it
            .exports
            .iter()
            .map(|ed| emit_extern_decl(true, &mut sv, ed))
            .collect::<Vec<_>>();

        // instantiations for the supertraits

        let mut stvs = BTreeMap::new();
        let _ = sv.cur_trait(); // make sure it exists
        let t = sv.cur_trait_immut();
        for (ti, _) in t.supertraits.iter() {
            let t = sv.resolve_trait_immut(false, ti);
            stvs.insert(ti.clone(), t.tv_idxs());
        }
        // hack to make the local-definedness check work properly, since
        // it usually should ignore the last origin component
        sv.origin.push(ImportExport::Export("self"));
        let mut stis = BTreeMap::new();
        for (id, tvs) in stvs.into_iter() {
            stis.insert(id, emit_tvis(&mut sv, EmitPositivity::Same, tvs));
        }
        for (id, ts) in stis.into_iter() {
            sv.cur_trait().supertraits.get_mut(&id).unwrap().extend(ts);
        }

        drop(sv);
        tracing::debug!("after exports, ncur_needs_vars is {:?}", needs_vars);
        for v in needs_vars {
            let id = s.noff_var_id(v);
            s.cur_trait().tvs.insert(id, (Some(v), TokenStream::new()));
        }

        s.cur_trait().items.extend(quote! { #(#exports)* });
    });
}

/// Emit (via mutating `s`) a set of Rust trait declarations
/// corresponding to this component. This includes an `Imports` and an
/// `Exports` trait, as well as a main trait with an `instantiate()`
/// function that maps from an implementer of the imports to an
/// implementor of the exports
fn emit_component<'a, 'b, 'c>(s: &'c mut State<'a, 'b>, wn: WitName, ct: &'c Component<'b>) {
    let mut s = s.with_cursor(wn.namespace_idents());

    let base_name = kebab_to_type(wn.name);

    s.cur_helper_mod = Some(kebab_to_namespace(wn.name));

    let import_name = kebab_to_imports_name(wn.name);
    *s.bound_vars = ct
        .uvars
        .iter()
        .rev()
        .map(Clone::clone)
        .collect::<VecDeque<_>>();
    s.cur_trait = Some(import_name.clone());
    s.colliding_import_names = find_colliding_import_names(&ct.imports);
    let imports = ct
        .imports
        .iter()
        .map(|ed| emit_extern_decl(false, &mut s, ed))
        .collect::<Vec<TokenStream>>();
    s.cur_trait().items.extend(quote! { #(#imports)* });

    s.adjust_vars(ct.instance.evars.len() as u32);
    s.import_param_var = Some(format_ident!("I"));

    let export_name = kebab_to_exports_name(wn.name);
    *s.bound_vars = ct
        .instance
        .evars
        .iter()
        .rev()
        .chain(ct.uvars.iter().rev())
        .map(Clone::clone)
        .collect::<VecDeque<_>>();
    s.cur_trait = Some(export_name.clone());
    let exports = ct
        .instance
        .unqualified
        .exports
        .iter()
        .map(|ed| emit_extern_decl(true, &mut s, ed))
        .collect::<Vec<_>>();
    s.cur_trait().tvs.insert(
        format_ident!("I"),
        (
            None,
            quote! { #import_name<P::NegativeOfThis> + ::core::marker::Send },
        ),
    );
    s.cur_trait().items.extend(quote! { #(#exports)* });

    s.cur_helper_mod = None;
    s.cur_trait = None;

    s.cur_mod().items.extend(quote! {
        pub trait #base_name<P: ::hyperlight_common::component::Positivity> {
            type Exports<I: #import_name<P::NegativeOfThis> + ::core::marker::Send>: #export_name<P, I>;
            // todo: can/should this 'static bound be avoided?
            // it is important right now because this is closed over in host functions
            fn instantiate<I: #import_name<P::NegativeOfThis> + ::core::marker::Send + 'static>(self, imports: I) -> <P as ::hyperlight_common::component::Positivity>::CallResult<Self::Exports<I>>;
        }
    });
}

/// See [`emit_component`]
pub fn emit_toplevel<'a, 'b, 'c>(s: &'c mut State<'a, 'b>, n: &str, ct: &'c Component<'b>) {
    let wn = split_wit_name(n);
    emit_component(s, wn, ct);
}