Skip to content

Commit

Permalink
wip: debug/08-escape-hatch
Browse files Browse the repository at this point in the history
  • Loading branch information
yue4u committed Feb 4, 2024
1 parent 7c1ec9d commit 6e73f7e
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 6 deletions.
37 changes: 33 additions & 4 deletions debug/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::{
parse_macro_input, AngleBracketedGenericArguments, DeriveInput, ExprLit, GenericArgument, Lit,
MetaNameValue, Path, PathArguments, PathSegment, Type, TypePath,
Meta, MetaNameValue, Path, PathArguments, PathSegment, Type, TypePath,
};

#[proc_macro_derive(CustomDebug, attributes(debug))]
Expand All @@ -25,6 +25,33 @@ pub fn derive(input: TokenStream) -> TokenStream {
associated.insert(ty.ident.to_string(), vec![]);
});

let custom_bound = input.attrs.iter().find_map(|attr| {
if attr.path().is_ident("debug") {
if let Ok(meta) = attr.parse_args::<Meta>() {
if let Ok(MetaNameValue {
value:
syn::Expr::Lit(ExprLit {
lit: Lit::Str(lit_str),
..
}),
..
}) = meta.require_name_value()
{
return Some(
lit_str
.value()
.parse::<proc_macro2::TokenStream>()
.unwrap_or(
syn::Error::new(lit_str.span(), "expect to be token stream")
.into_compile_error(),
),
);
}
}
}
None
});

let mut fields = vec![];
match &input.data {
syn::Data::Struct(s) => {
Expand Down Expand Up @@ -58,7 +85,9 @@ pub fn derive(input: TokenStream) -> TokenStream {
_ => {}
};

collect_associated_types(&f.ty, &mut associated);
if custom_bound.is_none() {
collect_associated_types(&f.ty, &mut associated);
}

let display = match fmt {
Some(fmt) => quote!(&format_args!(#fmt, &self.#field_name)),
Expand Down Expand Up @@ -98,9 +127,9 @@ pub fn derive(input: TokenStream) -> TokenStream {

let (bound, type_generics) = if bounds.len() > 0 {
(
quote!(
custom_bound.unwrap_or(quote!(
#(#bounds),*
),
)),
quote!(
<#(#types),*>
),
Expand Down
2 changes: 1 addition & 1 deletion debug/tests/progress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ fn tests() {
t.pass("tests/05-phantom-data.rs");
t.pass("tests/06-bound-trouble.rs");
t.pass("tests/07-associated-type.rs");
//t.pass("tests/08-escape-hatch.rs");
t.pass("tests/08-escape-hatch.rs");
}
9 changes: 8 additions & 1 deletion main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,20 @@
// To run the code:
// $ cargo run
use derive_debug::CustomDebug;
use std::fmt::Debug;

pub trait Trait {
type Value;
}

#[derive(CustomDebug)]
pub struct Field<T: Trait> {
#[debug(bound = "T::Value: Debug")]
pub struct Wrapper<T: Trait> {
field: Field<T>,
}

#[derive(CustomDebug)]
struct Field<T: Trait> {
values: Vec<T::Value>,
}

Expand Down

0 comments on commit 6e73f7e

Please sign in to comment.