cxxbridge_macro/
lib.rs

1#![allow(
2    clippy::cast_sign_loss,
3    clippy::doc_markdown,
4    clippy::elidable_lifetime_names,
5    clippy::enum_glob_use,
6    clippy::inherent_to_string,
7    clippy::items_after_statements,
8    clippy::match_bool,
9    clippy::match_same_arms,
10    clippy::needless_lifetimes,
11    clippy::needless_pass_by_value,
12    clippy::nonminimal_bool,
13    clippy::redundant_else,
14    clippy::ref_option,
15    clippy::single_match_else,
16    clippy::struct_field_names,
17    clippy::too_many_arguments,
18    clippy::too_many_lines,
19    clippy::toplevel_ref_arg,
20    clippy::uninlined_format_args
21)]
22#![allow(unknown_lints, mismatched_lifetime_syntaxes)]
23
24mod derive;
25mod expand;
26mod generics;
27mod syntax;
28mod tokens;
29mod type_id;
30
31#[cfg(feature = "experimental-enum-variants-from-header")]
32mod clang;
33#[cfg(feature = "experimental-enum-variants-from-header")]
34mod load;
35
36use crate::syntax::file::Module;
37use crate::syntax::namespace::Namespace;
38use crate::syntax::qualified::QualifiedName;
39use crate::type_id::Crate;
40use proc_macro::TokenStream;
41use syn::parse::{Parse, ParseStream, Parser, Result};
42use syn::parse_macro_input;
43
44/// `#[cxx::bridge] mod ffi { ... }`
45///
46/// Refer to the crate-level documentation for the explanation of how this macro
47/// is intended to be used.
48///
49/// The only additional thing to note here is namespace support — if the
50/// types and functions on the `extern "C++"` side of our bridge are in a
51/// namespace, specify that namespace as an argument of the cxx::bridge
52/// attribute macro.
53///
54/// ```
55/// #[cxx::bridge(namespace = "mycompany::rust")]
56/// # mod ffi {}
57/// ```
58///
59/// The types and functions from the `extern "Rust"` side of the bridge will be
60/// placed into that same namespace in the generated C++ code.
61#[proc_macro_attribute]
62pub fn bridge(args: TokenStream, input: TokenStream) -> TokenStream {
63    let _ = syntax::error::ERRORS;
64
65    let namespace = match Namespace::parse_bridge_attr_namespace.parse(args) {
66        Ok(namespace) => namespace,
67        Err(err) => return err.to_compile_error().into(),
68    };
69    let mut ffi = parse_macro_input!(input as Module);
70    ffi.namespace = namespace;
71
72    expand::bridge(ffi)
73        .unwrap_or_else(|err| err.to_compile_error())
74        .into()
75}
76
77#[doc(hidden)]
78#[proc_macro]
79pub fn type_id(input: TokenStream) -> TokenStream {
80    struct TypeId {
81        krate: Crate,
82        path: QualifiedName,
83    }
84
85    impl Parse for TypeId {
86        fn parse(input: ParseStream) -> Result<Self> {
87            let krate = input.parse().map(Crate::DollarCrate)?;
88            let path = QualifiedName::parse_quoted_or_unquoted(input)?;
89            Ok(TypeId { krate, path })
90        }
91    }
92
93    let arg = parse_macro_input!(input as TypeId);
94    type_id::expand(arg.krate, arg.path).into()
95}