Skip to content

Commit

Permalink
Add a small convenience macro for including generated scaffolding. (#397
Browse files Browse the repository at this point in the history
)
  • Loading branch information
rfk authored Feb 23, 2021
1 parent f7c8ccd commit d96edf1
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
13 changes: 12 additions & 1 deletion docs/manual/src/tutorial/Rust_scaffolding.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,21 @@ fn main() {

**Note:** This is the equivalent of calling (and does it under the hood) `uniffi-bindgen scaffolding src/math.udl --out-dir <OUT_DIR>`.

Lastly, we include the generated scaffolding code in our `lib.rs`:
Lastly, we include the generated scaffolding code in our `lib.rs`. If you've used the default build
settings then this can be done using a handy macro:

```rust
uniffi_macros::include_scaffolding!("math");
```

If you have generated the scaffolding in a custom location, use the standard `!include` macro
to include the generated file by name, like this:


```rust
include!(concat!(env!("OUT_DIR"), "/math.uniffi.rs"));
```

**Note:** The file name is always `<namespace>.uniffi.rs`.

Great! `add` is ready to see the outside world!
2 changes: 1 addition & 1 deletion examples/arithmetic/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,4 @@ fn equal(a: u64, b: u64) -> bool {

type Result<T, E = ArithmeticError> = std::result::Result<T, E>;

include!(concat!(env!("OUT_DIR"), "/arithmetic.uniffi.rs"));
uniffi_macros::include_scaffolding!("arithmetic");
28 changes: 28 additions & 0 deletions uniffi_macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,31 @@ impl syn::parse::Parse for FilePaths {
})
}
}

/// A helper macro to include generated component scaffolding.
///
/// This is a simple convenience macro to include the UniFFI component
/// scaffolding as built by `uniffi_build::generate_scaffolding`.
/// Use it like so:
///
/// ```rs
/// uniffi_macros::include_scaffolding!("my_component_name");
/// ```
///
/// This will expand to the appropriate `include!` invocation to include
/// the generated `my_component_name.uniffi.rs` (which it assumes has
/// been successfully built by your crate's `build.rs` script).
//
#[proc_macro]
pub fn include_scaffolding(component_name: proc_macro::TokenStream) -> proc_macro::TokenStream {
let name = syn::parse_macro_input!(component_name as syn::LitStr);
if std::env::var("OUT_DIR").is_err() {
quote! {
compile_error!("This macro assumes the crate has a build.rs script, but $OUT_DIR is not present");
}
} else {
quote! {
include!(concat!(env!("OUT_DIR"), "/", #name, ".uniffi.rs"));
}
}.into()
}

0 comments on commit d96edf1

Please sign in to comment.