wit_bindgen_wrpc_rust/
lib.rs

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
use crate::interface::InterfaceGenerator;
use anyhow::{bail, Result};
use heck::{ToSnakeCase, ToUpperCamelCase};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt::{self, Write as _};
use std::mem;
use wit_bindgen_core::wit_parser::{
    Flags, FlagsRepr, Function, Int, InterfaceId, Resolve, SizeAlign, TypeId, World, WorldId,
    WorldItem, WorldKey,
};
use wit_bindgen_core::{
    name_package_module, uwrite, uwriteln, Files, InterfaceGenerator as _, Source, Types,
    WorldGenerator,
};

mod interface;

struct InterfaceName {
    /// True when this interface name has been remapped through the use of `with` in the `bindgen!`
    /// macro invocation.
    remapped: bool,

    /// The string name for this interface.
    path: String,
}

#[derive(Default)]
struct RustWrpc {
    types: Types,
    src: Source,
    opts: Opts,
    import_modules: Vec<(String, Vec<String>)>,
    export_modules: Vec<(String, Vec<String>)>,
    skip: HashSet<String>,
    interface_names: HashMap<InterfaceId, InterfaceName>,
    import_funcs_called: bool,
    with_name_counter: usize,
    // Track which interfaces were generated. Remapped interfaces provided via `with`
    // are required to be used.
    generated_interfaces: HashSet<String>,
    world: Option<WorldId>,

    export_paths: Vec<String>,
    /// Interface names to how they should be generated
    with: GenerationConfiguration,
}

#[derive(Default)]
struct GenerationConfiguration {
    map: HashMap<String, InterfaceGeneration>,
    generate_by_default: bool,
}

impl GenerationConfiguration {
    fn get(&self, key: &str) -> Option<&InterfaceGeneration> {
        self.map.get(key).or_else(|| {
            self.generate_by_default
                .then_some(&InterfaceGeneration::Generate)
        })
    }

    fn insert(&mut self, name: String, generate: InterfaceGeneration) {
        self.map.insert(name, generate);
    }

    fn iter(&self) -> impl Iterator<Item = (&String, &InterfaceGeneration)> {
        self.map.iter()
    }
}

/// How an interface should be generated.
enum InterfaceGeneration {
    /// Remapped to some other type
    Remap(String),
    /// Generate the interface
    Generate,
}

#[cfg(feature = "clap")]
fn parse_with(s: &str) -> Result<(String, WithOption), String> {
    let (k, v) = s.split_once('=').ok_or_else(|| {
        format!("expected string of form `<key>=<value>[,<key>=<value>...]`; got `{s}`")
    })?;
    let v = match v {
        "generate" => WithOption::Generate,
        other => WithOption::Path(other.to_string()),
    };
    Ok((k.to_string(), v))
}

#[derive(Default, Debug, Clone)]
#[cfg_attr(feature = "clap", derive(clap::Args))]
pub struct Opts {
    /// Whether or not a formatter is executed to format generated code.
    #[cfg_attr(feature = "clap", arg(long))]
    pub format: bool,

    /// Names of functions to skip generating bindings for.
    #[cfg_attr(feature = "clap", arg(long))]
    pub skip: Vec<String>,

    /// The optional path to the bitflags crate to use.
    ///
    /// This defaults to `wit_bindgen_wrpc::bitflags`.
    #[cfg_attr(feature = "clap", arg(long))]
    pub bitflags_path: Option<String>,

    /// Additional derive attributes to add to generated types. If using in a CLI, this flag can be
    /// specified multiple times to add multiple attributes.
    ///
    /// These derive attributes will be added to any generated structs or enums
    #[cfg_attr(feature = "clap", arg(long = "additional_derive_attribute", short = 'd', default_values_t = Vec::<String>::new()))]
    pub additional_derive_attributes: Vec<String>,

    /// Remapping of interface names to rust module names.
    ///
    /// Argument must be of the form `k=v` and this option can be passed
    /// multiple times or one option can be comma separated, for example
    /// `k1=v1,k2=v2`.
    #[cfg_attr(feature = "clap", arg(long, value_parser = parse_with, value_delimiter = ','))]
    pub with: Vec<(String, WithOption)>,

    /// Indicates that all interfaces not specified in `with` should be
    /// generated.
    #[cfg_attr(feature = "clap", arg(long))]
    pub generate_all: bool,

