Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,6 @@ full = [
"chrono-tz",
"either",
"experimental-async",
"experimental-inspect",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I now added it dynamically in the _get_feature_sets function of the noxfile. Not sure if it's the best way to do it

"eyre",
"hashbrown",
"indexmap",
Expand Down
2 changes: 2 additions & 0 deletions newsfragments/5438.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Introspection: introduce `TypeHint` and make use of it to encode type hint annotations.
Rename `PyType{Info,Check}::TYPE_INFO` into `PyType{Info,Check}::TYPE_HINT`
14 changes: 13 additions & 1 deletion noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -1094,7 +1094,15 @@ def test_introspection(session: nox.Session):
for options in ([], ["--release"]):
if target is not None:
options += ("--target", target)
session.run_always("maturin", "develop", "-m", "./pytests/Cargo.toml", *options)
session.run_always(
"maturin",
"develop",
"-m",
"./pytests/Cargo.toml",
"--features",
"experimental-inspect",
*options,
)
# We look for the built library
lib_file = None
for file in Path(session.virtualenv.location).rglob("pyo3_pytests.*"):
Expand Down Expand Up @@ -1154,6 +1162,10 @@ def _get_feature_sets() -> Tuple[Optional[str], ...]:
# multiple-pymethods not supported on wasm
features += ",multiple-pymethods"

if get_rust_version() >= (1, 83, 0):
# experimental-inspect requires 1.83+
features += ",experimental-inspect"

if is_rust_nightly():
features += ",nightly"

Expand Down
1 change: 0 additions & 1 deletion pyo3-introspection/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ anyhow = "1"
goblin = ">=0.9, <0.11"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
unicode-ident = "1"

[dev-dependencies]
tempfile = "3.12.0"
Expand Down
121 changes: 106 additions & 15 deletions pyo3-introspection/src/introspection.rs
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like the annotation_stub stuff is still present, should we remove it at the same time?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code to extract modules was in the stubs.rs module and got removed

Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::model::{
Argument, Arguments, Attribute, Class, Function, Module, VariableLengthArgument,
Argument, Arguments, Attribute, Class, Function, Module, TypeHint, TypeHintExpr,
VariableLengthArgument,
};
use anyhow::{anyhow, bail, ensure, Context, Result};
use goblin::elf::section_header::SHN_XINDEX;
Expand All @@ -9,11 +10,13 @@ use goblin::mach::symbols::{NO_SECT, N_SECT};
use goblin::mach::{Mach, MachO, SingleArch};
use goblin::pe::PE;
use goblin::Object;
use serde::Deserialize;
use serde::de::value::MapAccessDeserializer;
use serde::de::{Error, MapAccess, Visitor};
use serde::{Deserialize, Deserializer};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::path::Path;
use std::{fs, str};
use std::{fmt, fs, str};

/// Introspect a cdylib built with PyO3 and returns the definition of a Python module.
///
Expand Down Expand Up @@ -192,7 +195,7 @@ fn convert_function(
name: &str,
arguments: &ChunkArguments,
decorators: &[String],
returns: &Option<String>,
returns: &Option<ChunkTypeHint>,
) -> Function {
Function {
name: name.into(),
Expand All @@ -210,30 +213,58 @@ fn convert_function(
.as_ref()
.map(convert_variable_length_argument),
},
returns: returns.clone(),
returns: returns.as_ref().map(convert_type_hint),
}
}

fn convert_argument(arg: &ChunkArgument) -> Argument {
Argument {
name: arg.name.clone(),
default_value: arg.default.clone(),
annotation: arg.annotation.clone(),
annotation: arg.annotation.as_ref().map(convert_type_hint),
}
}

fn convert_variable_length_argument(arg: &ChunkArgument) -> VariableLengthArgument {
VariableLengthArgument {
name: arg.name.clone(),
annotation: arg.annotation.clone(),
annotation: arg.annotation.as_ref().map(convert_type_hint),
}
}

fn convert_attribute(name: &str, value: &Option<String>, annotation: &Option<String>) -> Attribute {
fn convert_attribute(
name: &str,
value: &Option<String>,
annotation: &Option<ChunkTypeHint>,
) -> Attribute {
Attribute {
name: name.into(),
value: value.clone(),
annotation: annotation.clone(),
annotation: annotation.as_ref().map(convert_type_hint),
}
}

fn convert_type_hint(arg: &ChunkTypeHint) -> TypeHint {
match arg {
ChunkTypeHint::Ast(expr) => TypeHint::Ast(convert_type_hint_expr(expr)),
ChunkTypeHint::Plain(t) => TypeHint::Plain(t.clone()),
}
}

fn convert_type_hint_expr(expr: &ChunkTypeHintExpr) -> TypeHintExpr {
match expr {
ChunkTypeHintExpr::Builtin { id } => TypeHintExpr::Builtin { id: id.clone() },
ChunkTypeHintExpr::Attribute { module, attr } => TypeHintExpr::Attribute {
module: module.clone(),
attr: attr.clone(),
},
ChunkTypeHintExpr::Union { elts } => TypeHintExpr::Union {
elts: elts.iter().map(convert_type_hint_expr).collect(),
},
ChunkTypeHintExpr::Subscript { value, slice } => TypeHintExpr::Subscript {
value: Box::new(convert_type_hint_expr(value)),
slice: slice.iter().map(convert_type_hint_expr).collect(),
},
}
}

Expand Down Expand Up @@ -388,8 +419,8 @@ enum Chunk {
parent: Option<String>,
#[serde(default)]
decorators: Vec<String>,
#[serde(default)]
returns: Option<String>,
#[serde(default, deserialize_with = "deserialize_type_hint")]
returns: Option<ChunkTypeHint>,
},
Attribute {
#[serde(default)]
Expand All @@ -399,8 +430,8 @@ enum Chunk {
name: String,
#[serde(default)]
value: Option<String>,
#[serde(default)]
annotation: Option<String>,
#[serde(default, deserialize_with = "deserialize_type_hint")]
annotation: Option<ChunkTypeHint>,
},
}

Expand All @@ -423,6 +454,66 @@ struct ChunkArgument {
name: String,
#[serde(default)]
default: Option<String>,
#[serde(default)]
annotation: Option<String>,
#[serde(default, deserialize_with = "deserialize_type_hint")]
annotation: Option<ChunkTypeHint>,
}

enum ChunkTypeHint {
Ast(ChunkTypeHintExpr),
Plain(String),
}

#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
enum ChunkTypeHintExpr {
Builtin {
id: String,
},
Attribute {
module: String,
attr: String,
},
Union {
elts: Vec<ChunkTypeHintExpr>,
},
Subscript {
value: Box<ChunkTypeHintExpr>,
slice: Vec<ChunkTypeHintExpr>,
},
}

fn deserialize_type_hint<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Option<ChunkTypeHint>, D::Error> {
struct AnnotationVisitor;

impl<'de> Visitor<'de> for AnnotationVisitor {
type Value = ChunkTypeHint;

fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("annotation")
}

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_string(v.into())
}

fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
Ok(ChunkTypeHint::Plain(v))
}

fn visit_map<M: MapAccess<'de>>(self, map: M) -> Result<ChunkTypeHint, M::Error> {
Ok(ChunkTypeHint::Ast(Deserialize::deserialize(
MapAccessDeserializer::new(map),
)?))
}
}

