Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the problem with deriving Debug with other attributes #15

Merged
merged 3 commits into from
Nov 18, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 32 additions & 20 deletions derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ use quote::{format_ident, quote, ToTokens};
use repr::Repr;
use std::collections::HashSet;
use syn::{
parse_macro_input, punctuated::Punctuated, spanned::Spanned, Error, Ident, ItemEnum, Path,
Token, Visibility,
parse_macro_input, spanned::Spanned, Error, Ident, ItemEnum, Meta, MetaList, NestedMeta,
Visibility,
};

/// Sets the span for every token tree in the token stream
Expand Down Expand Up @@ -96,6 +96,25 @@ fn emit_debug_impl<'a>(
})
}

fn generate_derive_set(
nested: &syn::punctuated::Punctuated<NestedMeta, syn::token::Comma>,
allow_alias: bool,
derive_set: &mut HashSet<String>,
) -> bool {
let mut make_custom_debug_impl = false;
for nested_meta in nested.iter() {
if let NestedMeta::Meta(inner_meta) = nested_meta {
let inner_meta_str = format!("{}", quote::quote!(#inner_meta));
if inner_meta_str.contains("Debug") && !allow_alias {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would break a derive some_crate::DeriveThatHasDebugInTheName.

Can you instead have it only "capture" a Debug derive if its path is exactly one of these:

  • Debug
  • fmt::Debug
  • ::core::fmt::Debug
  • core::fmt::Debug
  • ::std::fmt::Debug
  • std::fmt::Debug

It's unlikely (albeit possible) that these would conflict with other derives

make_custom_debug_impl = true;
} else {
derive_set.insert(inner_meta_str);
}
}
}
make_custom_debug_impl
}

fn open_enum_impl(
enum_: ItemEnum,
Config {
Expand Down Expand Up @@ -135,31 +154,24 @@ fn open_enum_impl(

// To make `match` seamless, derive(PartialEq, Eq) if they aren't already.
let mut our_derives = HashSet::new();
our_derives.insert("PartialEq");
our_derives.insert("Eq");
our_derives.insert("PartialEq".to_owned());
our_derives.insert("Eq".to_owned());
let mut make_custom_debug_impl = false;
for attr in &enum_.attrs {
let mut include_in_struct = true;
// Turns out `is_ident` does a `to_string` every time
match attr.path.to_token_stream().to_string().as_str() {
"derive" => {
let derives =
attr.parse_args_with(Punctuated::<Path, Token![,]>::parse_terminated)?;
for derive in derives {
if derive.is_ident("PartialEq") {
our_derives.remove("PartialEq");
} else if derive.is_ident("Eq") {
our_derives.remove("Eq");
}

// If we allow aliasing, then don't bother with a custom
// debug impl. There's no way to tell which alias we should
// print.
if derive.is_ident("Debug") && !allow_alias {
make_custom_debug_impl = true;
include_in_struct = false;
if let Some(meta) = attr.parse_meta().ok() {
if let Meta::List(MetaList {
path: _, nested, ..
}) = meta
{
make_custom_debug_impl =
generate_derive_set(&nested, allow_alias, &mut our_derives);
}
}
include_in_struct = false;
}
// Copy linting attribute to the impl.
"allow" | "warn" | "deny" | "forbid" => impl_attrs.push(attr.to_token_stream()),
Expand Down Expand Up @@ -199,7 +211,7 @@ fn open_enum_impl(
if !our_derives.is_empty() {
let our_derives = our_derives
.into_iter()
.map(|d| Ident::new(d, Span::call_site()));
.map(|d| Ident::new(&d, Span::call_site()));
struct_attrs.push(quote!(#[derive(#(#our_derives),*)]));
}

Expand Down
66 changes: 66 additions & 0 deletions tests/derives.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright © 2023 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

extern crate open_enum;
use open_enum::*;

#[open_enum]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum Color3 {
Red = 0x0,
White = 0x1,
}

#[open_enum]
#[derive(core::fmt::Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum Color4 {
Red = 0x0,
White = 0x1,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct EmbeddedColor {
pub color: Color3,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct EmbeddedColorExtension {
pub color: Color4,
}

#[test]
fn embedded_enum_struct() {
let test_struct = EmbeddedColor { color: Color3::Red };

assert_eq!(test_struct.color, Color3::Red);

let expected_debug_str = "EmbeddedColor { color: Red }";
let debug_str = format!("{:?}", test_struct);

assert_eq!(expected_debug_str, debug_str);
}

#[test]
fn extended_embedded_enum_struct() {
let test_struct = EmbeddedColorExtension { color: Color4::Red };

assert_eq!(test_struct.color, Color4::Red);

let expected_debug_str = "EmbeddedColorExtension { color: Red }";
let debug_str = format!("{:?}", test_struct);

assert_eq!(expected_debug_str, debug_str);
}