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