cxxbridge_macro/
lib.rs

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