From 96003f03a4803bf11999f5ea9d75102d1cbd016b Mon Sep 17 00:00:00 2001 From: Vincent Alsteen Date: Thu, 21 Dec 2023 16:01:38 +0100 Subject: [PATCH] fix support for lifetimes --- src/enum_variant_accessor.rs | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/src/enum_variant_accessor.rs b/src/enum_variant_accessor.rs index 15e8d1b..4d83d5e 100644 --- a/src/enum_variant_accessor.rs +++ b/src/enum_variant_accessor.rs @@ -2,10 +2,7 @@ use either::Either; use proc_macro2::{Delimiter, Ident, Span, TokenStream, TokenTree}; use quote::{quote_spanned, ToTokens, TokenStreamExt}; use syn::token::Mut; -use syn::{ - self, spanned::Spanned, Attribute, Data, DeriveInput, Error, Expr, ExprParen, ExprPath, Fields, FieldsNamed, Meta, - MetaList, Token, Type, TypeReference, Variant, -}; +use syn::{self, spanned::Spanned, Attribute, Data, DeriveInput, Error, Expr, ExprParen, ExprPath, Fields, FieldsNamed, Meta, MetaList, Token, Type, TypeReference, Variant, GenericParam}; const ATTR_HELP: &str = "EnumAccessor: Invalid accessor declaration, expected #[accessor(field1: type, except(VariantWithoutAccessor1,VariantWithoutAccessor2))]"; const ENUM_HELP: &str = "EnumAccessor: only variants with one unnamed parameter, unit and named variants are supported"; @@ -445,11 +442,21 @@ pub fn impl_enum_accessor(input: DeriveInput) -> TokenStream { let generics = &input.generics; let where_clause = &input.generics.where_clause; - let generics_params = &input.generics.params.to_token_stream(); + + let generics_params = &input + .generics + .params + .iter() + .map(|p| match p { + GenericParam::Type(t) => t.ident.to_token_stream(), + GenericParam::Const(t) => t.ident.to_token_stream(), + GenericParam::Lifetime(t) => t.to_token_stream(), + }) + .collect::>(); syn::parse_quote_spanned! {input_span => #[allow(dead_code)] - impl #generics #ident <#generics_params> #where_clause { + impl #generics #ident <#(#generics_params),*> #where_clause { #(#accessor_impls)* } } @@ -563,10 +570,10 @@ impl SomeEnum { fn test_lifetimes() { let input = syn::parse_quote! { #[accessor(acc1: usize, (B))] - enum SomeEnum<'a> { - A(a), + enum SomeEnum<'a, Get: Fn() -> u8> { + A(A), B, - C(b<'a>) + C(&'a Get) } }; @@ -576,7 +583,7 @@ impl SomeEnum { assert_eq!( output, r"#[allow(dead_code)] -impl<'a> SomeEnum<'a> { +impl<'a, Get: Fn() -> u8> SomeEnum<'a, Get> { pub fn acc1(&self) -> std::option::Option<&usize> { match self { Self::A(x, ..) => std::option::Option::Some(&x.acc1),