educe/trait_handlers/
mod.rs1#![cfg_attr(not(feature = "default"), allow(dead_code))]
2
3#[cfg(feature = "Clone")]
4pub mod clone;
5#[cfg(feature = "Copy")]
6pub mod copy;
7#[cfg(feature = "Debug")]
8pub mod debug;
9#[cfg(feature = "Default")]
10pub mod default;
11#[cfg(feature = "Deref")]
12pub mod deref;
13#[cfg(feature = "DerefMut")]
14pub mod deref_mut;
15#[cfg(feature = "Eq")]
16pub mod eq;
17#[cfg(feature = "Hash")]
18pub mod hash;
19#[cfg(feature = "Ord")]
20pub mod ord;
21#[cfg(feature = "PartialEq")]
22pub mod partial_eq;
23#[cfg(feature = "PartialOrd")]
24pub mod partial_ord;
25
26use std::str::FromStr;
27
28use proc_macro2::TokenStream;
29use quote::{quote, ToTokens};
30use syn::{
31 self, punctuated::Punctuated, token::Comma, DeriveInput, Expr, GenericParam, LitStr, Meta,
32 Path, WhereClause, WherePredicate,
33};
34
35use crate::Trait;
36
37pub trait TraitHandler {
38 fn trait_meta_handler(
39 ast: &DeriveInput,
40 tokens: &mut TokenStream,
41 traits: &[Trait],
42 meta: &Meta,
43 );
44}
45
46#[inline]
47pub fn create_path_from_lit_str(s: &LitStr) -> Option<Path> {
48 let s = s.value();
49
50 let s = s.trim();
51
52 if s.is_empty() {
53 None
54 } else {
55 let tokens = TokenStream::from_str(s).unwrap();
56
57 Some(syn::parse2(tokens).unwrap())
58 }
59}
60
61#[inline]
62pub fn create_path_string_from_lit_str(s: &LitStr) -> Option<String> {
63 create_path_from_lit_str(s).map(|path| path.into_token_stream().to_string().replace(' ', ""))
64}
65
66#[inline]
67pub fn create_expr_from_lit_str(s: &LitStr) -> Option<Expr> {
68 let s = s.value();
69
70 let s = s.trim();
71
72 if s.is_empty() {
73 None
74 } else {
75 let tokens = TokenStream::from_str(s).unwrap();
76
77 Some(syn::parse2(tokens).unwrap())
78 }
79}
80
81#[inline]
82pub fn create_expr_string_from_lit_str(s: &LitStr) -> Option<String> {
83 create_expr_from_lit_str(s).map(|expr| expr.into_token_stream().to_string().replace(' ', ""))
84}
85
86#[inline]
87pub fn create_where_predicates_from_lit_str(
88 s: &LitStr,
89) -> Option<Punctuated<WherePredicate, Comma>> {
90 let s = s.value();
91
92 let s = s.trim();
93
94 if s.is_empty() {
95 None
96 } else {
97 let s = format!("where {}", s);
98
99 let tokens = TokenStream::from_str(&s).unwrap();
100
101 let where_clause: WhereClause = syn::parse2(tokens).unwrap();
102
103 Some(where_clause.predicates)
104 }
105}
106
107#[inline]
108pub fn create_where_predicates_from_generic_parameters(
109 p: &Punctuated<GenericParam, Comma>,
110 bound_trait: &Path,
111) -> Punctuated<WherePredicate, Comma> {
112 let mut where_predicates = Punctuated::new();
113
114 for param in p.iter() {
115 if let GenericParam::Type(typ) = param {
116 let ident = &typ.ident;
117
118 where_predicates.push(syn::parse2(quote! { #ident: #bound_trait }).unwrap());
119 }
120 }
121
122 where_predicates
123}