Skip to main content

hao_runtime_macros/
lib.rs

1//! Generates Rust bindings for a .NET assembly, for use with `hao-runtime`.
2//!
3//! ```ignore
4//! mod my_lib {
5//!     hao_runtime_macros::bind! {
6//!         assembly = "dotnet/MyLib.dll",
7//!     }
8//! }
9//!
10//! let runtime = hao_runtime::Runtime::coreclr()?;
11//! let calculator = my_lib::my_lib::Calculator::new(&runtime, 10)?;
12//! assert_eq!(calculator.add(5)?, 15);
13//! ```
14//!
15//! Options:
16//! - `assembly = "path"`: the assembly, relative to the crate's `Cargo.toml`.
17//! - `assembly_env = "VAR"`: read the path from an environment variable at
18//!   compile time instead, e.g. one set by a build script.
19//! - `framework = "Name"`: an assembly of the installed .NET, such as
20//!   `System.Private.CoreLib`, found when compiling. CoreCLR only.
21//! - `types = ["Ns.Type", ...]`: only bind these types (nested types use `+`).
22//!
23//! Every public, non-generic class gets a struct in a module named after its
24//! namespace. Public, non-generic methods whose parameters are primitives,
25//! strings or classes are bound. Static methods and constructors take the
26//! [`Runtime`](https://docs.rs/hao-runtime) to call into.
27
28mod codegen;
29mod model;
30mod names;
31mod options;
32mod thunks;
33mod ty;
34
35use proc_macro::TokenStream;
36
37use options::Options;
38
39fn expand(options: Options) -> syn::Result<proc_macro2::TokenStream> {
40    let Options {
41        path,
42        span,
43        framework,
44        types,
45    } = options;
46    let error = |e: hao::error::HaoError| {
47        syn::Error::new_spanned(&span, format!("{}: {}", path.display(), e))
48    };
49
50    let library = hao::Module::from_path_no_resolve(&path).map_err(error)?;
51    let name = library
52        .assembly
53        .as_ref()
54        .map(|a| a.get().name.clone())
55        .ok_or_else(|| syn::Error::new_spanned(&span, "the module has no assembly manifest"))?;
56
57    let model = model::Model::new(&library, types.as_deref());
58    for wanted in types.iter().flatten() {
59        if !model
60            .types
61            .iter()
62            .any(|t| &t.ty.get().full_name().replace('/', "+") == wanted)
63        {
64            return Err(syn::Error::new_spanned(
65                &span,
66                format!("{} is not a public, non-generic class in {}", wanted, name),
67            ));
68        }
69    }
70
71    let thunks_name = format!("{}.HaoThunks", name);
72    let coreclr =
73        thunks::build(&library, &model, &thunks_name, thunks::Target::CoreClr).map_err(error)?;
74    let mono =
75        thunks::build(&library, &model, &thunks_name, thunks::Target::Mono).map_err(error)?;
76    // Framework assemblies are already available to the runtime, so they aren't loaded by path.
77    let path = match framework {
78        true => String::new(),
79        false => path
80            .canonicalize()
81            .unwrap_or(path)
82            .to_string_lossy()
83            .into_owned(),
84    };
85    Ok(codegen::generate(
86        &model,
87        codegen::Assembly {
88            name: &name,
89            path: &path,
90            thunks_name: &thunks_name,
91            coreclr: &coreclr,
92            mono: &mono,
93        },
94    ))
95}
96
97/// Generates bindings for a .NET assembly. See the crate docs.
98#[proc_macro]
99pub fn bind(input: TokenStream) -> TokenStream {
100    let options = syn::parse_macro_input!(input as Options);
101    expand(options)
102        .unwrap_or_else(|e| e.to_compile_error())
103        .into()
104}