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