| 1 |
//! Implementation of a [`PartialEq`] derive macro. |
| 2 |
|
| 3 |
use proc_macro2::TokenStream; |
| 4 |
use quote::{format_ident, quote, ToTokens}; |
| 5 |
use syn::{ |
| 6 |
parse_quote, |
| 7 |
punctuated::{self, Punctuated}, |
| 8 |
spanned::Spanned as _, |
| 9 |
}; |
| 10 |
|
| 11 |
use crate::utils::{ |
| 12 |
attr::{self, ParseMultiple as _}, |
| 13 |
pattern_matching::FieldsExt as _, |
| 14 |
structural_inclusion::TypeExt as _, |
| 15 |
GenericsSearch, HashSet, |
| 16 |
}; |
| 17 |
|
| 18 |
/// Expands a [`PartialEq`] derive macro. |
| 19 |
pub fn expand(input: &syn::DeriveInput, _: &'static str) -> syn::Result<TokenStream> { |
| 20 |
let attr_name = format_ident!("partial_eq"); |
| 21 |
let secondary_attr_name = format_ident!("eq"); |
| 22 |
|
| 23 |
let mut has_skipped_variants = false; |
| 24 |
let mut variants = vec![]; |
| 25 |
|
| 26 |
match &input.data { |
| 27 |
syn::Data::Struct(data) => { |
| 28 |
for attr_name in [&attr_name, &secondary_attr_name] { |
| 29 |
if attr::Skip::parse_attrs(&input.attrs, attr_name)?.is_some() { |
| 30 |
has_skipped_variants = true; |
| 31 |
break; |
| 32 |
} |
| 33 |
} |
| 34 |
if !has_skipped_variants { |
| 35 |
let mut skipped_fields = SkippedFields::default(); |
| 36 |
'fields: for (n, field) in data.fields.iter().enumerate() { |
| 37 |
for attr_name in [&attr_name, &secondary_attr_name] { |
| 38 |
if attr::Skip::parse_attrs(&field.attrs, attr_name)?.is_some() { |
| 39 |
_ = skipped_fields.insert(n); |
| 40 |
continue 'fields; |
| 41 |
} |
| 42 |
} |
| 43 |
} |
| 44 |
variants.push((None, &data.fields, skipped_fields)); |
| 45 |
} |
| 46 |
} |
| 47 |
syn::Data::Enum(data) => { |
| 48 |
'variants: for variant in &data.variants { |
| 49 |
for attr_name in [&attr_name, &secondary_attr_name] { |
| 50 |
if attr::Skip::parse_attrs(&variant.attrs, attr_name)?.is_some() { |
| 51 |
has_skipped_variants = true; |
| 52 |
continue 'variants; |
| 53 |
} |
| 54 |
} |
| 55 |
let mut skipped_fields = SkippedFields::default(); |
| 56 |
'fields: for (n, field) in variant.fields.iter().enumerate() { |
| 57 |
for attr_name in [&attr_name, &secondary_attr_name] { |
| 58 |
if attr::Skip::parse_attrs(&field.attrs, attr_name)?.is_some() { |
| 59 |
_ = skipped_fields.insert(n); |
| 60 |
continue 'fields; |
| 61 |
} |
| 62 |
} |
| 63 |
} |
| 64 |
variants.push((Some(&variant.ident), &variant.fields, skipped_fields)); |
| 65 |
} |
| 66 |
} |
| 67 |
syn::Data::Union(data) => { |
| 68 |
return Err(syn::Error::new( |
| 69 |
data.union_token.span(), |
| 70 |
"`PartialEq` cannot be derived for unions", |
| 71 |
)) |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
Ok(StructuralExpansion { |
| 76 |
self_ty: (&input.ident, &input.generics), |
| 77 |
variants, |
| 78 |
has_skipped_variants, |
| 79 |
is_enum: matches!(input.data, syn::Data::Enum(_)), |
| 80 |
} |
| 81 |
.into_token_stream()) |
| 82 |
} |
| 83 |
|
| 84 |
/// Indices of [`syn::Field`]s marked with an [`attr::Skip`]. |
| 85 |
type SkippedFields = HashSet<usize>; |
| 86 |
|
| 87 |
/// Expansion of a macro for generating a structural [`PartialEq`] implementation of an enum or a |
| 88 |
/// struct. |
| 89 |
struct StructuralExpansion<'i> { |
| 90 |
/// [`syn::Ident`] and [`syn::Generics`] of the enum/struct. |
| 91 |
/// |
| 92 |
/// [`syn::Ident`]: struct@syn::Ident |
| 93 |
self_ty: (&'i syn::Ident, &'i syn::Generics), |
| 94 |
|
| 95 |
/// [`syn::Fields`] of the enum/struct to be compared in this [`StructuralExpansion`]. |
| 96 |
variants: Vec<(Option<&'i syn::Ident>, &'i syn::Fields, SkippedFields)>, |
| 97 |
|
| 98 |
/// Indicator whether some original enum variants where skipped with an [`attr::Skip`]. |
| 99 |
has_skipped_variants: bool, |
| 100 |
|
| 101 |
/// Indicator whether this expansion is for an enum. |
| 102 |
is_enum: bool, |
| 103 |
} |
| 104 |
|
| 105 |
impl StructuralExpansion<'_> { |
| 106 |
/// Generates body of the [`PartialEq::eq()`]/[`PartialEq::ne()`] method implementation for this |
| 107 |
/// [`StructuralExpansion`], if it's required. |
| 108 |
fn body(&self, eq: bool) -> Option<TokenStream> { |
| 109 |
// Special case: empty enum (also, no need for `ne()` method in this case). |
| 110 |
if self.is_enum && self.variants.is_empty() && !self.has_skipped_variants { |
| 111 |
return eq.then(|| quote! { match *self {} }); |
| 112 |
} |
| 113 |
|
| 114 |
let no_fields_result = quote! { #eq }; |
| 115 |
|
| 116 |
// Special case: fully skipped struct (also, no need for `ne()` method in this case). |
| 117 |
if !self.is_enum && self.variants.is_empty() && self.has_skipped_variants { |
| 118 |
return eq.then_some(no_fields_result); |
| 119 |
} |
| 120 |
// Special case: no fields to compare in struct/single-variant enum (also, no need for |
| 121 |
// `ne()` method in this case). |
| 122 |
if !(self.is_enum && self.has_skipped_variants) |
| 123 |
&& self.variants.len() == 1 |
| 124 |
&& (self.variants[0].1.is_empty() |
| 125 |
|| self.variants[0].1.len() == self.variants[0].2.len()) |
| 126 |
{ |
| 127 |
return eq.then_some(no_fields_result); |
| 128 |
} |
| 129 |
|
| 130 |
let (cmp, chain) = if eq { |
| 131 |
(quote! { == }, quote! { && }) |
| 132 |
} else { |
| 133 |
(quote! { != }, quote! { || }) |
| 134 |
}; |
| 135 |
|
| 136 |
let discriminants_cmp = (self.variants.len() > 1 || self.has_skipped_variants) |
| 137 |
.then(|| { |
| 138 |
quote! { |
| 139 |
derive_more::core::mem::discriminant(self) #cmp |
| 140 |
derive_more::core::mem::discriminant(__other) |
| 141 |
} |
| 142 |
}); |
| 143 |
|
| 144 |
let match_arms = self |
| 145 |
.variants |
| 146 |
.iter() |
| 147 |
.filter_map(|(variant, all_fields, skipped_fields)| { |
| 148 |
if all_fields.is_empty() || skipped_fields.len() == all_fields.len() { |
| 149 |
return None; |
| 150 |
} |
| 151 |
|
| 152 |
let variant = variant.map(|variant| quote! { :: #variant }); |
| 153 |
let self_pattern = all_fields |
| 154 |
.non_exhaustive_arm_pattern("__self_", skipped_fields); |
| 155 |
let other_pattern = all_fields |
| 156 |
.non_exhaustive_arm_pattern("__other_", skipped_fields); |
| 157 |
|
| 158 |
let mut val_eqs = (0..all_fields.len()) |
| 159 |
.filter(|num| !skipped_fields.contains(num)) |
| 160 |
.map(|num| { |
| 161 |
let self_val = format_ident!("__self_{num}"); |
| 162 |
let other_val = format_ident!("__other_{num}"); |
| 163 |
punctuated::Pair::Punctuated(quote! { #self_val #cmp #other_val }, &chain) |
| 164 |
}) |
| 165 |
.collect::<Punctuated<TokenStream, _>>(); |
| 166 |
_ = val_eqs.pop_punct(); |
| 167 |
|
| 168 |
Some(quote! { |
| 169 |
(Self #variant #self_pattern, Self #variant #other_pattern) => { #val_eqs } |
| 170 |
}) |
| 171 |
}) |
| 172 |
.collect::<Vec<_>>(); |
| 173 |
let match_expr = (!match_arms.is_empty()).then(|| { |
| 174 |
let no_fields_arm = (match_arms.len() != self.variants.len() |
| 175 |
|| self.has_skipped_variants) |
| 176 |
.then(|| { |
| 177 |
quote! { _ => #no_fields_result } |
| 178 |
}); |
| 179 |
let unreachable_arm = (self.variants.len() > 1 |
| 180 |
&& no_fields_arm.is_none()) |
| 181 |
.then(|| { |
| 182 |
quote! { |
| 183 |
// SAFETY: This arm is never reachable due to `mem::discriminant()` comparison |
| 184 |
// preceding the expanded `match (self, other)` expression, but is |
| 185 |
// required by it when there is more than one variant. |
| 186 |
_ => unsafe { derive_more::core::hint::unreachable_unchecked() }, |
| 187 |
} |
| 188 |
}); |
| 189 |
|
| 190 |
quote! { |
| 191 |
match (self, __other) { |
| 192 |
#( #match_arms , )* |
| 193 |
#no_fields_arm |
| 194 |
#unreachable_arm |
| 195 |
} |
| 196 |
} |
| 197 |
}); |
| 198 |
|
| 199 |
// If there is only `mem::discriminant()` comparison, there is no need to generate `ne()` |
| 200 |
// method in the expansion, as its default implementation will do just fine. |
| 201 |
if !eq && discriminants_cmp.is_some() && match_expr.is_none() { |
| 202 |
return None; |
| 203 |
} |
| 204 |
|
| 205 |
let chain = |
| 206 |
(discriminants_cmp.is_some() && match_expr.is_some()).then_some(chain); |
| 207 |
|
| 208 |
Some(quote! { |
| 209 |
#discriminants_cmp #chain #match_expr |
| 210 |
}) |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
impl ToTokens for StructuralExpansion<'_> { |
| 215 |
fn to_tokens(&self, tokens: &mut TokenStream) { |
| 216 |
let ty = self.self_ty.0; |
| 217 |
let (_, ty_generics, _) = self.self_ty.1.split_for_impl(); |
| 218 |
|
| 219 |
let generics_search = GenericsSearch::from(self.self_ty.1); |
| 220 |
let mut generics = self.self_ty.1.clone(); |
| 221 |
{ |
| 222 |
let self_ty: syn::Type = parse_quote! { Self }; |
| 223 |
let implementor_ty: syn::Type = parse_quote! { #ty #ty_generics }; |
| 224 |
for (_, all_fields, skipped_fields) in &self.variants { |
| 225 |
for field_ty in |
| 226 |
all_fields.iter().enumerate().filter_map(|(n, field)| { |
| 227 |
(!skipped_fields.contains(&n)).then_some(&field.ty) |
| 228 |
}) |
| 229 |
{ |
| 230 |
if generics_search.any_in(field_ty) |
| 231 |
&& !field_ty.contains_type_structurally(&self_ty) |
| 232 |
&& !field_ty.contains_type_structurally(&implementor_ty) |
| 233 |
{ |
| 234 |
generics.make_where_clause().predicates.push(parse_quote! { |
| 235 |
#field_ty: derive_more::core::cmp::PartialEq |
| 236 |
}); |
| 237 |
} |
| 238 |
} |
| 239 |
} |
| 240 |
} |
| 241 |
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); |
| 242 |
|
| 243 |
let eq_method = self.body(true).map(|body| { |
| 244 |
quote! { |
| 245 |
#[inline] |
| 246 |
fn eq(&self, __other: &Self) -> bool { #body } |
| 247 |
} |
| 248 |
}); |
| 249 |
let ne_method = self.body(false).map(|body| { |
| 250 |
quote! { |
| 251 |
#[inline] |
| 252 |
fn ne(&self, __other: &Self) -> bool { #body } |
| 253 |
} |
| 254 |
}); |
| 255 |
|
| 256 |
quote! { |
| 257 |
#[allow(private_bounds)] |
| 258 |
#[automatically_derived] |
| 259 |
impl #impl_generics derive_more::core::cmp::PartialEq for #ty #ty_generics |
| 260 |
#where_clause |
| 261 |
{ |
| 262 |
#eq_method |
| 263 |
#ne_method |
| 264 |
} |
| 265 |
} |
| 266 |
.to_tokens(tokens); |
| 267 |
} |
| 268 |
} |