blob: 291b03ce610022f1913664f39b2469a67bb0092c [file] [log] [blame]
David Tolnay7db73692019-10-20 14:51:12 -04001#![allow(
David Tolnay30d214c2020-03-15 23:54:34 -07002 clippy::inherent_to_string,
David Tolnay7db73692019-10-20 14:51:12 -04003 clippy::large_enum_variant,
4 clippy::new_without_default,
5 clippy::or_fun_call,
6 clippy::toplevel_ref_arg,
7 clippy::useless_let_if_seq
8)]
9
10extern crate proc_macro;
11
David Tolnayf3a9afa2020-10-08 23:22:12 -070012mod derive;
David Tolnay7db73692019-10-20 14:51:12 -040013mod expand;
David Tolnay7db73692019-10-20 14:51:12 -040014mod syntax;
David Tolnayd09e0122020-05-04 02:34:23 -070015mod type_id;
David Tolnay7db73692019-10-20 14:51:12 -040016
David Tolnay05ef6ff2020-08-29 11:27:05 -070017use crate::syntax::file::Module;
David Tolnay08419302020-04-19 20:38:20 -070018use crate::syntax::namespace::Namespace;
David Tolnaya8d94a12020-09-06 23:28:18 -070019use crate::syntax::qualified::QualifiedName;
David Tolnay7db73692019-10-20 14:51:12 -040020use proc_macro::TokenStream;
David Tolnaya8d94a12020-09-06 23:28:18 -070021use syn::parse::{Parse, ParseStream, Result};
22use syn::parse_macro_input;
David Tolnay7db73692019-10-20 14:51:12 -040023
24/// `#[cxx::bridge] mod ffi { ... }`
25///
26/// Refer to the crate-level documentation for the explanation of how this macro
27/// is intended to be used.
28///
29/// The only additional thing to note here is namespace support — if the
30/// types and functions on the `extern "C"` side of our bridge are in a
31/// namespace, specify that namespace as an argument of the cxx::bridge
32/// attribute macro.
33///
34/// ```
35/// #[cxx::bridge(namespace = mycompany::rust)]
36/// # mod ffi {}
37/// ```
38///
39/// The types and functions from the `extern "Rust"` side of the bridge will be
40/// placed into that same namespace in the generated C++ code.
41#[proc_macro_attribute]
42pub fn bridge(args: TokenStream, input: TokenStream) -> TokenStream {
43 let _ = syntax::error::ERRORS;
44
45 let namespace = parse_macro_input!(args as Namespace);
David Tolnay3c64a4e2020-08-29 14:07:38 -070046 let mut ffi = parse_macro_input!(input as Module);
47 ffi.namespace = namespace;
David Tolnay7db73692019-10-20 14:51:12 -040048
David Tolnay3c64a4e2020-08-29 14:07:38 -070049 expand::bridge(ffi)
David Tolnay7db73692019-10-20 14:51:12 -040050 .unwrap_or_else(|err| err.to_compile_error())
51 .into()
52}
David Tolnayd09e0122020-05-04 02:34:23 -070053
54#[proc_macro]
55pub fn type_id(input: TokenStream) -> TokenStream {
David Tolnaya8d94a12020-09-06 23:28:18 -070056 struct TypeId(QualifiedName);
57
58 impl Parse for TypeId {
59 fn parse(input: ParseStream) -> Result<Self> {
60 QualifiedName::parse_quoted_or_unquoted(input).map(TypeId)
61 }
62 }
63
64 let arg = parse_macro_input!(input as TypeId);
65 type_id::expand(arg.0).into()
David Tolnayd09e0122020-05-04 02:34:23 -070066}