-
Notifications
You must be signed in to change notification settings - Fork 905
Basic introspection of #[derive(FromPyObject)] #5339
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Basic introspection of `#[derive(FromPyObject)]` (no struct fields support yet) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,9 @@ | ||
| use crate::attributes::{DefaultAttribute, FromPyWithAttribute, RenamingRule}; | ||
| use crate::derive_attributes::{ContainerAttributes, FieldAttributes, FieldGetter}; | ||
| #[cfg(feature = "experimental-inspect")] | ||
| use crate::introspection::ConcatenationBuilder; | ||
| #[cfg(feature = "experimental-inspect")] | ||
| use crate::utils::TypeExt; | ||
| use crate::utils::{self, Ctx}; | ||
| use proc_macro2::TokenStream; | ||
| use quote::{format_ident, quote, quote_spanned, ToTokens}; | ||
|
|
@@ -96,17 +100,29 @@ impl<'a> Enum<'a> { | |
| ) | ||
| ) | ||
| } | ||
|
|
||
| #[cfg(feature = "experimental-inspect")] | ||
| fn write_input_type(&self, builder: &mut ConcatenationBuilder, ctx: &Ctx) { | ||
| for (i, var) in self.variants.iter().enumerate() { | ||
| if i > 0 { | ||
| builder.push_str(" | "); | ||
| } | ||
| var.write_input_type(builder, ctx); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| struct NamedStructField<'a> { | ||
| ident: &'a syn::Ident, | ||
| getter: Option<FieldGetter>, | ||
| from_py_with: Option<FromPyWithAttribute>, | ||
| default: Option<DefaultAttribute>, | ||
| ty: &'a syn::Type, | ||
| } | ||
|
|
||
| struct TupleStructField { | ||
| from_py_with: Option<FromPyWithAttribute>, | ||
| ty: syn::Type, | ||
| } | ||
|
|
||
| /// Container Style | ||
|
|
@@ -120,7 +136,8 @@ enum ContainerType<'a> { | |
| /// Newtype struct container, e.g. `#[transparent] struct Foo { a: String }` | ||
| /// | ||
| /// The field specified by the identifier is extracted directly from the object. | ||
| StructNewtype(&'a syn::Ident, Option<FromPyWithAttribute>), | ||
| #[cfg_attr(not(feature = "experimental-inspect"), allow(unused))] | ||
| StructNewtype(&'a syn::Ident, Option<FromPyWithAttribute>, &'a syn::Type), | ||
| /// Tuple struct, e.g. `struct Foo(String)`. | ||
| /// | ||
| /// Variant contains a list of conversion methods for each of the fields that are directly | ||
|
|
@@ -129,7 +146,8 @@ enum ContainerType<'a> { | |
| /// Tuple newtype, e.g. `#[transparent] struct Foo(String)` | ||
| /// | ||
| /// The wrapped field is directly extracted from the object. | ||
| TupleNewtype(Option<FromPyWithAttribute>), | ||
| #[cfg_attr(not(feature = "experimental-inspect"), allow(unused))] | ||
| TupleNewtype(Option<FromPyWithAttribute>, Box<syn::Type>), | ||
| } | ||
|
|
||
| /// Data container | ||
|
|
@@ -168,6 +186,7 @@ impl<'a> Container<'a> { | |
| ); | ||
| Ok(TupleStructField { | ||
| from_py_with: attrs.from_py_with, | ||
| ty: field.ty.clone(), | ||
| }) | ||
| }) | ||
| .collect::<Result<Vec<_>>>()?; | ||
|
|
@@ -176,7 +195,7 @@ impl<'a> Container<'a> { | |
| // Always treat a 1-length tuple struct as "transparent", even without the | ||
| // explicit annotation. | ||
| let field = tuple_fields.pop().unwrap(); | ||
| ContainerType::TupleNewtype(field.from_py_with) | ||
| ContainerType::TupleNewtype(field.from_py_with, Box::new(field.ty)) | ||
| } else if options.transparent.is_some() { | ||
| bail_spanned!( | ||
| fields.span() => "transparent structs and variants can only have 1 field" | ||
|
|
@@ -216,6 +235,7 @@ impl<'a> Container<'a> { | |
| getter: attrs.getter, | ||
| from_py_with: attrs.from_py_with, | ||
| default: attrs.default, | ||
| ty: &field.ty, | ||
| }) | ||
| }) | ||
| .collect::<Result<Vec<_>>>()?; | ||
|
|
@@ -237,7 +257,7 @@ impl<'a> Container<'a> { | |
| field.getter.is_none(), | ||
| field.ident.span() => "`transparent` structs may not have a `getter` for the inner field" | ||
| ); | ||
| ContainerType::StructNewtype(field.ident, field.from_py_with) | ||
| ContainerType::StructNewtype(field.ident, field.from_py_with, field.ty) | ||
| } else { | ||
| ContainerType::Struct(struct_fields) | ||
| } | ||
|
|
@@ -274,10 +294,10 @@ impl<'a> Container<'a> { | |
| /// Build derivation body for a struct. | ||
| fn build(&self, ctx: &Ctx) -> TokenStream { | ||
| match &self.ty { | ||
| ContainerType::StructNewtype(ident, from_py_with) => { | ||
| ContainerType::StructNewtype(ident, from_py_with, _) => { | ||
| self.build_newtype_struct(Some(ident), from_py_with, ctx) | ||
| } | ||
| ContainerType::TupleNewtype(from_py_with) => { | ||
| ContainerType::TupleNewtype(from_py_with, _) => { | ||
| self.build_newtype_struct(None, from_py_with, ctx) | ||
| } | ||
| ContainerType::Tuple(tups) => self.build_tuple_struct(tups, ctx), | ||
|
|
@@ -438,6 +458,51 @@ impl<'a> Container<'a> { | |
|
|
||
| quote!(::std::result::Result::Ok(#self_ty{#fields})) | ||
| } | ||
|
|
||
| #[cfg(feature = "experimental-inspect")] | ||
| fn write_input_type(&self, builder: &mut ConcatenationBuilder, ctx: &Ctx) { | ||
| match &self.ty { | ||
| ContainerType::StructNewtype(_, from_py_with, ty) => { | ||
| Self::write_field_input_type(from_py_with, ty, builder, ctx); | ||
| } | ||
| ContainerType::TupleNewtype(from_py_with, ty) => { | ||
| Self::write_field_input_type(from_py_with, ty, builder, ctx); | ||
| } | ||
| ContainerType::Tuple(tups) => { | ||
| builder.push_str("tuple["); | ||
| for (i, TupleStructField { from_py_with, ty }) in tups.iter().enumerate() { | ||
| if i > 0 { | ||
| builder.push_str(", "); | ||
| } | ||
| Self::write_field_input_type(from_py_with, ty, builder, ctx); | ||
| } | ||
| builder.push_str("]"); | ||
| } | ||
| ContainerType::Struct(_) => { | ||
| // TODO: implement using a Protocol? | ||
| builder.push_str("_typeshed.Incomplete") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(feature = "experimental-inspect")] | ||
| fn write_field_input_type( | ||
| from_py_with: &Option<FromPyWithAttribute>, | ||
| ty: &syn::Type, | ||
| builder: &mut ConcatenationBuilder, | ||
| ctx: &Ctx, | ||
| ) { | ||
| if from_py_with.is_some() { | ||
| // We don't know what from_py_with is doing | ||
| builder.push_str("_typeshed.Incomplete") | ||
|
Comment on lines
+496
to
+497
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It would be interesting to discuss how we make this work, I guess some manually-applied type hint would be the only way. |
||
| } else { | ||
| let ty = ty.clone().elide_lifetimes(); | ||
| let pyo3_crate_path = &ctx.pyo3_path; | ||
| builder.push_tokens( | ||
| quote! { <#ty as #pyo3_crate_path::FromPyObject<'_>>::INPUT_TYPE.as_bytes() }, | ||
| ) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn verify_and_get_lifetime(generics: &syn::Generics) -> Result<Option<&syn::LifetimeParam>> { | ||
|
|
@@ -487,29 +552,64 @@ pub fn build_derive_from_pyobject(tokens: &DeriveInput) -> Result<TokenStream> { | |
| bail_spanned!(tokens.span() => "`transparent` or `annotation` is not supported \ | ||
| at top level for enums"); | ||
| } | ||
| let en = Enum::new(en, &tokens.ident, options)?; | ||
| let en = Enum::new(en, &tokens.ident, options.clone())?; | ||
| en.build(ctx) | ||
| } | ||
| syn::Data::Struct(st) => { | ||
| if let Some(lit_str) = &options.annotation { | ||
| bail_spanned!(lit_str.span() => "`annotation` is unsupported for structs"); | ||
| } | ||
| let ident = &tokens.ident; | ||
| let st = Container::new(&st.fields, parse_quote!(#ident), options)?; | ||
| let st = Container::new(&st.fields, parse_quote!(#ident), options.clone())?; | ||
| st.build(ctx) | ||
| } | ||
| syn::Data::Union(_) => bail_spanned!( | ||
| tokens.span() => "#[derive(FromPyObject)] is not supported for unions" | ||
| ), | ||
| }; | ||
|
|
||
| #[cfg(feature = "experimental-inspect")] | ||
| let input_type = { | ||
| let mut builder = ConcatenationBuilder::default(); | ||
| if tokens | ||
| .generics | ||
| .params | ||
| .iter() | ||
| .all(|p| matches!(p, syn::GenericParam::Lifetime(_))) | ||
| { | ||
| match &tokens.data { | ||
| syn::Data::Enum(en) => { | ||
| Enum::new(en, &tokens.ident, options)?.write_input_type(&mut builder, ctx) | ||
| } | ||
| syn::Data::Struct(st) => { | ||
| let ident = &tokens.ident; | ||
| Container::new(&st.fields, parse_quote!(#ident), options.clone())? | ||
| .write_input_type(&mut builder, ctx) | ||
| } | ||
| syn::Data::Union(_) => { | ||
| // Not supported at this point | ||
| builder.push_str("_typeshed.Incomplete") | ||
| } | ||
| } | ||
| } else { | ||
| // We don't know how to deal with generic parameters | ||
| // Blocked by https://github.com/rust-lang/rust/issues/76560 | ||
| builder.push_str("_typeshed.Incomplete") | ||
| }; | ||
| let input_type = builder.into_token_stream(&ctx.pyo3_path); | ||
| quote! { const INPUT_TYPE: &'static str = unsafe { ::std::str::from_utf8_unchecked(#input_type) }; } | ||
| }; | ||
| #[cfg(not(feature = "experimental-inspect"))] | ||
| let input_type = quote! {}; | ||
|
|
||
| let ident = &tokens.ident; | ||
| Ok(quote!( | ||
| #[automatically_derived] | ||
| impl #impl_generics #pyo3_path::FromPyObject<#lt_param> for #ident #ty_generics #where_clause { | ||
| fn extract_bound(obj: &#pyo3_path::Bound<#lt_param, #pyo3_path::PyAny>) -> #pyo3_path::PyResult<Self> { | ||
| #derives | ||
| } | ||
| #input_type | ||
| } | ||
| )) | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -219,6 +219,9 @@ pub trait PyClassImpl: Sized + 'static { | |
| /// from the PyClassDocGenerator` type. | ||
| const DOC: &'static CStr; | ||
|
|
||
| #[cfg(feature = "experimental-inspect")] | ||
| const TYPE_NAME: &'static str; | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Useful to initialize |
||
|
|
||
| fn items_iter() -> PyClassItemsIter; | ||
|
|
||
| #[inline] | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
_typeshed.Incompleteis an alias oftyping.Anythat hints that the type should be edited to something smaller: https://typing.python.org/en/latest/guides/writing_stubs.html#incomplete-stubsThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A protocol seems like the right approach; we want to describe the shape of what we expect without any knowledge of its actual type, given we fully duck-type the extraction.