Skip to content

Commit

Permalink
Factor out some duplicated code.
Browse files Browse the repository at this point in the history
  • Loading branch information
nnethercote committed Nov 9, 2023
1 parent 316ffba commit dd6bab9
Showing 1 changed file with 31 additions and 42 deletions.
73 changes: 31 additions & 42 deletions compiler/rustc_macros/src/hash_stable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,28 +45,9 @@ pub(crate) fn hash_stable_generic_derive(
s.add_bounds(synstructure::AddBounds::Generics);
s.add_impl_generic(generic);
s.add_where_predicate(parse_quote! { __CTX: crate::HashStableContext });
let body = s.each(|bi| {
let attrs = parse_attributes(bi.ast());
if attrs.ignore {
quote! {}
} else if let Some(project) = attrs.project {
quote! {
(&#bi.#project).hash_stable(__hcx, __hasher);
}
} else {
quote! {
#bi.hash_stable(__hcx, __hasher);
}
}
});

let discriminant = match s.ast().data {
syn::Data::Enum(_) => quote! {
::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
},
syn::Data::Struct(_) => quote! {},
syn::Data::Union(_) => panic!("cannot derive on union"),
};
let discriminant = hash_stable_discriminant(&mut s);
let body = hash_stable_body(&mut s);

s.bound_impl(
quote!(::rustc_data_structures::stable_hasher::HashStable<__CTX>),
Expand All @@ -87,28 +68,9 @@ pub(crate) fn hash_stable_derive(mut s: synstructure::Structure<'_>) -> proc_mac
let generic: syn::GenericParam = parse_quote!('__ctx);
s.add_bounds(synstructure::AddBounds::Generics);
s.add_impl_generic(generic);
let body = s.each(|bi| {
let attrs = parse_attributes(bi.ast());
if attrs.ignore {
quote! {}
} else if let Some(project) = attrs.project {
quote! {
(&#bi.#project).hash_stable(__hcx, __hasher);
}
} else {
quote! {
#bi.hash_stable(__hcx, __hasher);
}
}
});

let discriminant = match s.ast().data {
syn::Data::Enum(_) => quote! {
::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
},
syn::Data::Struct(_) => quote! {},
syn::Data::Union(_) => panic!("cannot derive on union"),
};
let discriminant = hash_stable_discriminant(&mut s);
let body = hash_stable_body(&mut s);

s.bound_impl(
quote!(
Expand All @@ -128,3 +90,30 @@ pub(crate) fn hash_stable_derive(mut s: synstructure::Structure<'_>) -> proc_mac
},
)
}

fn hash_stable_discriminant(s: &mut synstructure::Structure<'_>) -> proc_macro2::TokenStream {
match s.ast().data {
syn::Data::Enum(_) => quote! {
::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
},
syn::Data::Struct(_) => quote! {},
syn::Data::Union(_) => panic!("cannot derive on union"),
}
}

fn hash_stable_body(s: &mut synstructure::Structure<'_>) -> proc_macro2::TokenStream {
s.each(|bi| {
let attrs = parse_attributes(bi.ast());
if attrs.ignore {
quote! {}
} else if let Some(project) = attrs.project {
quote! {
(&#bi.#project).hash_stable(__hcx, __hasher);
}
} else {
quote! {
#bi.hash_stable(__hcx, __hasher);
}
}
})
}

0 comments on commit dd6bab9

Please sign in to comment.