    /// Whether to generate unused structures, not generated by default (false)
    #[cfg_attr(feature = "clap", arg(long))]
    pub generate_unused_types: bool,

    /// The optional path to the `anyhow` crate to use.
    ///
    /// This defaults to `wit_bindgen_wrpc::anyhow`.
    #[cfg_attr(feature = "clap", arg(long))]
    pub anyhow_path: Option<String>,

    /// The optional path to the `bytes` crate to use.
    ///
    /// This defaults to `wit_bindgen_wrpc::bytes`.
    #[cfg_attr(feature = "clap", arg(long))]
    pub bytes_path: Option<String>,

    /// The optional path to the `futures` crate to use.
    ///
    /// This defaults to `wit_bindgen_wrpc::futures`.
    #[cfg_attr(feature = "clap", arg(long))]
    pub futures_path: Option<String>,

    /// The optional path to the `tokio` crate to use.
    ///
    /// This defaults to `wit_bindgen_wrpc::tokio`.
    #[cfg_attr(feature = "clap", arg(long))]
    pub tokio_path: Option<String>,

    /// The optional path to the `tokio-util` crate to use.
    ///
    /// This defaults to `wit_bindgen_wrpc::tokio_util`.
    #[cfg_attr(feature = "clap", arg(long))]
    pub tokio_util_path: Option<String>,

    /// The optional path to the `tracing` crate to use.
    ///
    /// This defaults to `wit_bindgen_wrpc::tracing`.
    #[cfg_attr(feature = "clap", arg(long))]
    pub tracing_path: Option<String>,

    /// The optional path to the `wasm-tokio` crate to use.
    ///
    /// This defaults to `wit_bindgen_wrpc::wasm_tokio`.
    #[cfg_attr(feature = "clap", arg(long))]
    pub wasm_tokio_path: Option<String>,

    /// The optional path to the `wrpc-transport` crate to use.
    ///
    /// This defaults to `wit_bindgen_wrpc::wrpc_transport`.
    #[cfg_attr(feature = "clap", arg(long))]
    pub wrpc_transport_path: Option<String>,
}

impl Opts {
    #[must_use]
    pub fn build(self) -> Box<dyn WorldGenerator> {
        let mut r = RustWrpc::new();
        r.skip = self.skip.iter().cloned().collect();
        r.opts = self;
        Box::new(r)
    }
}

impl RustWrpc {
    fn new() -> RustWrpc {
        RustWrpc::default()
    }

