From 0eef74c38cfc4817d4262a44cb3af908e61fb5b9 Mon Sep 17 00:00:00 2001 From: rzvxa Date: Wed, 7 Aug 2024 19:40:41 +0330 Subject: [PATCH] refactor: make it simple. --- .../src/generators/derive_clone_in.rs | 67 ++++++++----------- 1 file changed, 28 insertions(+), 39 deletions(-) diff --git a/tasks/ast_codegen/src/generators/derive_clone_in.rs b/tasks/ast_codegen/src/generators/derive_clone_in.rs index 9421e834f5082c..e73754f57bd220 100644 --- a/tasks/ast_codegen/src/generators/derive_clone_in.rs +++ b/tasks/ast_codegen/src/generators/derive_clone_in.rs @@ -51,7 +51,7 @@ impl Generator for DeriveCloneIn { fn derive_enum(def: &EnumDef) -> TokenStream { let ty_ident = def.ident(); - impl_clone_in(&ty_ident, def.has_lifetime, || { + let (alloc, body) = { let mut used_alloc = false; let matches = def .all_variants() @@ -74,12 +74,13 @@ fn derive_enum(def: &EnumDef) -> TokenStream { } }, ) - }) + }; + impl_clone_in(&ty_ident, def.has_lifetime, alloc, body) } fn derive_struct(def: &StructDef) -> TokenStream { let ty_ident = def.ident(); - impl_clone_in(&ty_ident, def.has_lifetime, || { + let (alloc, body) = { let (alloc_ident, body) = if def.fields.is_empty() { (format_ident!("_"), TokenStream::default()) } else { @@ -89,45 +90,33 @@ fn derive_struct(def: &StructDef) -> TokenStream { }); (format_ident!("alloc"), quote!({ #(#fields),* })) }; - ( - alloc_ident, - quote! { - #ty_ident #body - }, - ) - }) + (alloc_ident, quote!( #ty_ident #body )) + }; + impl_clone_in(&ty_ident, def.has_lifetime, alloc, body) } -fn impl_clone_in(ty_ident: &Ident, has_lifetime: bool, body: F) -> TokenStream -where - F: FnOnce() -> (/* allocator name */ Ident, TokenStream), -{ - let (alloc, body) = body(); - let (impl_lifetimes, trait_lifetime, old_lifetime, new_lifetime, alloc_ref) = if has_lifetime { - ( - quote!(<'old_alloc, 'new_alloc>), - quote!(<'new_alloc>), - quote!(<'old_alloc>), - quote!(<'new_alloc>), - quote!(&'new_alloc), - ) +fn impl_clone_in( + ty_ident: &Ident, + has_lifetime: bool, + alloc: Ident, + body: TokenStream, +) -> TokenStream { + if has_lifetime { + quote! { + impl <'old_alloc, 'new_alloc> CloneIn<'new_alloc> for #ty_ident<'old_alloc> { + type Cloned = #ty_ident<'new_alloc>; + fn clone_in(&self, #alloc: &'new_alloc Allocator) -> Self::Cloned { + #body + } + } + } } else { - ( - quote!(<'alloc>), - quote!(<'alloc>), - TokenStream::default(), - TokenStream::default(), - quote!(&'alloc), - ) - }; - - quote! { - endl!(); - impl #impl_lifetimes CloneIn #trait_lifetime for #ty_ident #old_lifetime { - type Cloned = #ty_ident #new_lifetime; - - fn clone_in(&self, #alloc: #alloc_ref Allocator) -> Self::Cloned { - #body + quote! { + impl <'alloc> CloneIn<'alloc> for #ty_ident { + type Cloned = #ty_ident; + fn clone_in(&self, #alloc: &'alloc Allocator) -> Self::Cloned { + #body + } } } }