From e309d01a2c78fe24edba83542bc7005bfb195465 Mon Sep 17 00:00:00 2001 From: David Koloski Date: Sun, 8 Sep 2024 13:15:38 -0400 Subject: [PATCH] Handle raw variant names correctly --- bytecheck_derive/src/lib.rs | 14 +++++++++----- bytecheck_derive/src/util.rs | 11 ++++++++++- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/bytecheck_derive/src/lib.rs b/bytecheck_derive/src/lib.rs index 19c6148..3ae6e42 100644 --- a/bytecheck_derive/src/lib.rs +++ b/bytecheck_derive/src/lib.rs @@ -23,7 +23,7 @@ use syn::{ use crate::{ attributes::{Attributes, FieldAttributes}, repr::Repr, - util::iter_fields, + util::{iter_fields, strip_raw}, }; /// Derives `CheckBytes` for the labeled type. @@ -321,8 +321,10 @@ fn derive_check_bytes(mut input: DeriveInput) -> Result { let variant_structs = data.variants.iter().map(|v| { let variant = &v.ident; - let variant_name = - Ident::new(&format!("Variant{variant}"), v.span()); + let variant_name = Ident::new( + &format!("Variant{}", strip_raw(variant)), + v.span(), + ); match v.fields { Fields::Named(ref fields) => { let fields = fields.named.iter().map(|f| { @@ -365,8 +367,10 @@ fn derive_check_bytes(mut input: DeriveInput) -> Result { let check_arms = data.variants.iter().map(|v| { let variant = &v.ident; - let variant_name = - Ident::new(&format!("Variant{variant}"), v.span()); + let variant_name = Ident::new( + &format!("Variant{}", strip_raw(variant)), + v.span(), + ); match v.fields { Fields::Named(ref fields) => { let checks = fields.named.iter().map(|f| { diff --git a/bytecheck_derive/src/util.rs b/bytecheck_derive/src/util.rs index 678e048..2858d96 100644 --- a/bytecheck_derive/src/util.rs +++ b/bytecheck_derive/src/util.rs @@ -1,7 +1,8 @@ use core::iter::FlatMap; use syn::{ - punctuated::Iter, Data, DataEnum, DataStruct, DataUnion, Field, Variant, + punctuated::Iter, Data, DataEnum, DataStruct, DataUnion, Field, Ident, + Variant, }; type VariantFieldsFn = fn(&Variant) -> Iter<'_, Field>; @@ -39,3 +40,11 @@ pub fn iter_fields(data: &Data) -> FieldsIter<'_> { } } } + +pub fn strip_raw(ident: &Ident) -> String { + let as_string = ident.to_string(); + as_string + .strip_prefix("r#") + .map(ToString::to_string) + .unwrap_or(as_string) +}