    fn interface<'a>(
        &'a mut self,
        identifier: Identifier<'a>,
        resolve: &'a Resolve,
        in_import: bool,
    ) -> InterfaceGenerator<'a> {
        let mut sizes = SizeAlign::default();
        sizes.fill(resolve);

        InterfaceGenerator {
            identifier,
            src: Source::default(),
            in_import,
            gen: self,
            resolve,
        }
    }

    fn emit_modules(&mut self, modules: Vec<(String, Vec<String>)>) {
        #[derive(Default)]
        struct Module {
            submodules: BTreeMap<String, Module>,
            contents: Vec<String>,
        }
        let mut map = Module::default();
        for (module, path) in modules {
            let mut cur = &mut map;
            for name in &path[..path.len() - 1] {
                cur = cur
                    .submodules
                    .entry(name.clone())
                    .or_insert(Module::default());
            }
            cur.contents.push(module);
        }
        emit(&mut self.src, map);
        fn emit(me: &mut Source, module: Module) {
            for (name, submodule) in module.submodules {
                // Ignore dead-code warnings. If the bindings are only used
                // within a crate, and not exported to a different crate, some
                // parts may be unused, and that's ok.
                uwriteln!(me, "#[allow(dead_code)]");

                uwriteln!(me, "pub mod {name} {{");
                emit(me, submodule);
                uwriteln!(me, "}}");
            }
            for submodule in module.contents {
                uwriteln!(me, "{submodule}");
            }
        }
    }

    fn anyhow_path(&self) -> &str {
        self.opts
            .anyhow_path
            .as_deref()
            .unwrap_or("::wit_bindgen_wrpc::anyhow")
    }

    fn bitflags_path(&self) -> &str {
        self.opts
            .bitflags_path
            .as_deref()
            .unwrap_or("::wit_bindgen_wrpc::bitflags")
    }

    fn bytes_path(&self) -> &str {
        self.opts
            .bytes_path
            .as_deref()
            .unwrap_or("::wit_bindgen_wrpc::bytes")
    }

    fn futures_path(&self) -> &str {
        self.opts
            .futures_path
            .as_deref()
            .unwrap_or("::wit_bindgen_wrpc::futures")
    }

    fn tokio_path(&self) -> &str {
        self.opts
            .tokio_path
            .as_deref()
            .unwrap_or("::wit_bindgen_wrpc::tokio")
    }

    fn tokio_util_path(&self) -> &str {
        self.opts
            .tokio_util_path
            .as_deref()
            .unwrap_or("::wit_bindgen_wrpc::tokio_util")
    }

    fn tracing_path(&self) -> &str {
        self.opts
            .tracing_path
            .as_deref()
            .unwrap_or("::wit_bindgen_wrpc::tracing")
    }

    fn wasm_tokio_path(&self) -> &str {
        self.opts
            .wasm_tokio_path
            .as_deref()
            .unwrap_or("::wit_bindgen_wrpc::wasm_tokio")
    }

    fn wrpc_transport_path(&self) -> &str {
        self.opts
            .wrpc_transport_path
            .as_deref()
            .unwrap_or("::wit_bindgen_wrpc::wrpc_transport")
    }

    fn name_interface(
        &mut self,
        resolve: &Resolve,
        id: InterfaceId,
        name: &WorldKey,
        is_export: bool,
    ) -> Result<bool> {
        let with_name = resolve.name_world_key(name);
        let Some(remapping) = self.with.get(&with_name) else {
            bail!("no remapping found for {with_name:?} - use the `generate!` macro's `with` option to force the interface to be generated or specify where it is already defined:
```
with: {{\n\t{with_name:?}: generate\n}}
```")
        };
        self.generated_interfaces.insert(with_name);
        let entry = match remapping {
            InterfaceGeneration::Remap(remapped_path) => {
                let name = format!("__with_name{}", self.with_name_counter);
                self.with_name_counter += 1;
                uwriteln!(self.src, "use {remapped_path} as {name};");
                InterfaceName {
                    remapped: true,
                    path: name,
                }
            }
            InterfaceGeneration::Generate => {
                let path = compute_module_path(name, resolve, is_export).join("::");

                InterfaceName {
                    remapped: false,
                    path,
                }
            }
        };

        let remapped = entry.remapped;
        self.interface_names.insert(id, entry);

        Ok(remapped)
    }

    /// Generates a `serve` function for the `world_id` specified.
    ///
    /// This will generate a macro which will then itself invoke all the
    /// other macros collected in `self.export_paths` prior. All these macros
    /// are woven together in this single invocation.
    fn finish_serve_function(&mut self) {
        const ROOT: &str = "Handler<T::Context>";
        let mut traits: Vec<String> = self
            .export_paths
            .iter()
            .map(|path| {
                if path.is_empty() {
                    ROOT.to_string()
                } else {
                    format!("{path}::{ROOT}")
                }
            })
            .collect();
        let bound = match traits.len() {
            0 => return,
            1 => traits.pop().unwrap(),
            _ => traits.join(" + "),
        };
        let anyhow = self.anyhow_path().to_string();
        let futures = self.futures_path().to_string();
        let tokio = self.tokio_path().to_string();
        let wrpc_transport = self.wrpc_transport_path().to_string();
        uwriteln!(
            self.src,
            r#"
#[allow(clippy::manual_async_fn)]
pub fn serve<'a, T: {wrpc_transport}::Serve>(
    wrpc: &'a T,
    handler: impl {bound} + ::core::marker::Send + ::core::marker::Sync + ::core::clone::Clone + 'static,
) -> impl ::core::future::Future<
        Output = {anyhow}::Result<
            ::std::vec::Vec<
                (
                    &'static str,
                    &'static str,
                    ::core::pin::Pin<
                        ::std::boxed::Box<
                            dyn {futures}::Stream<
                                Item = {anyhow}::Result<
                                    ::core::pin::Pin<
                                        ::std::boxed::Box<
                                            dyn ::core::future::Future<
                                                Output = {anyhow}::Result<()>
                                            > + ::core::marker::Send + 'static
                                        >
                                    >
                                >
                            > + ::core::marker::Send + 'static
                        >
                    >
                )
            >
        >
    > + ::core::marker::Send + {wrpc_transport}::Captures<'a> {{
    async move {{
        let interfaces = {tokio}::try_join!("#
        );
        for path in &self.export_paths {
            if !path.is_empty() {
                self.src.push_str(path);
                self.src.push_str("::");
            }
            self.src.push_str("serve_interface(wrpc, handler.clone()),");
        }
        uwriteln!(
            self.src,
            r#"
        )?;
        let mut streams = Vec::new();"#
        );
        for i in 0..self.export_paths.len() {
            uwrite!(
                self.src,
                r"
        for s in interfaces.{i} {{
            streams.push(s);
        }}"
            );
        }
        uwriteln!(
            self.src,
            r#"
        Ok(streams)
    }}
}}"#
        );
    }
}

