Skip to content

Commit

Permalink
refactor: make it simple.
Browse files Browse the repository at this point in the history
  • Loading branch information
rzvxa committed Aug 7, 2024
1 parent b3c190d commit 0eef74c
Showing 1 changed file with 28 additions and 39 deletions.
67 changes: 28 additions & 39 deletions tasks/ast_codegen/src/generators/derive_clone_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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 {
Expand All @@ -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<F>(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
}
}
}
}
Expand Down

0 comments on commit 0eef74c

Please sign in to comment.