1 use proc_macro2::{Ident, TokenStream};
2 use quote::format_ident;
3
4 use syn;
5 use try;
6
wrap_in_const( serde_path: Option<&syn::Path>, trait_: &str, ty: &Ident, code: TokenStream, ) -> TokenStream7 pub fn wrap_in_const(
8 serde_path: Option<&syn::Path>,
9 trait_: &str,
10 ty: &Ident,
11 code: TokenStream,
12 ) -> TokenStream {
13 let try_replacement = try::replacement();
14
15 let dummy_const = if cfg!(underscore_consts) {
16 format_ident!("_")
17 } else {
18 format_ident!("_IMPL_{}_FOR_{}", trait_, unraw(ty))
19 };
20
21 let use_serde = match serde_path {
22 Some(path) => quote! {
23 use #path as _serde;
24 },
25 None => quote! {
26 #[allow(rust_2018_idioms, clippy::useless_attribute)]
27 extern crate serde as _serde;
28 },
29 };
30
31 quote! {
32 #[doc(hidden)]
33 #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
34 const #dummy_const: () = {
35 #use_serde
36 #try_replacement
37 #code
38 };
39 }
40 }
41
42 #[allow(deprecated)]
unraw(ident: &Ident) -> String43 fn unraw(ident: &Ident) -> String {
44 // str::trim_start_matches was added in 1.30, trim_left_matches deprecated
45 // in 1.33. We currently support rustc back to 1.15 so we need to continue
46 // to use the deprecated one.
47 ident.to_string().trim_left_matches("r#").to_owned()
48 }
49