impl WorldGenerator for RustWrpc {
    fn preprocess(&mut self, resolve: &Resolve, world: WorldId) {
        wit_bindgen_core::generated_preamble(&mut self.src, env!("CARGO_PKG_VERSION"));

        // Render some generator options to assist with debugging and/or to help
        // recreate it if the original generation command is lost.
        uwriteln!(self.src, "// Options used:");
        if !self.opts.skip.is_empty() {
            uwriteln!(self.src, "//   * skip: {:?}", self.opts.skip);
        }
        if !self.opts.additional_derive_attributes.is_empty() {
            uwriteln!(
                self.src,
                "//   * additional derives {:?}",
                self.opts.additional_derive_attributes
            );
        }
        for (k, v) in &self.opts.with {
            uwriteln!(self.src, "//   * with {k:?} = {v:?}");
        }
        self.types.analyze(resolve);
        self.world = Some(world);

        let world = &resolve.worlds[world];
        // Specify that all imports local to the world's package should be generated
        for (key, item) in world.imports.iter().chain(world.exports.iter()) {
            if let WorldItem::Interface { id, .. } = item {
                if resolve.interfaces[*id].package == world.package {
                    let name = resolve.name_world_key(key);
                    if self.with.get(&name).is_none() {
                        self.with.insert(name, InterfaceGeneration::Generate);
                    }
                }
            }
        }
        for (k, v) in &self.opts.with {
            self.with.insert(k.clone(), v.clone().into());
        }
        self.with.generate_by_default = self.opts.generate_all;
    }

    fn import_interface(
        &mut self,
        resolve: &Resolve,
        name: &WorldKey,
        id: InterfaceId,
        _files: &mut Files,
    ) -> Result<()> {
        let mut gen = self.interface(Identifier::Interface(id, name), resolve, true);
        let (snake, module_path) = gen.start_append_submodule(name);
        if gen.gen.name_interface(resolve, id, name, false)? {
            return Ok(());
        }
        gen.types(id);

        let interface = &resolve.interfaces[id];
        let name = match name {
            WorldKey::Name(s) => s.to_string(),
            WorldKey::Interface(..) => interface
                .name
                .as_ref()
                .expect("interface name missing")
                .to_string(),
        };
        let instance = if let Some(package) = interface.package {
            resolve.id_of_name(package, &name)
        } else {
            name
        };
        gen.generate_imports(&instance, resolve.interfaces[id].functions.values());

        gen.finish_append_submodule(&snake, module_path);

        Ok(())
    }

    fn import_funcs(
        &mut self,
        resolve: &Resolve,
        world: WorldId,
        funcs: &[(&str, &Function)],
        _files: &mut Files,
    ) {
        self.import_funcs_called = true;

        let mut gen = self.interface(Identifier::World(world), resolve, true);
        let World {
            ref name, package, ..
        } = resolve.worlds[world];
        let instance = if let Some(package) = package {
            resolve.id_of_name(package, name)
        } else {
            name.to_string()
        };
        gen.generate_imports(&instance, funcs.iter().map(|(_, func)| *func));

        let src = gen.finish();
        self.src.push_str(&src);
    }

