term_render_macros/lib.rs
1use proc_macro::TokenStream;
2use quote::quote;
3
4use syn::{parse_macro_input, Expr, Token};
5use syn::punctuated::Punctuated;
6
7/// Expands to a call to the Colorize trait, reducing boilerplate. If a single value is provided, it
8/// converts to a call to `Colorize::colorize` with the provided value. If none,
9/// or multiple values are provided, it converts to a call to `Colorize::colorizes`
10/// with a vector of the provided values.
11/// This macro can be used with any type that implements the Colorize trait, including:
12/// * `Colored`
13/// * `String`
14/// * `str`
15/// # Parameters
16/// - value of type T with trait Colorize
17/// - n ColorType variants where n is [0, ∞)
18/// # Example
19/// ```
20/// term_render::color!("Hello World", White, Bold, Underline);
21/// term_render::color!("Hello World"); // converts to Colored without applying modifiers
22/// ```
23#[proc_macro]
24pub fn color (input: TokenStream) -> TokenStream {
25 let args: Punctuated<Expr, Token![,]> = parse_macro_input!(input with Punctuated::parse_terminated);
26 let string = &args[0];
27 let variants: Vec <_> = args.iter().skip(1).map(|ident| quote! { ColorType::#ident }).collect();
28
29 if variants.len() == 1 {
30 let arg = &args[1];
31 return TokenStream::from (quote! {
32 #string.colorize(ColorType::#arg)
33 })
34 }
35 TokenStream::from (quote! {
36 #string.colorizes(vec![#(#variants),*])
37 })
38}
39
40/// Expands the provided value into an `Arc<RwLock<T>>`.
41/// This is a shorthand macro to avoid writing the full expression every time (i.e.
42/// `std::sync::Arc::new(parking_lot::RwLock::new(value))` ).
43/// # Parameters
44/// - value of type T
45/// # Example
46/// ```
47/// let data = send_sync!(MyStruct { field1: 10, field2: String::from("Hello") });
48/// // instead of
49/// let data = std::sync::Arc::new(parking_lot::RwLock::new(MyStruct { field1: 10, field2: String::from("Hello") }));
50/// ```
51#[proc_macro]
52pub fn send_sync (input: TokenStream) -> TokenStream {
53 let args: Punctuated<Expr, Token![,]> = parse_macro_input!(input with Punctuated::parse_terminated);
54 let value = &args[0];
55 TokenStream::from (quote! {
56 std::sync::Arc::new(parking_lot::RwLock::new(#value))
57 })
58}
59