blob: fae874a6ce63196d12abffae9f005063e361ca62 [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
12mod expand;
David Tolnay7db73692019-10-20 14:51:12 -040013mod syntax;
David Tolnayd09e0122020-05-04 02:34:23 -070014mod type_id;
David Tolnay7db73692019-10-20 14:51:12 -040015
David Tolnay05ef6ff2020-08-29 11:27:05 -070016use crate::syntax::file::Module;
David Tolnay08419302020-04-19 20:38:20 -070017use crate::syntax::namespace::Namespace;
David Tolnaya8d94a12020-09-06 23:28:18 -070018use crate::syntax::qualified::QualifiedName;
David Tolnay7db73692019-10-20 14:51:12 -040019use proc_macro::TokenStream;
David Tolnaya8d94a12020-09-06 23:28:18 -070020use syn::parse::{Parse, ParseStream, Result};
21use syn::parse_macro_input;
David Tolnay7db73692019-10-20 14:51:12 -040022
23/// `#[cxx::bridge] mod ffi { ... }`
24///
25/// Refer to the crate-level documentation for the explanation of how this macro
26/// is intended to be used.
27///
28/// The only additional thing to note here is namespace support — if the
29/// types and functions on the `extern "C"` side of our bridge are in a
30/// namespace, specify that namespace as an argument of the cxx::bridge
31/// attribute macro.
32///
33/// ```
34/// #[cxx::bridge(namespace = mycompany::rust)]
35/// # mod ffi {}
36/// ```
37///
38/// The types and functions from the `extern "Rust"` side of the bridge will be
39/// placed into that same namespace in the generated C++ code.
40#[proc_macro_attribute]
41pub fn bridge(args: TokenStream, input: TokenStream) -> TokenStream {
42 let _ = syntax::error::ERRORS;
43
44 let namespace = parse_macro_input!(args as Namespace);
David Tolnay3c64a4e2020-08-29 14:07:38 -070045 let mut ffi = parse_macro_input!(input as Module);
46 ffi.namespace = namespace;
David Tolnay7db73692019-10-20 14:51:12 -040047
David Tolnay3c64a4e2020-08-29 14:07:38 -070048 expand::bridge(ffi)
David Tolnay7db73692019-10-20 14:51:12 -040049 .unwrap_or_else(|err| err.to_compile_error())
50 .into()
51}
David Tolnayd09e0122020-05-04 02:34:23 -070052
53#[proc_macro]
54pub fn type_id(input: TokenStream) -> TokenStream {
David Tolnaya8d94a12020-09-06 23:28:18 -070055 struct TypeId(QualifiedName);
56
57 impl Parse for TypeId {
58 fn parse(input: ParseStream) -> Result<Self> {
59 QualifiedName::parse_quoted_or_unquoted(input).map(TypeId)
60 }
61 }
62
63 let arg = parse_macro_input!(input as TypeId);
64 type_id::expand(arg.0).into()
David Tolnayd09e0122020-05-04 02:34:23 -070065}