From 87fb6bfde5d900c09b2f0932a222200d1d291991 Mon Sep 17 00:00:00 2001 From: Icxolu <10486322+Icxolu@users.noreply.github.com> Date: Sat, 4 May 2024 16:56:10 +0200 Subject: [PATCH] store the `FnArg` ident as a `Cow` instead of a reference This allow also storing idents that were generated as part of the macro instead of only ones the were present in the source code. This is needed for example in complex enum tuple variants. --- pyo3-macros-backend/src/method.rs | 21 ++++++++++++++------- pyo3-macros-backend/src/pyclass.rs | 2 +- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/pyo3-macros-backend/src/method.rs b/pyo3-macros-backend/src/method.rs index 982cf62946e..cb86e8ec606 100644 --- a/pyo3-macros-backend/src/method.rs +++ b/pyo3-macros-backend/src/method.rs @@ -1,3 +1,4 @@ +use std::borrow::Cow; use std::fmt::Display; use proc_macro2::{Span, TokenStream}; @@ -18,7 +19,7 @@ use crate::{ #[derive(Clone, Debug)] pub struct RegularArg<'a> { - pub name: &'a syn::Ident, + pub name: Cow<'a, syn::Ident>, pub ty: &'a syn::Type, pub from_py_with: Option, pub default_value: Option, @@ -28,14 +29,14 @@ pub struct RegularArg<'a> { /// Pythons *args argument #[derive(Clone, Debug)] pub struct VarargsArg<'a> { - pub name: &'a syn::Ident, + pub name: Cow<'a, syn::Ident>, pub ty: &'a syn::Type, } /// Pythons **kwarg argument #[derive(Clone, Debug)] pub struct KwargsArg<'a> { - pub name: &'a syn::Ident, + pub name: Cow<'a, syn::Ident>, pub ty: &'a syn::Type, } @@ -61,7 +62,7 @@ pub enum FnArg<'a> { } impl<'a> FnArg<'a> { - pub fn name(&self) -> &'a syn::Ident { + pub fn name(&self) -> &syn::Ident { match self { FnArg::Regular(RegularArg { name, .. }) => name, FnArg::VarArgs(VarargsArg { name, .. }) => name, @@ -98,7 +99,10 @@ impl<'a> FnArg<'a> { .. }) = self { - *self = Self::VarArgs(VarargsArg { name, ty }); + *self = Self::VarArgs(VarargsArg { + name: name.clone(), + ty, + }); Ok(self) } else { bail_spanned!(self.name().span() => "args cannot be optional") @@ -113,7 +117,10 @@ impl<'a> FnArg<'a> { .. }) = self { - *self = Self::KwArgs(KwargsArg { name, ty }); + *self = Self::KwArgs(KwargsArg { + name: name.clone(), + ty, + }); Ok(self) } else { bail_spanned!(self.name().span() => "kwargs must be Option<_>") @@ -159,7 +166,7 @@ impl<'a> FnArg<'a> { } Ok(Self::Regular(RegularArg { - name: ident, + name: Cow::Borrowed(ident), ty: &cap.ty, from_py_with, default_value: None, diff --git a/pyo3-macros-backend/src/pyclass.rs b/pyo3-macros-backend/src/pyclass.rs index d9c84655b42..f8bfa164d7d 100644 --- a/pyo3-macros-backend/src/pyclass.rs +++ b/pyo3-macros-backend/src/pyclass.rs @@ -1153,7 +1153,7 @@ fn complex_enum_struct_variant_new<'a>( for field in &variant.fields { args.push(FnArg::Regular(RegularArg { - name: field.ident, + name: Cow::Borrowed(field.ident), ty: field.ty, from_py_with: None, default_value: None,