Debian Codegraph @

.cargo/vendor/wit-bindgen/src/lib.rs

raw
1 //! Bindings generation support for Rust with the Component Model.
2 //!
3 //! This crate is a bindings generator for [WIT] and the [Component Model].
4 //! Users are likely interested in the [`generate!`] macro which actually
5 //! generates bindings. Otherwise this crate provides any runtime support
6 //! necessary for the macro-generated code.
7 //!
8 //! [WIT]: https://component-model.bytecodealliance.org/design/wit.html
9 //! [Component Model]: https://component-model.bytecodealliance.org/
10
11 #![no_std]
12
13 #[cfg(not(feature = "rustc-dep-of-std"))]
14 extern crate alloc;
15 #[cfg(feature = "std")]
16 extern crate std;
17
18 /// Generate bindings for an input WIT document.
19 ///
20 /// This macro is the bread-and-butter of the `wit-bindgen` crate. The macro
21 /// here will parse [WIT] as input and generate Rust bindings to work with the
22 /// `world` that's specified in the [WIT]. For a primer on WIT see [this
23 /// documentation][WIT] and for a primer on worlds see [here][worlds].
24 ///
25 /// [WIT]: https://component-model.bytecodealliance.org/design/wit.html
26 /// [worlds]: https://component-model.bytecodealliance.org/design/worlds.html
27 ///
28 /// This macro takes as input a [WIT package] as well as a [`world`][worlds]
29 /// within that package. It will then generate a Rust function for all `import`s
30 /// into the world. If there are any `export`s then a Rust `trait` will be
31 /// generated for you to implement. The macro additionally takes a number of
32 /// configuration parameters documented below as well.
33 ///
34 /// Basic invocation of the macro can look like:
35 ///
36 /// ```
37 /// use wit_bindgen::generate;
38 /// # macro_rules! generate { ($($t:tt)*) => () }
39 ///
40 /// generate!();
41 /// ```
42 ///
43 /// This will parse a WIT package in the `wit` folder adjacent to your project's
44 /// `Cargo.toml` file. Within this WIT package there must be precisely one
45 /// `world` and that world will be the one that has bindings generated for it.
46 /// All other options remain at their default values (more on this below).
47 ///
48 /// If your WIT package has more than one `world`, or if you want to select a
49 /// world from the dependencies, you can specify a world explicitly:
50 ///
51 /// ```
52 /// use wit_bindgen::generate;
53 /// # macro_rules! generate { ($($t:tt)*) => () }
54 ///
55 /// generate!("my-world");
56 /// generate!("wasi:cli/imports");
57 /// ```
58 ///
59 /// This form of the macro takes a single string as an argument which is a
60 /// "world specifier" to select which world is being generated. As a single
61 /// string, such as `"my-world"`, this selects the world named `my-world` in the
62 /// package being parsed in the `wit` folder. The longer form specification
63 /// `"wasi:cli/imports"` indicates that the `wasi:cli` package, located in the
64 /// `wit/deps` folder, will have a world named `imports` and those bindings will
65 /// be generated.
66 ///
67 /// If your WIT package is located in a different directory than one called
68 /// `wit` then it can be specified with the `in` keyword:
69 ///
70 /// ```
71 /// use wit_bindgen::generate;
72 /// # macro_rules! generate { ($($t:tt)*) => () }
73 ///
74 /// generate!(in "./my/other/path/to/wit");
75 /// generate!("a-world" in "../path/to/wit");
76 /// ```
77 ///
78 /// The full-form of the macro, however, takes a braced structure which is a
79 /// "bag of options":
80 ///
81 /// ```
82 /// use wit_bindgen::generate;
83 /// # macro_rules! generate { ($($t:tt)*) => () }
84 ///
85 /// generate!({
86 /// world: "my-world",
87 /// path: "../path/to/wit",
88 /// // ...
89 /// });
90 /// ```
91 ///
92 /// For documentation on each option, see below.
93 ///
94 /// ## Exploring generated bindings
95 ///
96 /// Once bindings have been generated they can be explored via a number of means
97 /// to see what was generated:
98 ///
99 /// * Using `cargo doc` should render all of the generated bindings in addition
100 /// to the original comments in the WIT format itself.
101 /// * If your IDE supports `rust-analyzer` code completion should be available
102 /// to explore and see types.
103 /// * The `wit-bindgen` CLI tool, packaged as `wit-bindgen-cli` on crates.io,
104 /// can be executed the same as the `generate!` macro and the output can be
105 /// read.
106 /// * If you're seeing an error, `WIT_BINDGEN_DEBUG=1` can help debug what's
107 /// happening (more on this below) by emitting macro output to a file.
108 /// * This documentation can be consulted for various constructs as well.
109 ///
110 /// Currently browsing generated code may have road bumps on the way. If you run
111 /// into issues or have idea of how to improve the situation please [file an
112 /// issue].
113 ///
114 /// [file an issue]: https://github.com/bytecodealliance/wit-bindgen/issues/new
115 ///
116 /// ## Namespacing
117 ///
118 /// In WIT, worlds can import and export `interface`s, functions, and types. Each
119 /// `interface` can either be "anonymous" and only named within the context of a
120 /// `world` or it can have a "package ID" associated with it. Names in Rust take
121 /// into account all the names associated with a WIT `interface`. For example
122 /// the package ID `foo:bar/baz` would create a `mod foo` which contains a `mod
123 /// bar` which contains a `mod baz`.
124 ///
125 /// WIT imports and exports are additionally separated into their own
126 /// namespaces. Imports are generated at the level of the `generate!` macro
127 /// where exports are generated under an `exports` namespace.
128 ///
129 /// ## Imports
130 ///
131 /// Imports into a `world` can be types, resources, functions, and interfaces.
132 /// Each of these is bound as a Rust type, function, or module. The intent is
133 /// that the WIT interfaces map to what is roughly idiomatic Rust for the given
134 /// interface.
135 ///
136 /// ### Imports: Top-level functions and types
137 ///
138 /// Imports at the top-level of a world are generated directly where the
139 /// `generate!` macro is invoked.
140 ///
141 /// ```
142 /// use wit_bindgen::generate;
143 ///
144 /// generate!({
145 /// inline: r"
146 /// package a:b;
147 ///
148 /// world the-world {
149 /// record fahrenheit {
150 /// degrees: f32,
151 /// }
152 ///
153 /// import what-temperature-is-it: func() -> fahrenheit;
154 ///
155 /// record celsius {
156 /// degrees: f32,
157 /// }
158 ///
159 /// import convert-to-celsius: func(a: fahrenheit) -> celsius;
160 /// }
161 /// ",
162 /// });
163 ///
164 /// fn test() {
165 /// let current_temp = what_temperature_is_it();
166 /// println!("current temp in fahrenheit is {}", current_temp.degrees);
167 /// let in_celsius: Celsius = convert_to_celsius(current_temp);
168 /// println!("current temp in celsius is {}", in_celsius.degrees);
169 /// }
170 /// ```
171 ///
172 /// ### Imports: Interfaces
173 ///
174 /// Interfaces are placed into submodules where the `generate!` macro is
175 /// invoked and are namespaced based on their identifiers.
176 ///
177 /// ```
178 /// use wit_bindgen::generate;
179 ///
180 /// generate!({
181 /// inline: r"
182 /// package my:test;
183 ///
184 /// interface logging {
185 /// enum level {
186 /// debug,
187 /// info,
188 /// error,
189 /// }
190 /// log: func(level: level, msg: string);
191 /// }
192 ///
193 /// world the-world {
194 /// import logging;
195 /// import global-logger: interface {
196 /// use logging.{level};
197 ///
198 /// set-current-level: func(level: level);
199 /// get-current-level: func() -> level;
200 /// }
201 /// }
202 /// ",
203 /// });
204 ///
205 /// // `my` and `test` are from `package my:test;` and `logging` is for the
206 /// // interfac name.
207 /// use my::test::logging::Level;
208 ///
209 /// fn test() {
210 /// let current_level = global_logger::get_current_level();
211 /// println!("current logging level is {current_level:?}");
212 /// global_logger::set_current_level(Level::Error);
213 ///
214 /// my::test::logging::log(Level::Info, "Hello there!");
215 /// }
216 /// #
217 /// # fn main() {}
218 /// ```
219 ///
220 /// ### Imports: Resources
221 ///
222 /// Imported resources generate a type named after the name of the resource.
223 /// This type is then used both for borrows as `&T` as well as via ownership as
224 /// `T`. Resource methods are bound as methods on the type `T`.
225 ///
226 /// ```
227 /// use wit_bindgen::generate;
228 ///
229 /// generate!({
230 /// inline: r#"
231 /// package my:test;
232 ///
233 /// interface logger {
234 /// enum level {
235 /// debug,
236 /// info,
237 /// error,
238 /// }
239 ///
240 /// resource logger {
241 /// constructor(destination: string);
242 /// log: func(level: level, msg: string);
243 /// }
244 /// }
245 ///
246 /// // Note that while this world does not textually import the above
247 /// // `logger` interface it is a transitive dependency via the `use`
248 /// // statement so the "elaborated world" imports the logger.
249 /// world the-world {
250 /// use logger.{logger};
251 ///
252 /// import get-global-logger: func() -> logger;
253 /// }
254 /// "#,
255 /// });
256 ///
257 /// use my::test::logger::Level;
258 ///
259 /// fn test() {
260 /// let logger = get_global_logger();
261 /// logger.log(Level::Debug, "This is a global message");
262 ///
263 /// let logger2 = Logger::new("/tmp/other.log");
264 /// logger2.log(Level::Info, "This is not a global message");
265 /// }
266 /// #
267 /// # fn main() {}
268 /// ```
269 ///
270 /// Note in the above example the lack of import of `Logger`. The `use`
271 /// statement imported the `Logger` type, an alias of it, from the `logger`
272 /// interface into `the-world`. This generated a Rust `type` alias so `Logger`
273 /// was available at the top-level.
274 ///
275 /// ## Exports: Basic Usage
276 ///
277 /// A WIT world can not only `import` functionality but can additionally
278 /// `export` functionality as well. An `export` represents a contract that the
279 /// Rust program must implement to be able to work correctly. The `generate!`
280 /// macro's goal is to take care of all the low-level and ABI details for you,
281 /// so the end result is that `generate!`, for exports, will generate Rust
282 /// `trait`s that you must implement.
283 ///
284 /// A minimal example of this is:
285 ///
286 /// ```
287 /// use wit_bindgen::generate;
288 ///
289 /// generate!({
290 /// inline: r#"
291 /// package my:test;
292 ///
293 /// world my-world {
294 /// export hello: func();
295 /// }
296 /// "#,
297 /// });
298 ///
299 /// struct MyComponent;
300 ///
301 /// impl Guest for MyComponent {
302 /// fn hello() {}
303 /// }
304 ///
305 /// export!(MyComponent);
306 /// #
307 /// # fn main() {}
308 /// ```
309 ///
310 /// Here the `Guest` trait was generated by the `generate!` macro and represents
311 /// the functions at the top-level of `my-world`, in this case the function
312 /// `hello`. A custom type, here called `MyComponent`, is created and the trait
313 /// is implemented for that type.
314 ///
315 /// Additionally a macro is generated by `generate!` (macros generating macros)
316 /// called `export!`. The `export!` macro is given a component that implements
317 /// the export `trait`s and then it will itself generate all necessary
318 /// `#[unsafe(no_mangle)]` functions to implement the ABI required.
319 ///
320 /// ## Exports: Multiple Interfaces
321 ///
322 /// Each `interface` in WIT will generate a `trait` that must be implemented in
323 /// addition to the top-level `trait` for the world. All traits are named
324 /// `Guest` here and are namespaced appropriately in modules:
325 ///
326 /// ```
327 /// use wit_bindgen::generate;
328 ///
329 /// generate!({
330 /// inline: r#"
331 /// package my:test;
332 ///
333 /// interface a {
334 /// func-in-a: func();
335 /// second-func-in-a: func();
336 /// }
337 ///
338 /// world my-world {
339 /// export a;
340 /// export b: interface {
341 /// func-in-b: func();
342 /// }
343 /// export c: func();
344 /// }
345 /// "#,
346 /// });
347 ///
348 /// struct MyComponent;
349 ///
350 /// impl Guest for MyComponent {
351 /// fn c() {}
352 /// }
353 ///
354 /// impl exports::my::test::a::Guest for MyComponent {
355 /// fn func_in_a() {}
356 /// fn second_func_in_a() {}
357 /// }
358 ///
359 /// impl exports::b::Guest for MyComponent {
360 /// fn func_in_b() {}
361 /// }
362 ///
363 /// export!(MyComponent);
364 /// #
365 /// # fn main() {}
366 /// ```
367 ///
368 /// Here note that there were three `Guest` traits generated for each of the
369 /// three groups: two interfaces and one `world`. Also note that traits (and
370 /// types) for exports are namespaced in an `exports` module.
371 ///
372 /// Note that when the top-level `world` does not have any exported functions,
373 /// or if an interface does not have any functions, then no `trait` is
374 /// generated:
375 ///
376 /// ```
377 /// use wit_bindgen::generate;
378 ///
379 /// generate!({
380 /// inline: r#"
381 /// package my:test;
382 ///
383 /// interface a {
384 /// type my-type = u32;
385 /// }
386 ///
387 /// world my-world {
388 /// export b: interface {
389 /// use a.{my-type};
390 ///
391 /// foo: func() -> my-type;
392 /// }
393 /// }
394 /// "#,
395 /// });
396 ///
397 /// struct MyComponent;
398 ///
399 /// impl exports::b::Guest for MyComponent {
400 /// fn foo() -> u32 {
401 /// 42
402 /// }
403 /// }
404 ///
405 /// export!(MyComponent);
406 /// #
407 /// # fn main() {}
408 /// ```
409 ///
410 /// ## Exports: Resources
411 ///
412 /// Exporting a resource is significantly different than importing a resource.
413 /// A component defining a resource can create new resources of that type at any
414 /// time, for example. Additionally resources can be "dereferenced" into their
415 /// underlying values within the component.
416 ///
417 /// Owned resources have a custom type generated and borrowed resources are
418 /// generated with a type of the same name suffixed with `Borrow<'_>`, such as
419 /// `MyResource` and `MyResourceBorrow<'_>`.
420 ///
421 /// Like `interface`s the methods and functions used with a `resource` are
422 /// packaged up into a `trait`.
423 ///
424 /// Specifying a custom resource type is done with an associated type on the
425 /// corresponding trait for the resource's containing interface/world:
426 ///
427 /// ```
428 /// use wit_bindgen::generate;
429 /// use std::cell::{RefCell, Cell};
430 ///
431 /// generate!({
432 /// inline: r#"
433 /// package my:test;
434 ///
435 /// interface logging {
436 /// enum level {
437 /// debug,
438 /// info,
439 /// error,
440 /// }
441 ///
442 /// resource logger {
443 /// constructor(level: level);
444 /// log: func(level: level, msg: string);
445 /// level: func() -> level;
446 /// set-level: func(level: level);
447 /// }
448 /// }
449 ///
450 /// world my-world {
451 /// export logging;
452 /// }
453 /// "#,
454 /// });
455 ///
456 /// use exports::my::test::logging::{Guest, GuestLogger, Level};
457 ///
458 /// struct MyComponent;
459 ///
460 /// // Note that the `logging` interface has no methods of its own but a trait
461 /// // is required to be implemented here to specify the type of `Logger`.
462 /// impl Guest for MyComponent {
463 /// type Logger = MyLogger;
464 /// }
465 ///
466 /// struct MyLogger {
467 /// level: Cell<Level>,
468 /// contents: RefCell<String>,
469 /// }
470 ///
471 /// impl GuestLogger for MyLogger {
472 /// fn new(level: Level) -> MyLogger {
473 /// MyLogger {
474 /// level: Cell::new(level),
475 /// contents: RefCell::new(String::new()),
476 /// }
477 /// }
478 ///
479 /// fn log(&self, level: Level, msg: String) {
480 /// if level as u32 <= self.level.get() as u32 {
481 /// self.contents.borrow_mut().push_str(&msg);
482 /// self.contents.borrow_mut().push_str("\n");
483 /// }
484 /// }
485 ///
486 /// fn level(&self) -> Level {
487 /// self.level.get()
488 /// }
489 ///
490 /// fn set_level(&self, level: Level) {
491 /// self.level.set(level);
492 /// }
493 /// }
494 ///
495 /// export!(MyComponent);
496 /// #
497 /// # fn main() {}
498 /// ```
499 ///
500 /// It's important to note that resources in Rust do not get `&mut self` as
501 /// methods, but instead are required to be defined with `&self`. This requires
502 /// the use of interior mutability such as `Cell` and `RefCell` above from the
503 /// `std::cell` module.
504 ///
505 /// ## Exports: The `export!` macro
506 ///
507 /// Components are created by having exported WebAssembly functions with
508 /// specific names, and these functions are not created when `generate!` is
509 /// invoked. Instead these functions are created afterwards once you've defined
510 /// your own type an implemented the various `trait`s for it. The
511 /// `#[unsafe(no_mangle)]` functions that will become the component are created
512 /// with the generated `export!` macro.
513 ///
514 /// Each call to `generate!` will itself generate a macro called `export!`.
515 /// The macro's first argument is the name of a type that implements the traits
516 /// generated:
517 ///
518 /// ```
519 /// use wit_bindgen::generate;
520 ///
521 /// generate!({
522 /// inline: r#"
523 /// package my:test;
524 ///
525 /// world my-world {
526 /// # export hello: func();
527 /// // ...
528 /// }
529 /// "#,
530 /// });
531 ///
532 /// struct MyComponent;
533 ///
534 /// impl Guest for MyComponent {
535 /// # fn hello() {}
536 /// // ...
537 /// }
538 ///
539 /// export!(MyComponent);
540 /// #
541 /// # fn main() {}
542 /// ```
543 ///
544 /// This argument is a Rust type which implements the `Guest` traits generated
545 /// by `generate!`. Note that all `Guest` traits must be implemented for the
546 /// type provided or an error will be generated.
547 ///
548 /// This macro additionally accepts a second argument. The macro itself needs to
549 /// be able to find the module where the `generate!` macro itself was originally
550 /// invoked. Currently that can't be done automatically so a path to where
551 /// `generate!` was provided can also be passed to the macro. By default, the
552 /// argument is set to `self`:
553 ///
554 /// ```
555 /// use wit_bindgen::generate;
556 ///
557 /// generate!({
558 /// // ...
559 /// # inline: r#"
560 /// # package my:test;
561 /// #
562 /// # world my-world {
563 /// # export hello: func();
564 /// # // ...
565 /// # }
566 /// # "#,
567 /// });
568 /// #
569 /// # struct MyComponent;
570 /// #
571 /// # impl Guest for MyComponent {
572 /// # fn hello() {}
573 /// # // ...
574 /// # }
575 /// #
576 /// export!(MyComponent with_types_in self);
577 /// #
578 /// # fn main() {}
579 /// ```
580 ///
581 /// This indicates that the current module, referred to with `self`, is the one
582 /// which had the `generate!` macro expanded.
583 ///
584 /// If, however, the `generate!` macro was run in a different module then that
585 /// must be configured:
586 ///
587 /// ```
588 /// mod bindings {
589 /// wit_bindgen::generate!({
590 /// // ...
591 /// # inline: r#"
592 /// # package my:test;
593 /// #
594 /// # world my-world {
595 /// # export hello: func();
596 /// # // ...
597 /// # }
598 /// # "#,
599 /// });
600 /// }
601 /// #
602 /// # struct MyComponent;
603 /// #
604 /// # impl bindings::Guest for MyComponent {
605 /// # fn hello() {}
606 /// # // ...
607 /// # }
608 /// #
609 /// bindings::export!(MyComponent with_types_in bindings);
610 /// #
611 /// # fn main() {}
612 /// ```
613 ///
614 /// ## Debugging output to `generate!`
615 ///
616 /// While `wit-bindgen` is tested to the best of our ability there are
617 /// inevitably bugs and issues that arise. These can range from bad error
618 /// messages to misconfigured invocations to bugs in the macro itself. To assist
619 /// with debugging these situations the macro recognizes an environment
620 /// variable:
621 ///
622 /// ```shell
623 /// export WIT_BINDGEN_DEBUG=1
624 /// ```
625 ///
626 /// When set the macro will emit the result of expansion to a file and then
627 /// `include!` that file. Any error messages generated by `rustc` should then
628 /// point to the generated file and allow you to open it up, read it, and
629 /// inspect it. This can often provide better context to the error than rustc
630 /// provides by default with macros.
631 ///
632 /// It is not recommended to set this environment variable by default as it will
633 /// cause excessive rebuilds of Cargo projects. It's recommended to only use it
634 /// as necessary to debug issues.
635 ///
636 /// ## Options to `generate!`
637 ///
638 /// The full list of options that can be passed to the `generate!` macro are as
639 /// follows. Note that there are no required options, they all have default
640 /// values.
641 ///
642 ///
643 /// ```
644 /// use wit_bindgen::generate;
645 /// # macro_rules! generate { ($($t:tt)*) => () }
646 ///
647 /// generate!({
648 /// // The name of the world that bindings are being generated for. If this
649 /// // is not specified then it's required that the package selected
650 /// // below has a single `world` in it.
651 /// world: "my-world",
652 ///
653 /// // Path to parse WIT and its dependencies from. Defaults to the `wit`
654 /// // folder adjacent to your `Cargo.toml`.
655 /// //
656 /// // This parameter also supports the form of a list, such as:
657 /// // ["../path/to/wit1", "../path/to/wit2"]
658 /// // Usually used in testing, our test suite may want to generate code
659 /// // from wit files located in multiple paths within a single mod, and we
660 /// // don't want to copy these files again. Currently these locations must
661 /// // be ordered, as later paths can't contain dependencies on earlier
662 /// // paths. This restriction may be lifted in the future.
663 /// path: "../path/to/wit",
664 ///
665 /// // Enables passing "inline WIT". If specified this is the default
666 /// // package that a world is selected from. Any dependencies that this
667 /// // inline WIT refers to must be defined in the `path` option above.
668 /// //
669 /// // By default this is not specified.
670 /// inline: "
671 /// world my-world {
672 /// import wasi:cli/imports;
673 ///
674 /// export my-run: func()
675 /// }
676 /// ",
677 ///
678 /// // Additional traits to derive for all defined types. Note that not all
679 /// // types may be able to implement these traits, such as resources.
680 /// //
681 /// // By default this set is empty.
682 /// additional_derives: [PartialEq, Eq, Hash, Clone],
683 ///
684 /// // When generating bindings for interfaces that are not defined in the
685 /// // same package as `world`, this option can be used to either generate
686 /// // those bindings or point to already generated bindings.
687 /// // For example, if your world refers to WASI types then the `wasi` crate
688 /// // already has generated bindings for all WASI types and structures. In this
689 /// // situation the key `with` here can be used to use those types
690 /// // elsewhere rather than regenerating types.
691 /// // If for example your world refers to some type and you want to use
692 /// // your own custom implementation of that type then you can specify
693 /// // that here as well. There is a requirement on the remapped (custom)
694 /// // type to have the same internal structure and identical to what would
695 /// // wit-bindgen generate (including alignment, etc.), since
696 /// // lifting/lowering uses its fields directly.
697 /// //
698 /// // If, however, your world refers to interfaces for which you don't have
699 /// // already generated bindings then you can use the special `generate` value
700 /// // to have those bindings generated.
701 /// //
702 /// // The `with` key here works for interfaces and individual types.
703 /// //
704 /// // When an interface or type is specified here no bindings will be
705 /// // generated at all. It's assumed bindings are fully generated
706 /// // somewhere else. This is an indicator that any further references to types
707 /// // defined in these interfaces should use the upstream paths specified
708 /// // here instead.
709 /// //
710 /// // Any unused keys in this map are considered an error.
711 /// with: {
712 /// "wasi:io/poll": wasi::io::poll,
713 /// "some:package/my-interface": generate,
714 /// "some:package/my-interface/my-type": my_crate::types::MyType,
715 /// },
716 ///
717 /// // Indicates that all interfaces not present in `with` should be assumed
718 /// // to be marked with `generate`.
719 /// generate_all,
720 ///
721 /// // An optional list of function names to skip generating bindings for.
722 /// // This is only applicable to imports and the name specified is the name
723 /// // of the function.
724 /// skip: ["foo", "bar", "baz"],
725 ///
726 /// // Configuration of how Rust types are generated.
727 /// //
728 /// // This option will change how WIT types are mapped to Rust types. There
729 /// // are a number of ways this can be done depending on the context. For
730 /// // example a Rust `&str` is suitable to pass to an imported function but
731 /// // an exported function receives a `String`. These both represent the
732 /// // WIT type `string`, however.
733 /// //
734 /// // Type generation becomes extra-significant when aggregates come into
735 /// // play (such as a WIT `record` or `variant`), especially when the
736 /// // aggregate is used both in an imported function and exported one.
737 /// //
738 /// // There are three modes of ownership, documented here, but only one
739 /// // can be specified.
740 /// //
741 /// // The default mode is "Owning" meaning that all Rust types will by
742 /// // default contain their owned containers. For example a `record` with
743 /// // a `string` will map to a Rust `struct` containing a `String`. This
744 /// // maximizes the chance that types can be shared between imports and
745 /// // exports but can come at a cost where calling an import may require
746 /// // more allocations than necessary.
747 /// ownership: Owning,
748 ///
749 /// // Specifies an alternative name for the `export!` macro generated for
750 /// // any exports this world has.
751 /// //
752 /// // Defaults to "export"
753 /// export_macro_name: "export",
754 ///
755 /// // Indicates whether the `export!` macro is `pub` or just `pub(crate)`.
756 /// //
757 /// // This defaults to `false`.
758 /// pub_export_macro: false,
759 ///
760 /// // The second mode of ownership is "Borrowing". This mode then
761 /// // additionally has a boolean flag indicating whether duplicate types
762 /// // should be generated if necessary.
763 /// //
764 /// // This mode will prefer using borrowed values in Rust to represent WIT
765 /// // values where possible. For example if the argument to an imported
766 /// // function is a record-with-a-string then in Rust that will generate a
767 /// // `struct` with a lifetime parameter storing `&'a str`.
768 /// //
769 /// // The `duplicate_if_necessary` flag will cause duplicate types to be
770 /// // generated when a WIT type is used both in an import and export. In
771 /// // this situation one will be called `FooParam` and one will be called
772 /// // `FooResult` (where `foo` is the WIT name).
773 /// //
774 /// // It's generally recommended to not turn this on unless performance
775 /// // requires it. Even if so, please feel free to open an issue on the
776 /// // `wit-bindgen` repository to help improve the default "Owning" use
777 /// // case above if possible.
778 /// ownership: Borrowing { duplicate_if_necessary: false },
779 ///
780 /// // The generated `export!` macro, if any, will by default look for
781 /// // generated types adjacent to where the `export!` macro is invoked
782 /// // through the `self` module. This option can be used to change the
783 /// // defaults to look somewhere else instead.
784 /// default_bindings_module: "path::to::bindings",
785 ///
786 /// // This will suffix the custom section containing component type
787 /// // information with the specified string. This is not required by
788 /// // default but if the same world is generated in two different locations
789 /// // in the crate then one bindings generation location will need this
790 /// // suffix to avoid having the custom sections corrupt each other.
791 /// type_section_suffix: "suffix",
792 ///
793 /// // Configures the path to the `wit-bindgen` crate itself. By default
794 /// // this is `wit_bindgen` assuming that your crate depends on the
795 /// // `wit-bindgen` crate itself.
796 /// runtime_path: "path::to::wit_bindgen",
797 ///
798 /// // Configure where the `bitflags` crate is located. By default this
799 /// // is `wit_bindgen::bitflags` which already reexports `bitflags` for
800 /// // you.
801 /// bitflags_path: "path::to::bitflags",
802 ///
803 /// // Indicates that instead of `&str` and `String` the `&[u8]` and
804 /// // `Vec<u8>` types should be used. Only intended for cases where
805 /// // compiled size is of the utmost concern as this can avoid pulling in
806 /// // UTF-8 validation.
807 /// raw_strings,
808 ///
809 /// // Emits `#[cfg(feature = "std")]` around `impl Error for ... {}` blocks
810 /// // for generated types. This is a niche option that is only here to
811 /// // support the standard library itself depending on this crate one day.
812 /// std_feature,
813 ///
814 /// // Disable a workaround to force wasm constructors to be run only once
815 /// // when exported functions are called.
816 /// disable_run_ctors_once_workaround: false,
817 ///
818 /// // Whether to generate unused `record`, `enum`, `variant` types.
819 /// // By default, they will not be generated unless they are used as input
820 /// // or return value of a function.
821 /// generate_unused_types: false,
822 ///
823 /// // A list of "features" which correspond to WIT features to activate
824 /// // when parsing WIT files. This enables `@unstable` annotations showing
825 /// // up and having bindings generated for them.
826 /// //
827 /// // By default this is an empty list.
828 /// features: ["foo", "bar", "baz"],
829 ///
830 /// // Disables generation of a `#[used]` static to try harder to get the
831 /// // custom section describing WIT types linked into the binary when
832 /// // used in library-like situations. This is `false` by default with
833 /// // `#[used]` statics being emitted.
834 /// disable_custom_section_link_helpers: false,
835 ///
836 /// // Write generated code to a .rs file, which allows the compiler to
837 /// // emit more useful diagnostics for errors in the generated code. This
838 /// // is primarily useful for `wit-bindgen` developers.
839 /// //
840 /// // This does the same thing as setting `WIT_BINDGEN_DEBUG=1`, except
841 /// // that it can be used on a more fine-grained basis (i.e. it only affects
842 /// // the specific `generate!` call where it is used.
843 /// debug: true,
844 ///
845 /// // Generate async import and/or export bindings.
846 /// //
847 /// // The resulting bindings will use the component model
848 /// // [async ABI](https://github.com/WebAssembly/component-model/blob/main/design/mvp/Async.md).
849 /// //
850 /// // If this option is not provided then the WIT's source annotation will
851 /// // be used instead.
852 /// async: true, // all bindings are async
853 /// async: false, // all bindings are sync
854 /// // With an array per-function configuration can be specified. A leading
855 /// // '-' will disable async for that particular function.
856 /// async: [
857 /// "wasi:http/[email protected]#[static]body.finish",
858 /// "import:wasi:http/[email protected]#handle",
859 /// "-export:wasi:http/[email protected]#handle",
860 /// "all",
861 /// ],
862 /// });
863 /// ```
864 ///
865 /// [WIT package]: https://component-model.bytecodealliance.org/design/packages.html
866 #[cfg(feature = "macros")]
867 pub use wit_bindgen_rust_macro::generate;
868
869 #[cfg(docsrs)]
870 pub mod examples;
871
872 #[doc(hidden)]
873 pub mod rt;
874
875 #[cfg(feature = "async")]
876 pub use rt::async_support::{
877 backpressure_dec, backpressure_inc, backpressure_set, block_on, spawn, yield_async,
878 yield_blocking, AbiBuffer, FutureRead, FutureReader, FutureWrite, FutureWriteCancel,
879 FutureWriteError, FutureWriter, StreamRead, StreamReader, StreamResult, StreamWrite,
880 StreamWriter,
881 };