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
28#![cfg_attr(docsrs, feature(doc_cfg))]
29#![warn(missing_docs)]
30
31mod codegen;
32mod model;
33mod names;
34mod options;
35mod thunks;
36mod ty;
37
38use proc_macro::TokenStream;
39
40use options::Options;
41
42fn expand(options: Options) -> syn::Result<proc_macro2::TokenStream> {
43    let Options {
44        path,
45        span,
46        framework,
47        types,
48    } = options;
49    let error = |e: hao::error::HaoError| {
50        syn::Error::new_spanned(&span, format!("{}: {}", path.display(), e))
51    };
52
53    let library = hao::Module::from_path_no_resolve(&path).map_err(error)?;
54    let name = library
55        .assembly
56        .as_ref()
57        .map(|a| a.get().name.clone())
58        .ok_or_else(|| syn::Error::new_spanned(&span, "the module has no assembly manifest"))?;
59
60    let model = model::Model::new(&library, types.as_deref());
61    for wanted in types.iter().flatten() {
62        if !model
63            .types
64            .iter()
65            .any(|t| &t.ty.get().full_name().replace('/', "+") == wanted)
66        {
67            return Err(syn::Error::new_spanned(
68                &span,
69                format!("{} is not a public, non-generic class in {}", wanted, name),
70            ));
71        }
72    }
73
74    let thunks_name = format!("{}.HaoThunks", name);
75    let coreclr =
76        thunks::build(&library, &model, &thunks_name, thunks::Target::CoreClr).map_err(error)?;
77    let mono =
78        thunks::build(&library, &model, &thunks_name, thunks::Target::Mono).map_err(error)?;
79    // Framework assemblies are already available to the runtime, so they aren't loaded by path.
80    let path = match framework {
81        true => String::new(),
82        false => path
83            .canonicalize()
84            .unwrap_or(path)
85            .to_string_lossy()
86            .into_owned(),
87    };
88    Ok(codegen::generate(
89        &model,
90        codegen::Assembly {
91            name: &name,
92            path: &path,
93            thunks_name: &thunks_name,
94            coreclr: &coreclr,
95            mono: &mono,
96        },
97    ))
98}
99
100/// Generates bindings for a .NET assembly. See the crate docs.
101#[proc_macro]
102pub fn bind(input: TokenStream) -> TokenStream {
103    let options = syn::parse_macro_input!(input as Options);
104    expand(options)
105        .unwrap_or_else(|e| e.to_compile_error())
106        .into()
107}