Ok(Some(deserializer.deserialize_any(AnnotationVisitor)?))
}
33 changes: 29 additions & 4 deletions pyo3-introspection/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub struct Function {
pub decorators: Vec<String>,
pub arguments: Arguments,
/// return type
pub returns: Option<String>,
pub returns: Option<TypeHint>,
}

#[derive(Debug, Eq, PartialEq, Clone, Hash)]
Expand All @@ -31,7 +31,7 @@ pub struct Attribute {
/// Value as a Python expression if easily expressible
pub value: Option<String>,
/// Type annotation as a Python expression
pub annotation: Option<String>,
pub annotation: Option<TypeHint>,
}

#[derive(Debug, Eq, PartialEq, Clone, Hash)]
Expand All @@ -54,13 +54,38 @@ pub struct Argument {
/// Default value as a Python expression
pub default_value: Option<String>,
/// Type annotation as a Python expression
pub annotation: Option<String>,
pub annotation: Option<TypeHint>,
}

/// A variable length argument ie. *vararg or **kwarg
#[derive(Debug, Eq, PartialEq, Clone, Hash)]
pub struct VariableLengthArgument {
pub name: String,
/// Type annotation as a Python expression
pub annotation: Option<String>,
pub annotation: Option<TypeHint>,
}

/// A type hint annotation
///
/// Might be a plain string or an AST fragment
#[derive(Debug, Eq, PartialEq, Clone, Hash)]
pub enum TypeHint {
Ast(TypeHintExpr),
Plain(String),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is for custom type hint witten in the #[pyo3(signature = ] attribute.

}

/// A type hint annotation as an AST fragment
#[derive(Debug, Eq, PartialEq, Clone, Hash)]
pub enum TypeHintExpr {
/// A Python builtin like `int`
Builtin { id: String },
/// The attribute of a python object like `{value}.{attr}`
Attribute { module: String, attr: String },
/// A union `{left} | {right}`
Union { elts: Vec<TypeHintExpr> },
/// A subscript `{value}[*slice]`
Subscript {
value: Box<TypeHintExpr>,
slice: Vec<TypeHintExpr>,
},
}
Loading
Loading