pyo3_stub_gen/stub_type/
builtins.rs

1//! Define PyStubType for built-in types based on <https://pyo3.rs/v0.22.2/conversions/tables#argument-types>
2
3use crate::runtime::{union_type, PyRuntimeType};
4use crate::stub_type::*;
5use ::pyo3::prelude::*;
6use ::pyo3::types::{PyBool, PyComplex, PyFloat, PyInt, PyString};
7use std::{
8    borrow::Cow,
9    ffi::{OsStr, OsString},
10    path::PathBuf,
11    rc::Rc,
12    sync::Arc,
13    time::SystemTime,
14};
15
16macro_rules! impl_builtin {
17    ($ty:ty, $pytype:expr, $py_type_obj:ty) => {
18        impl PyStubType for $ty {
19            fn type_output() -> TypeInfo {
20                TypeInfo::builtin($pytype)
21            }
22        }
23        impl PyRuntimeType for $ty {
24            fn runtime_type_object(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
25                Ok(py.get_type::<$py_type_obj>().into_any())
26            }
27        }
28    };
29}
30
31macro_rules! impl_with_module {
32    ($ty:ty, $pytype:expr, $module:expr) => {
33        impl PyStubType for $ty {
34            fn type_output() -> TypeInfo {
35                TypeInfo::with_module($pytype, $module.into())
36            }
37        }
38        impl PyRuntimeType for $ty {
39            fn runtime_type_object(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
40                // Import the type from the Python module
41                let module = py.import($module)?;
42                // Extract just the type name from "module.TypeName"
43                let type_name = $pytype.rsplit('.').next().unwrap_or($pytype);
44                module.getattr(type_name)
45            }
46        }
47    };
48}
49
50// NOTE:
51impl PyStubType for () {
52    fn type_output() -> TypeInfo {
53        TypeInfo::none()
54    }
55}
56impl PyRuntimeType for () {
57    fn runtime_type_object(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
58        // None type in Python
59        Ok(py.get_type::<::pyo3::types::PyNone>().into_any())
60    }
61}
62
63impl_builtin!(bool, "bool", PyBool);
64impl_builtin!(u8, "int", PyInt);
65impl_builtin!(u16, "int", PyInt);
66impl_builtin!(u32, "int", PyInt);
67impl_builtin!(u64, "int", PyInt);
68impl_builtin!(u128, "int", PyInt);
69impl_builtin!(usize, "int", PyInt);
70impl_builtin!(i8, "int", PyInt);
71impl_builtin!(i16, "int", PyInt);
72impl_builtin!(i32, "int", PyInt);
73impl_builtin!(i64, "int", PyInt);
74impl_builtin!(i128, "int", PyInt);
75impl_builtin!(isize, "int", PyInt);
76impl_builtin!(f32, "float", PyFloat);
77impl_builtin!(f64, "float", PyFloat);
78impl_builtin!(num_complex::Complex32, "complex", PyComplex);
79impl_builtin!(num_complex::Complex64, "complex", PyComplex);
80
81impl_builtin!(std::num::NonZeroU8, "int", PyInt);
82impl_builtin!(std::num::NonZeroU16, "int", PyInt);
83impl_builtin!(std::num::NonZeroU32, "int", PyInt);
84impl_builtin!(std::num::NonZeroU64, "int", PyInt);
85impl_builtin!(std::num::NonZeroU128, "int", PyInt);
86impl_builtin!(std::num::NonZeroUsize, "int", PyInt);
87impl_builtin!(std::num::NonZeroI8, "int", PyInt);
88impl_builtin!(std::num::NonZeroI16, "int", PyInt);
89impl_builtin!(std::num::NonZeroI32, "int", PyInt);
90impl_builtin!(std::num::NonZeroI64, "int", PyInt);
91impl_builtin!(std::num::NonZeroI128, "int", PyInt);
92impl_builtin!(std::num::NonZeroIsize, "int", PyInt);
93
94impl_builtin!(char, "str", PyString);
95impl_builtin!(&str, "str", PyString);
96impl_builtin!(OsStr, "str", PyString);
97impl_builtin!(String, "str", PyString);
98impl_builtin!(OsString, "str", PyString);
99impl_builtin!(Cow<'_, str>, "str", PyString);
100impl_builtin!(Cow<'_, OsStr>, "str", PyString);
101impl_builtin!(Cow<'_, [u8]>, "bytes", ::pyo3::types::PyBytes);
102
103#[cfg(feature = "jiff-02")]
104mod impl_jiff_02 {
105    use super::*;
106
107    impl_with_module!(jiff_02::Timestamp, "datetime.datetime", "datetime");
108    impl_with_module!(jiff_02::Zoned, "datetime.datetime", "datetime");
109    impl_with_module!(jiff_02::civil::DateTime, "datetime.datetime", "datetime");
110    impl_with_module!(jiff_02::civil::Date, "datetime.date", "datetime");
111    impl_with_module!(jiff_02::civil::Time, "datetime.time", "datetime");
112    impl_with_module!(jiff_02::civil::ISOWeekDate, "datetime.date", "datetime");
113    impl_with_module!(jiff_02::tz::Offset, "datetime.tzinfo", "datetime");
114    impl_with_module!(jiff_02::tz::TimeZone, "datetime.tzinfo", "datetime");
115    impl_with_module!(jiff_02::SignedDuration, "datetime.timedelta", "datetime");
116    impl_with_module!(jiff_02::Span, "datetime.timedelta", "datetime");
117}
118
119#[cfg(feature = "ordered-float")]
120mod impl_ordered_float {
121    use super::*;
122    use ::pyo3::types::PyFloat;
123    impl_builtin!(ordered_float::NotNan<f32>, "float", PyFloat);
124    impl_builtin!(ordered_float::NotNan<f64>, "float", PyFloat);
125    impl_builtin!(ordered_float::OrderedFloat<f32>, "float", PyFloat);
126    impl_builtin!(ordered_float::OrderedFloat<f64>, "float", PyFloat);
127}
128
129impl PyStubType for PathBuf {
130    fn type_output() -> TypeInfo {
131        TypeInfo::with_module("pathlib.Path", "pathlib".into())
132    }
133    fn type_input() -> TypeInfo {
134        TypeInfo::builtin("str")
135            | TypeInfo::with_module("os.PathLike", "os".into())
136            | TypeInfo::with_module("pathlib.Path", "pathlib".into())
137    }
138}
139impl PyRuntimeType for PathBuf {
140    fn runtime_type_object(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
141        let pathlib = py.import("pathlib")?;
142        pathlib.getattr("Path")
143    }
144}
145
146impl<Tz: chrono::TimeZone> PyStubType for chrono::DateTime<Tz> {
147    fn type_output() -> TypeInfo {
148        TypeInfo::with_module("datetime.datetime", "datetime".into())
149    }
150}
151impl<Tz: chrono::TimeZone> PyRuntimeType for chrono::DateTime<Tz> {
152    fn runtime_type_object(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
153        let datetime = py.import("datetime")?;
154        datetime.getattr("datetime")
155    }
156}
157
158impl_with_module!(SystemTime, "datetime.datetime", "datetime");
159impl_with_module!(chrono::NaiveDateTime, "datetime.datetime", "datetime");
160impl_with_module!(chrono::NaiveDate, "datetime.date", "datetime");
161impl_with_module!(chrono::NaiveTime, "datetime.time", "datetime");
162impl_with_module!(chrono::FixedOffset, "datetime.tzinfo", "datetime");
163impl_with_module!(chrono::Utc, "datetime.tzinfo", "datetime");
164impl_with_module!(std::time::Duration, "datetime.timedelta", "datetime");
165impl_with_module!(chrono::Duration, "datetime.timedelta", "datetime");
166impl_with_module!(time::Duration, "datetime.timedelta", "datetime");
167impl_with_module!(time::Date, "datetime.date", "datetime");
168impl_with_module!(time::OffsetDateTime, "datetime.datetime", "datetime");
169impl_with_module!(time::PrimitiveDateTime, "datetime.datetime", "datetime");
170impl_with_module!(time::UtcDateTime, "datetime.datetime", "datetime");
171impl_with_module!(time::Time, "datetime.time", "datetime");
172impl_with_module!(time::UtcOffset, "datetime.tzinfo", "datetime");
173impl_with_module!(std::net::Ipv4Addr, "ipaddress.IPv4Address", "ipaddress");
174impl_with_module!(std::net::Ipv6Addr, "ipaddress.IPv6Address", "ipaddress");
175
176impl PyStubType for std::net::IpAddr {
177    fn type_output() -> TypeInfo {
178        TypeInfo::with_module(
179            "ipaddress.IPv4Address",
180            ModuleRef::Named("ipaddress".to_string()),
181        ) | TypeInfo::with_module(
182            "ipaddress.IPv6Address",
183            ModuleRef::Named("ipaddress".to_string()),
184        )
185    }
186}
187impl PyRuntimeType for std::net::IpAddr {
188    fn runtime_type_object(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
189        let module = py.import("ipaddress")?;
190        let type_v4 = module.getattr("IPv4Address")?;
191        let type_v6 = module.getattr("IPv6Address")?;
192        union_type(py, &[type_v4, type_v6])
193    }
194}
195
196#[cfg(feature = "uuid")]
197impl PyStubType for uuid::Uuid {
198    fn type_output() -> TypeInfo {
199        TypeInfo::with_module("uuid.UUID", "uuid".into())
200    }
201}
202
203impl<T: PyStubType> PyStubType for &T {
204    fn type_input() -> TypeInfo {
205        T::type_input()
206    }
207    fn type_output() -> TypeInfo {
208        T::type_output()
209    }
210}
211impl<T: PyRuntimeType> PyRuntimeType for &T {
212    fn runtime_type_object(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
213        T::runtime_type_object(py)
214    }
215}
216
217impl<T: PyStubType> PyStubType for Rc<T> {
218    fn type_input() -> TypeInfo {
219        T::type_input()
220    }
221    fn type_output() -> TypeInfo {
222        T::type_output()
223    }
224}
225impl<T: PyRuntimeType> PyRuntimeType for Rc<T> {
226    fn runtime_type_object(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
227        T::runtime_type_object(py)
228    }
229}
230
231impl<T: PyStubType> PyStubType for Arc<T> {
232    fn type_input() -> TypeInfo {
233        T::type_input()
234    }
235    fn type_output() -> TypeInfo {
236        T::type_output()
237    }
238}
239impl<T: PyRuntimeType> PyRuntimeType for Arc<T> {
240    fn runtime_type_object(py: Python<'_>) -> PyResult<Bound<'_, PyAny>> {
241        T::runtime_type_object(py)
242    }
243}