File size: 2,025 Bytes
2409829
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#![doc(html_root_url = "http://docs.rs/dyn-any-derive/0.1.0")]

extern crate proc_macro;

use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::{DeriveInput, GenericParam, Lifetime, LifetimeParam, TypeParamBound, parse_macro_input};

/// Derives an implementation for the [`DynAny`] trait.
///
/// # Note
///
/// Currently only works with `struct` inputs.
///
/// # Example
///
/// ## Struct
///
/// ```
/// # use dyn_any::{DynAny, StaticType};
/// #[derive(DynAny)]
/// pub struct Color<'a, 'b> {
///     r: &'a u8,
///     g: &'b u8,
///     b: &'a u8,
/// }
///
///
/// // Generated Impl
///
/// // impl<'dyn_any> StaticType for Color<'dyn_any, 'dyn_any> {
/// //     type Static = Color<'static, 'static>;
/// // }
///
/// ```
#[proc_macro_derive(DynAny, attributes(dyn_any_derive))]
pub fn system_desc_derive(input: TokenStream) -> TokenStream {
	let ast = parse_macro_input!(input as DeriveInput);
	let struct_name = &ast.ident;
	let generics = &ast.generics;

	let static_params = replace_lifetimes(generics, "'static");
	let dyn_params = replace_lifetimes(generics, "'dyn_any");

	let old_params = &generics.params.iter().collect::<Vec<_>>();
	quote! {
		unsafe impl<'dyn_any, #(#old_params,)*> dyn_any::StaticType for #struct_name <#(#dyn_params,)*> {
			type Static =  #struct_name <#(#static_params,)*>;
		}
	}
	.into()
}

fn replace_lifetimes(generics: &syn::Generics, replacement: &str) -> Vec<proc_macro2::TokenStream> {
	let params = generics
		.params
		.iter()
		.map(|param| {
			let param = match param {
				GenericParam::Lifetime(_) => GenericParam::Lifetime(LifetimeParam::new(Lifetime::new(replacement, Span::call_site()))),
				GenericParam::Type(t) => {
					let mut t = t.clone();
					t.bounds.iter_mut().for_each(|bond| {
						if let TypeParamBound::Lifetime(t) = bond {
							*t = Lifetime::new(replacement, Span::call_site())
						}
					});
					GenericParam::Type(t.clone())
				}
				c => c.clone(),
			};
			quote! {#param}
		})
		.collect::<Vec<_>>();
	params
}