Skip to content

Commit b08ca81

Browse files
Peternator7Peter Glotfelty
and
Peter Glotfelty
authored
Fix potential errors from vis diffs (#409)
Co-authored-by: Peter Glotfelty <peter@glotfelty.us>
1 parent b7c31f5 commit b08ca81

File tree

1 file changed

+23
-10
lines changed

1 file changed

+23
-10
lines changed

strum_macros/src/macros/enum_discriminants.rs

+23-10
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
3636
let discriminants_name = type_properties.discriminant_name.unwrap_or(default_name);
3737
let discriminants_vis = type_properties
3838
.discriminant_vis
39-
.unwrap_or_else(|| vis.clone());
39+
.as_ref()
40+
.unwrap_or_else(|| &vis);
4041

4142
// Pass through all other attributes
4243
let pass_though_attributes = type_properties.discriminant_others;
@@ -159,6 +160,26 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
159160
}
160161
};
161162

163+
// For now, only implement IntoDiscriminant if the user has not overriden the visibility.
164+
let impl_into_discriminant = match type_properties.discriminant_vis {
165+
// If the visibilty is unspecified or `pub` then we implement IntoDiscriminant
166+
None | Some(syn::Visibility::Public(..)) => quote! {
167+
impl #impl_generics #strum_module_path::IntoDiscriminant for #name #ty_generics #where_clause {
168+
type Discriminant = #discriminants_name;
169+
170+
#[inline]
171+
fn discriminant(&self) -> Self::Discriminant {
172+
<Self::Discriminant as ::core::convert::From<&Self>>::from(self)
173+
}
174+
}
175+
},
176+
// If it's something restricted such as `pub(super)` then we skip implementing the
177+
// trait for now. There are certainly scenarios where they could be equivalent, but
178+
// as a heuristic, if someone is overriding the visibility, it's because they want
179+
// the discriminant type to be less visible than the original type.
180+
_ => quote! {},
181+
};
182+
162183
Ok(quote! {
163184
/// Auto-generated discriminant enum variants
164185
#derives
@@ -168,15 +189,7 @@ pub fn enum_discriminants_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
168189
#(#discriminants),*
169190
}
170191

171-
impl #impl_generics #strum_module_path::IntoDiscriminant for #name #ty_generics #where_clause {
172-
type Discriminant = #discriminants_name;
173-
174-
#[inline]
175-
fn discriminant(&self) -> Self::Discriminant {
176-
<Self::Discriminant as ::core::convert::From<&Self>>::from(self)
177-
}
178-
}
179-
192+
#impl_into_discriminant
180193
#impl_from
181194
#impl_from_ref
182195
})

0 commit comments

Comments
 (0)