    fn export_interface(
        &mut self,
        resolve: &Resolve,
        name: &WorldKey,
        id: InterfaceId,
        _files: &mut Files,
    ) -> Result<()> {
        let mut gen = self.interface(Identifier::Interface(id, name), resolve, false);
        let (snake, module_path) = gen.start_append_submodule(name);
        if gen.gen.name_interface(resolve, id, name, true)? {
            return Ok(());
        }
        gen.types(id);
        let exports = gen.generate_exports(
            Identifier::Interface(id, name),
            resolve.interfaces[id].functions.values(),
        );
        gen.finish_append_submodule(&snake, module_path);
        if exports {
            self.export_paths
                .push(self.interface_names[&id].path.clone());
        }
        Ok(())
    }

    fn export_funcs(
        &mut self,
        resolve: &Resolve,
        world: WorldId,
        funcs: &[(&str, &Function)],
        _files: &mut Files,
    ) -> Result<()> {
        let mut gen = self.interface(Identifier::World(world), resolve, false);
        let exports = gen.generate_exports(Identifier::World(world), funcs.iter().map(|f| f.1));
        let src = gen.finish();
        self.src.push_str(&src);
        if exports {
            self.export_paths.push(String::new());
        }
        Ok(())
    }

    fn import_types(
        &mut self,
        resolve: &Resolve,
        world: WorldId,
        types: &[(&str, TypeId)],
        _files: &mut Files,
    ) {
        let mut gen = self.interface(Identifier::World(world), resolve, true);
        for (name, ty) in types {
            gen.define_type(name, *ty);
        }
        let src = gen.finish();
        self.src.push_str(&src);
    }

    fn finish_imports(&mut self, resolve: &Resolve, world: WorldId, files: &mut Files) {
        if !self.import_funcs_called {
            // We call `import_funcs` even if the world doesn't import any
            // functions since one of the side effects of that method is to
            // generate `struct`s for any imported resources.
            self.import_funcs(resolve, world, &[], files);
        }
    }

    fn finish(&mut self, resolve: &Resolve, world: WorldId, files: &mut Files) -> Result<()> {
        let name = &resolve.worlds[world].name;

        let imports = mem::take(&mut self.import_modules);
        self.emit_modules(imports);
        let exports = mem::take(&mut self.export_modules);
        self.emit_modules(exports);

        self.finish_serve_function();

        let mut src = mem::take(&mut self.src);
        if self.opts.format {
            let syntax_tree = syn::parse_file(src.as_str()).unwrap();
            *src.as_mut_string() = prettyplease::unparse(&syntax_tree);
        }

        let module_name = name.to_snake_case();
        files.push(&format!("{module_name}.rs"), src.as_bytes());

        let remapped_keys = self
            .with
            .iter()
            .map(|(k, _)| k)
            .cloned()
            .collect::<HashSet<String>>();

        let mut unused_keys = remapped_keys
            .difference(&self.generated_interfaces)
            .collect::<Vec<&String>>();

        unused_keys.sort();

        if !unused_keys.is_empty() {
            bail!("unused remappings provided via `with`: {unused_keys:?}");
        }

        Ok(())
    }
}

fn compute_module_path(name: &WorldKey, resolve: &Resolve, is_export: bool) -> Vec<String> {
    let mut path = Vec::new();
    if is_export {
        path.push("exports".to_string());
    }
    match name {
        WorldKey::Name(name) => {
            path.push(to_rust_ident(name));
        }
        WorldKey::Interface(id) => {
            let iface = &resolve.interfaces[*id];
            let pkg = iface.package.unwrap();
            let pkgname = resolve.packages[pkg].name.clone();
            path.push(to_rust_ident(&pkgname.namespace));
            path.push(to_rust_ident(&name_package_module(resolve, pkg)));
            path.push(to_rust_ident(iface.name.as_ref().unwrap()));
        }
    }
    path
}

enum Identifier<'a> {
    World(WorldId),
    Interface(InterfaceId, &'a WorldKey),
}

/// Options for with "with" remappings.
#[derive(Debug, Clone)]
pub enum WithOption {
    Path(String),
    Generate,
}

impl std::fmt::Display for WithOption {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            WithOption::Path(p) => f.write_fmt(format_args!("\"{p}\"")),
            WithOption::Generate => f.write_str("generate"),
        }
    }
}

impl From<WithOption> for InterfaceGeneration {
    fn from(opt: WithOption) -> Self {
        match opt {
            WithOption::Path(p) => InterfaceGeneration::Remap(p),
            WithOption::Generate => InterfaceGeneration::Generate,
        }
    }
}

