include_wit/
lib.rs

1#![deny(warnings)]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4#![warn(clippy::missing_docs_in_private_items)]
5
6//! `include_wit` allows for embedding [`wit_parser::Resolve`] instances into an application binary.
7//! It exposes a single macro which parses a WIT file or directory, and generates a WASM binary to include in
8//! the source code. This WASM binary is then parsed at runtime upon first access.
9//!
10//! ## Usage
11//!
12//! The following is a simple example of how to use `include_wit`. The full example may be found in [the examples folder](/crates/include_wit/examples/).
13//!
14//! ```rust
15//! // Embed the WIT folder into this application
16//! let resolve = include_wit::include_wit!("wit");
17//!
18//! // Print all interfaces in the resolve
19//! for x in &resolve.interfaces {
20//!     println!("{x:?}");
21//! }
22//! ```
23//!
24//! ## Optional features
25//!
26//! **relative_path** (requires nightly) - Makes all included WIT paths relative to the file where the macro is invoked.
27//!
28//! **track_path** (requires nightly) - Tracks the included WIT files for changes, causing recompilation automatically when they are edited.
29
30pub use include_wit_macro::include_wit;
31use once_cell::race::*;
32use std::ops::*;
33use wit_component::*;
34use wit_parser::*;
35
36/// A [`Resolve`] that has been embedded into a crate.
37pub struct IncludedResolve {
38    /// The fully-loaded resolve.
39    inner: OnceBox<Resolve>,
40    /// The raw bytes of the resolve.
41    wasm: &'static [u8],
42}
43
44impl IncludedResolve {
45    /// Creates a new resolve which will parse the given WIT package file.
46    pub const fn new(wasm: &'static [u8]) -> Self {
47        Self {
48            inner: OnceBox::new(),
49            wasm,
50        }
51    }
52}
53
54impl Deref for IncludedResolve {
55    type Target = Resolve;
56
57    fn deref(&self) -> &Self::Target {
58        self.inner.get_or_init(|| {
59            let resolve = decode(self.wasm).expect("Could not decode resolve.");
60            if let DecodedWasm::WitPackage(resolve, _) = resolve {
61                Box::new(resolve)
62            } else {
63                panic!("Incorrect resolve type.")
64            }
65        })
66    }
67}