quote_alias/lib.rs
1//! The [`alias!`] macro can be used to assign token streams to convenient identifiers.
2//!
3//! ```
4//! use quote::quote;
5//! use quote_alias::alias;
6//!
7//! alias! {
8//! Foo(my_crate::Foo),
9//! }
10//!
11//! # fn main() {
12//! // same as: quote! { my_crate::Foo::new() };
13//! let create_foo = quote! { #Foo::new() };
14//! # }
15//! ```
16//!
17//! See [`alias!`] for more detailed documentation and usage examples.
18
19#[doc(hidden)]
20pub use proc_macro2::TokenStream;
21#[doc(hidden)]
22pub use quote::{quote, ToTokens};
23
24/// Assigns a token stream to an identifier.
25///
26/// This is done by generating a unit struct that implements [`ToTokens`].
27/// The struct can be then interpolated in [`quote!`] invocations or have its `ToTokens` methods called directly.
28///
29/// Visibility and doc comments are also passed through to the struct.
30///
31/// # Usage
32/// ```
33/// use quote_alias::alias;
34/// use quote::quote;
35///
36/// alias! {
37/// /// `Foo` from `my_crate::foo`
38/// pub Foo(my_crate::foo::Foo),
39///
40/// this_and_that {
41/// my_crate::this();
42/// my_crate::that();
43/// },
44/// }
45///
46/// # fn main() {
47/// // same as: quote! { my_crate::foo::Foo::new() };
48/// quote! { #Foo::new() };
49///
50/// // same as: quote! {
51/// // my_crate::this();
52/// // my_crate::that();
53/// // };
54/// quote! { #this_and_that };
55/// # }
56/// ```
57///
58/// [`quote!`]: quote::quote
59/// [`ToTokens`]: quote::ToTokens
60#[macro_export]
61macro_rules! alias {
62 ($( $(#[doc = $doc:expr])* $vis:vis $ident:ident $body:tt ),* $(,)?) => {
63 $(
64 $(#[doc = $doc])*
65 $crate::alias!(@struct $vis $ident $body);
66 )*
67 };
68
69 (@struct $vis:vis $ident:ident { $($tt:tt)* }) => {
70 $crate::alias!(@struct $vis $ident ( $($tt)* ));
71 };
72 (@struct $vis:vis $ident:ident ( $($tt:tt)* )) => {
73 #[allow(non_camel_case_types)]
74 #[derive(Clone, Copy, Debug)]
75 $vis struct $ident;
76 impl $crate::ToTokens for $ident {
77 fn to_tokens(&self, tokens: &mut $crate::TokenStream) {
78 tokens.extend($crate::quote! { $($tt)* });
79 }
80 }
81 };
82}