#[derive(Default)]
struct FnSig {
    private: bool,
    use_item_name: bool,
    self_arg: Option<String>,
    self_is_first_param: bool,
}

#[must_use]
pub fn to_rust_ident(name: &str) -> String {
    match name {
        // Escape Rust keywords.
        // Source: https://doc.rust-lang.org/reference/keywords.html
        "as" => "as_".into(),
        "break" => "break_".into(),
        "const" => "const_".into(),
        "continue" => "continue_".into(),
        "crate" => "crate_".into(),
        "else" => "else_".into(),
        "enum" => "enum_".into(),
        "extern" => "extern_".into(),
        "false" => "false_".into(),
        "fn" => "fn_".into(),
        "for" => "for_".into(),
        "if" => "if_".into(),
        "impl" => "impl_".into(),
        "in" => "in_".into(),
        "let" => "let_".into(),
        "loop" => "loop_".into(),
        "match" => "match_".into(),
        "mod" => "mod_".into(),
        "move" => "move_".into(),
        "mut" => "mut_".into(),
        "pub" => "pub_".into(),
        "ref" => "ref_".into(),
        "return" => "return_".into(),
        "self" => "self_".into(),
        "static" => "static_".into(),
        "struct" => "struct_".into(),
        "super" => "super_".into(),
        "trait" => "trait_".into(),
        "true" => "true_".into(),
        "type" => "type_".into(),
        "unsafe" => "unsafe_".into(),
        "use" => "use_".into(),
        "where" => "where_".into(),
        "while" => "while_".into(),
        "async" => "async_".into(),
        "await" => "await_".into(),
        "dyn" => "dyn_".into(),
        "abstract" => "abstract_".into(),
        "become" => "become_".into(),
        "box" => "box_".into(),
        "do" => "do_".into(),
        "final" => "final_".into(),
        "macro" => "macro_".into(),
        "override" => "override_".into(),
        "priv" => "priv_".into(),
        "typeof" => "typeof_".into(),
        "unsized" => "unsized_".into(),
        "virtual" => "virtual_".into(),
        "yield" => "yield_".into(),
        "try" => "try_".into(),
        s => s.to_snake_case(),
    }
}

fn to_upper_camel_case(name: &str) -> String {
    match name {
        // The name "Handler" is reserved for traits generated by exported
        // interfaces, so remap types defined in wit to something else.
        "handler" => "Handler_".to_string(),
        s => s.to_upper_camel_case(),
    }
}

fn int_repr(repr: Int) -> &'static str {
    match repr {
        Int::U8 => "u8",
        Int::U16 => "u16",
        Int::U32 => "u32",
        Int::U64 => "u64",
    }
}

enum RustFlagsRepr {
    U8,
    U16,
    U32,
    U64,
    U128,
}

impl RustFlagsRepr {
    fn new(f: &Flags) -> RustFlagsRepr {
        match f.repr() {
            FlagsRepr::U8 => RustFlagsRepr::U8,
            FlagsRepr::U16 => RustFlagsRepr::U16,
            FlagsRepr::U32(1) => RustFlagsRepr::U32,
            FlagsRepr::U32(2) => RustFlagsRepr::U64,
            FlagsRepr::U32(3 | 4) => RustFlagsRepr::U128,
            FlagsRepr::U32(n) => panic!("unsupported number of flags: {}", n * 32),
        }
    }
}

impl fmt::Display for RustFlagsRepr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RustFlagsRepr::U8 => "u8".fmt(f),
            RustFlagsRepr::U16 => "u16".fmt(f),
            RustFlagsRepr::U32 => "u32".fmt(f),
            RustFlagsRepr::U64 => "u64".fmt(f),
            RustFlagsRepr::U128 => "u128".fmt(f),
        }
    }
}

#[derive(Debug, Clone)]
pub struct MissingWith(pub String);

impl fmt::Display for MissingWith {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "missing `with` mapping for the key `{}`", self.0)
    }
}

impl std::error::Error for MissingWith {}

// bail!("no remapping found for {with_name:?} - use the `generate!` macro's `with` option to force the interface to be generated or specify where it is already defined:
// ```
// with: {{\n\t{with_name:?}: generate\n}}
// ```")