diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:18:32 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:18:32 +0000 |
commit | 4547b622d8d29df964fa2914213088b148c498fc (patch) | |
tree | 9fc6b25f3c3add6b745be9a2400a6e96140046e9 /vendor/zerofrom-derive/src | |
parent | Releasing progress-linux version 1.66.0+dfsg1-1~progress7.99u1. (diff) | |
download | rustc-4547b622d8d29df964fa2914213088b148c498fc.tar.xz rustc-4547b622d8d29df964fa2914213088b148c498fc.zip |
Merging upstream version 1.67.1+dfsg1.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vendor/zerofrom-derive/src')
-rw-r--r-- | vendor/zerofrom-derive/src/lib.rs | 175 | ||||
-rw-r--r-- | vendor/zerofrom-derive/src/visitor.rs | 114 |
2 files changed, 289 insertions, 0 deletions
diff --git a/vendor/zerofrom-derive/src/lib.rs b/vendor/zerofrom-derive/src/lib.rs new file mode 100644 index 000000000..63fd58aae --- /dev/null +++ b/vendor/zerofrom-derive/src/lib.rs @@ -0,0 +1,175 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +//! Custom derives for `ZeroFrom` from the `zerofrom` crate. + +// https://github.com/unicode-org/icu4x/blob/main/docs/process/boilerplate.md#library-annotations +#![cfg_attr( + not(test), + deny( + clippy::indexing_slicing, + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::exhaustive_structs, + clippy::exhaustive_enums, + missing_debug_implementations, + ) +)] + +use proc_macro::TokenStream; +use proc_macro2::{Span, TokenStream as TokenStream2}; +use quote::quote; +use syn::spanned::Spanned; +use syn::{parse_macro_input, parse_quote, DeriveInput, Ident, Lifetime, Type, WherePredicate}; +use synstructure::Structure; + +mod visitor; + +/// Custom derive for `zerofrom::ZeroFrom`, +/// +/// This implements `ZeroFrom<Ty> for Ty` for types +/// without a lifetime parameter, and `ZeroFrom<Ty<'data>> for Ty<'static>` +/// for types with a lifetime parameter. +/// +/// Apply the `#[zerofrom(clone)]` attribute to a field if it doesn't implement +/// Copy or ZeroFrom; this data will be cloned when the struct is zero_from'ed. +#[proc_macro_derive(ZeroFrom, attributes(zerofrom))] +pub fn zf_derive(input: TokenStream) -> TokenStream { + let input = parse_macro_input!(input as DeriveInput); + TokenStream::from(zf_derive_impl(&input)) +} + +fn has_clone_attr(attrs: &[syn::Attribute]) -> bool { + attrs.iter().any(|a| { + if let Ok(i) = a.parse_args::<Ident>() { + if i == "clone" { + return true; + } + } + false + }) +} + +fn zf_derive_impl(input: &DeriveInput) -> TokenStream2 { + let tybounds = input + .generics + .type_params() + .map(|ty| { + // Strip out param defaults, we don't need them in the impl + let mut ty = ty.clone(); + ty.eq_token = None; + ty.default = None; + ty + }) + .collect::<Vec<_>>(); + let typarams = tybounds + .iter() + .map(|ty| ty.ident.clone()) + .collect::<Vec<_>>(); + let lts = input.generics.lifetimes().count(); + let name = &input.ident; + let structure = Structure::new(input); + + if lts == 0 { + let has_clone = structure + .variants() + .iter() + .flat_map(|variant| variant.bindings().iter()) + .any(|binding| has_clone_attr(&binding.ast().attrs)); + let (clone, clone_trait) = if has_clone { + (quote!(this.clone()), quote!(Clone)) + } else { + (quote!(*this), quote!(Copy)) + }; + let bounds: Vec<WherePredicate> = typarams + .iter() + .map(|ty| parse_quote!(#ty: #clone_trait + 'static)) + .collect(); + quote! { + impl<'zf, #(#tybounds),*> zerofrom::ZeroFrom<'zf, #name<#(#typarams),*>> for #name<#(#typarams),*> where #(#bounds),* { + fn zero_from(this: &'zf Self) -> Self { + #clone + } + } + } + } else { + if lts != 1 { + return syn::Error::new( + input.generics.span(), + "derive(ZeroFrom) cannot have multiple lifetime parameters", + ) + .to_compile_error(); + } + + let generics_env = typarams.iter().cloned().collect(); + + let mut zf_bounds: Vec<WherePredicate> = vec![]; + let body = structure.each_variant(|vi| { + vi.construct(|f, i| { + let binding = format!("__binding_{}", i); + let field = Ident::new(&binding, Span::call_site()); + + if has_clone_attr(&f.attrs) { + quote! { + #field.clone() + } + } else { + let fty = replace_lifetime(&f.ty, custom_lt("'zf")); + let lifetime_ty = replace_lifetime(&f.ty, custom_lt("'zf_inner")); + + let (has_ty, has_lt) = visitor::check_type_for_parameters(&f.ty, &generics_env); + if has_ty { + // For types without type parameters, the compiler can figure out that the field implements + // ZeroFrom on its own. However, if there are type parameters, there may be complex preconditions + // to `FieldTy: ZeroFrom` that need to be satisfied. We get them to be satisfied by requiring + // `FieldTy<'zf>: ZeroFrom<'zf, FieldTy<'zf_inner>>` + if has_lt { + zf_bounds + .push(parse_quote!(#fty: zerofrom::ZeroFrom<'zf, #lifetime_ty>)); + } else { + zf_bounds.push(parse_quote!(#fty: zerofrom::ZeroFrom<'zf, #fty>)); + } + } + if has_ty || has_lt { + // By doing this we essentially require ZF to be implemented + // on all fields + quote! { + <#fty as zerofrom::ZeroFrom<'zf, #lifetime_ty>>::zero_from(#field) + } + } else { + // No lifetimes, so we can just copy + quote! { *#field } + } + } + }) + }); + + quote! { + impl<'zf, 'zf_inner, #(#tybounds),*> zerofrom::ZeroFrom<'zf, #name<'zf_inner, #(#typarams),*>> for #name<'zf, #(#typarams),*> + where + #(#zf_bounds,)* { + fn zero_from(this: &'zf #name<'zf_inner, #(#typarams),*>) -> Self { + match *this { #body } + } + } + } + } +} + +fn custom_lt(s: &str) -> Lifetime { + Lifetime::new(s, Span::call_site()) +} + +fn replace_lifetime(x: &Type, lt: Lifetime) -> Type { + use syn::fold::Fold; + struct ReplaceLifetime(Lifetime); + + impl Fold for ReplaceLifetime { + fn fold_lifetime(&mut self, _: Lifetime) -> Lifetime { + self.0.clone() + } + } + ReplaceLifetime(lt).fold_type(x.clone()) +} diff --git a/vendor/zerofrom-derive/src/visitor.rs b/vendor/zerofrom-derive/src/visitor.rs new file mode 100644 index 000000000..ce65f7d6d --- /dev/null +++ b/vendor/zerofrom-derive/src/visitor.rs @@ -0,0 +1,114 @@ +// This file is part of ICU4X. For terms of use, please see the file +// called LICENSE at the top level of the ICU4X source tree +// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). + +//! Visitor for determining whether a type has type and non-static lifetime parameters +//! (duplicated in yoke/derive/src/visitor.rs) + +use std::collections::HashSet; +use syn::visit::{visit_lifetime, visit_type, visit_type_path, Visit}; +use syn::{Ident, Lifetime, Type, TypePath}; + +struct TypeVisitor<'a> { + /// The type parameters in scope + typarams: &'a HashSet<Ident>, + /// Whether we found a type parameter + found_typarams: bool, + /// Whether we found a non-'static lifetime parameter + found_lifetimes: bool, +} + +impl<'a, 'ast> Visit<'ast> for TypeVisitor<'a> { + fn visit_lifetime(&mut self, lt: &'ast Lifetime) { + if lt.ident != "static" { + self.found_lifetimes = true; + } + visit_lifetime(self, lt) + } + fn visit_type_path(&mut self, ty: &'ast TypePath) { + // We only need to check ty.path.get_ident() and not ty.qself or any + // generics in ty.path because the visitor will eventually visit those + // types on its own + if let Some(ident) = ty.path.get_ident() { + if self.typarams.contains(ident) { + self.found_typarams = true; + } + } + + visit_type_path(self, ty) + } +} + +/// Checks if a type has type or lifetime parameters, given the local context of +/// named type parameters. Returns (has_type_params, has_lifetime_params) +pub fn check_type_for_parameters(ty: &Type, typarams: &HashSet<Ident>) -> (bool, bool) { + let mut visit = TypeVisitor { + typarams, + found_typarams: false, + found_lifetimes: false, + }; + visit_type(&mut visit, ty); + + (visit.found_typarams, visit.found_lifetimes) +} + +#[cfg(test)] +mod tests { + use proc_macro2::Span; + use std::collections::HashSet; + use syn::{parse_quote, Ident}; + + use super::check_type_for_parameters; + fn make_typarams(params: &[&str]) -> HashSet<Ident> { + params + .iter() + .map(|x| Ident::new(x, Span::call_site())) + .collect() + } + + #[test] + fn test_simple_type() { + let environment = make_typarams(&["T", "U", "V"]); + + let ty = parse_quote!(Foo<'a, T>); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (true, true)); + + let ty = parse_quote!(Foo<T>); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (true, false)); + + let ty = parse_quote!(Foo<'static, T>); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (true, false)); + + let ty = parse_quote!(Foo<'a>); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (false, true)); + + let ty = parse_quote!(Foo<'a, Bar<U>, Baz<(V, u8)>>); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (true, true)); + + let ty = parse_quote!(Foo<'a, W>); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (false, true)); + } + + #[test] + fn test_assoc_types() { + let environment = make_typarams(&["T"]); + + let ty = parse_quote!(<Foo as SomeTrait<'a, T>>::Output); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (true, true)); + + let ty = parse_quote!(<Foo as SomeTrait<'static, T>>::Output); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (true, false)); + + let ty = parse_quote!(<T as SomeTrait<'static, Foo>>::Output); + let check = check_type_for_parameters(&ty, &environment); + assert_eq!(check, (true, false)); + } +} |