pyo3_stub_gen/lib.rs
1//! This crate creates stub files in following three steps using [inventory] crate:
2//!
3//! Define type information in Rust code (or by proc-macro)
4//! ---------------------------------------------------------
5//! The first step is to define Python type information in Rust code. [type_info] module provides several structs, for example:
6//!
7//! - [type_info::PyFunctionInfo] stores information of Python function, i.e. the name of the function, arguments and its types, return type, etc.
8//! - [type_info::PyClassInfo] stores information for Python class definition, i.e. the name of the class, members and its types, methods, etc.
9//!
10//! For better understanding of what happens in the background, let's define these information manually:
11//!
12//! ```
13//! use pyo3::*;
14//! use pyo3_stub_gen::type_info::*;
15//!
16//! // Usual PyO3 class definition
17//! #[pyclass(module = "my_module", name = "MyClass")]
18//! struct MyClass {
19//! #[pyo3(get)]
20//! name: String,
21//! #[pyo3(get)]
22//! description: Option<String>,
23//! }
24//!
25//! // Submit type information for stub file generation to inventory
26//! inventory::submit!{
27//! // Send information about Python class
28//! PyClassInfo {
29//! // Type ID of Rust struct (used to gathering phase discussed later)
30//! struct_id: std::any::TypeId::of::<MyClass>,
31//!
32//! // Python module name. Since stub file is generated per modules,
33//! // this helps where the class definition should be placed.
34//! module: Some("my_module"),
35//!
36//! // Python class name
37//! pyclass_name: "MyClass",
38//!
39//! getters: &[
40//! MemberInfo {
41//! name: "name",
42//! r#type: <String as ::pyo3_stub_gen::PyStubType>::type_output,
43//! doc: "Name docstring",
44//! default: None,
45//! deprecated: None,
46//! },
47//! MemberInfo {
48//! name: "description",
49//! r#type: <Option<String> as ::pyo3_stub_gen::PyStubType>::type_output,
50//! doc: "Description docstring",
51//! default: None,
52//! deprecated: None,
53//! },
54//! ],
55//!
56//! setters: &[],
57//!
58//! doc: "Docstring used in Python",
59//!
60//! // Base classes
61//! bases: &[],
62//!
63//! // Decorated with `#[pyclass(eq, ord)]`
64//! has_eq: false,
65//! has_ord: false,
66//! // Decorated with `#[pyclass(hash, str)]`
67//! has_hash: false,
68//! has_str: false,
69//! // Decorated with `#[pyclass(subclass)]`
70//! subclass: false,
71//! }
72//! }
73//! ```
74//!
75//! Roughly speaking, the above corresponds a following stub file `my_module.pyi`:
76//!
77//! ```python
78//! class MyClass:
79//! """
80//! Docstring used in Python
81//! """
82//! name: str
83//! """Name docstring"""
84//! description: Optional[str]
85//! """Description docstring"""
86//! ```
87//!
88//! We want to generate this [type_info::PyClassInfo] section automatically from `MyClass` Rust struct definition.
89//! This is done by using `#[gen_stub_pyclass]` proc-macro:
90//!
91//! ```
92//! use pyo3::*;
93//! use pyo3_stub_gen::{type_info::*, derive::gen_stub_pyclass};
94//!
95//! // Usual PyO3 class definition
96//! #[gen_stub_pyclass]
97//! #[pyclass(module = "my_module", name = "MyClass")]
98//! struct MyClass {
99//! #[pyo3(get)]
100//! name: String,
101//! #[pyo3(get)]
102//! description: Option<String>,
103//! }
104//! ```
105//!
106//! Since proc-macro is a converter from Rust code to Rust code, the output must be a Rust code.
107//! However, we need to gather these [type_info::PyClassInfo] definitions to generate stub files,
108//! and the above [inventory::submit] is for it.
109//!
110//! Gather type information into [StubInfo]
111//! ----------------------------------------
112//! [inventory] crate provides a mechanism to gather [inventory::submit]ted information when the library is loaded.
113//! To access these information through [inventory::iter], we need to define a gather function in the crate.
114//! Typically, this is done by following:
115//!
116//! ```rust
117//! use pyo3_stub_gen::{StubInfo, Result};
118//!
119//! pub fn stub_info() -> Result<StubInfo> {
120//! let manifest_dir: &::std::path::Path = env!("CARGO_MANIFEST_DIR").as_ref();
121//! StubInfo::from_pyproject_toml(manifest_dir.join("pyproject.toml"))
122//! }
123//! ```
124//!
125//! There is a helper macro to define it easily:
126//!
127//! ```rust
128//! pyo3_stub_gen::define_stub_info_gatherer!(sub_info);
129//! ```
130//!
131//! Generate stub file from [StubInfo]
132//! -----------------------------------
133//! [StubInfo] translates [type_info::PyClassInfo] and other information into a form helpful for generating stub files while gathering.
134//!
135//! [generate] module provides structs implementing [std::fmt::Display] to generate corresponding parts of stub file.
136//! For example, [generate::MethodDef] generates Python class method definition as follows:
137//!
138//! ```rust
139//! use pyo3_stub_gen::{TypeInfo, generate::*, type_info::ParameterKind};
140//!
141//! let method = MethodDef {
142//! name: "foo",
143//! parameters: Parameters {
144//! positional_or_keyword: vec![Parameter {
145//! name: "x",
146//! kind: ParameterKind::PositionalOrKeyword,
147//! type_info: TypeInfo::builtin("int"),
148//! default: ParameterDefault::None,
149//! }],
150//! ..Parameters::new()
151//! },
152//! r#return: TypeInfo::builtin("int"),
153//! doc: "This is a foo method.",
154//! r#type: MethodType::Instance,
155//! deprecated: None,
156//! is_async: false,
157//! type_ignored: None,
158//! is_overload: false,
159//! };
160//!
161//! assert_eq!(
162//! method.to_string().trim(),
163//! r#"
164//! def foo(self, x: builtins.int) -> builtins.int:
165//! r"""
166//! This is a foo method.
167//! """
168//! "#.trim()
169//! );
170//! ```
171//!
172//! [generate::ClassDef] generates Python class definition using [generate::MethodDef] and others, and other `*Def` structs works as well.
173//!
174//! [generate::Module] consists of `*Def` structs and yields an entire stub file `*.pyi` for a single Python (sub-)module, i.e. a shared library build by PyO3.
175//! [generate::Module]s are created as a part of [StubInfo], which merges [type_info::PyClassInfo]s and others submitted to [inventory] separately.
176//! [StubInfo] is instantiated with [pyproject::PyProject] to get where to generate the stub file,
177//! and [StubInfo::generate] generates the stub files for every modules.
178//!
179
180pub use inventory;
181pub use pyo3_stub_gen_derive as derive; // re-export to use in generated code
182
183pub mod exception;
184pub mod generate;
185pub mod pyproject;
186pub mod rule_name;
187mod stub_type;
188pub mod type_info;
189pub mod util;
190
191pub use generate::StubInfo;
192pub use pyproject::StubGenConfig;
193pub use stub_type::{ImportKind, ImportRef, ModuleRef, PyStubType, TypeIdentifierRef, TypeInfo};
194
195pub type Result<T> = anyhow::Result<T>;
196
197/// Create a function to initialize [StubInfo] from `pyproject.toml` in `CARGO_MANIFEST_DIR`.
198///
199/// If `pyproject.toml` is in another place, you need to create a function to call [StubInfo::from_pyproject_toml] manually.
200/// This must be placed in your PyO3 library crate, i.e. same crate where [inventory::submit]ted,
201/// not in `gen_stub` executables due to [inventory] mechanism.
202///
203#[macro_export]
204macro_rules! define_stub_info_gatherer {
205 ($function_name:ident) => {
206 /// Auto-generated function to gather information to generate stub files
207 pub fn $function_name() -> $crate::Result<$crate::StubInfo> {
208 let manifest_dir: &::std::path::Path = env!("CARGO_MANIFEST_DIR").as_ref();
209 $crate::StubInfo::from_pyproject_toml(manifest_dir.join("pyproject.toml"))
210 }
211 };
212}
213
214/// Add module-level documention using interpolation of runtime expressions.
215/// The first argument `module_doc!` receives is the full module name;
216/// the second and followings are a format string, same to `format!`.
217/// ```rust
218/// pyo3_stub_gen::module_doc!(
219/// "module.name",
220/// "Document for {} v{} ...",
221/// env!("CARGO_PKG_NAME"),
222/// env!("CARGO_PKG_VERSION")
223/// );
224/// ```
225#[macro_export]
226macro_rules! module_doc {
227 ($module:literal, $($fmt:tt)+) => {
228 $crate::inventory::submit! {
229 $crate::type_info::ModuleDocInfo {
230 module: $module,
231 doc: {
232 fn _fmt() -> String {
233 ::std::format!($($fmt)+)
234 }
235 _fmt
236 }
237 }
238 }
239 };
240}
241
242/// Add module-level variable, the first argument `module_variable!` receives is the full module name;
243/// the second argument is the name of the variable, the third argument is the type of the variable,
244/// and (optional) the fourth argument is the default value of the variable.
245/// ```rust
246/// pyo3_stub_gen::module_variable!("module.name", "CONSTANT1", usize);
247/// pyo3_stub_gen::module_variable!("module.name", "CONSTANT2", usize, 123);
248/// ```
249#[macro_export]
250macro_rules! module_variable {
251 ($module:expr, $name:expr, $ty:ty) => {
252 $crate::inventory::submit! {
253 $crate::type_info::PyVariableInfo{
254 name: $name,
255 module: $module,
256 r#type: <$ty as $crate::PyStubType>::type_output,
257 default: None,
258 }
259 }
260 };
261 ($module:expr, $name:expr, $ty:ty, $value:expr) => {
262 $crate::inventory::submit! {
263 $crate::type_info::PyVariableInfo{
264 name: $name,
265 module: $module,
266 r#type: <$ty as $crate::PyStubType>::type_output,
267 default: Some({
268 fn _fmt() -> String {
269 let v: $ty = $value;
270 $crate::util::fmt_py_obj(v)
271 }
272 _fmt
273 }),
274 }
275 }
276 };
277}
278
279/// Add module-level type alias using TypeInfo
280///
281/// This macro supports both single types and union types.
282///
283/// # Examples
284///
285/// Single type:
286/// ```rust
287/// pyo3_stub_gen::type_alias!("module.name", MyAlias = Option<usize>);
288/// ```
289///
290/// Union type (direct syntax):
291/// ```rust
292/// pyo3_stub_gen::type_alias!("module.name", MyUnion = i32 | String);
293/// ```
294/// ```rust,ignore
295/// pyo3_stub_gen::type_alias!("module.name", StructUnion = Bound<'static, TypeA> | Bound<'static, TypeB>);
296/// ```
297#[macro_export]
298macro_rules! type_alias {
299 // Pattern 1: Union types with docstring - must come first
300 ($module:expr, $name:ident = $($base:ty)|+, $doc:expr) => {
301 const _: () = {
302 struct __TypeAliasImpl;
303
304 impl $crate::PyStubType for __TypeAliasImpl {
305 fn type_output() -> $crate::TypeInfo {
306 $(<$base>::type_output()) | *
307 }
308 fn type_input() -> $crate::TypeInfo {
309 $(<$base>::type_input()) | *
310 }
311 }
312
313 $crate::inventory::submit! {
314 $crate::type_info::TypeAliasInfo {
315 name: stringify!($name),
316 module: $module,
317 r#type: <__TypeAliasImpl as $crate::PyStubType>::type_output,
318 doc: $doc,
319 }
320 }
321 };
322 };
323
324 // Pattern 2: Union types without docstring (backward compatible)
325 ($module:expr, $name:ident = $($base:ty)|+) => {
326 const _: () = {
327 struct __TypeAliasImpl;
328
329 impl $crate::PyStubType for __TypeAliasImpl {
330 fn type_output() -> $crate::TypeInfo {
331 $(<$base>::type_output()) | *
332 }
333 fn type_input() -> $crate::TypeInfo {
334 $(<$base>::type_input()) | *
335 }
336 }
337
338 $crate::inventory::submit! {
339 $crate::type_info::TypeAliasInfo {
340 name: stringify!($name),
341 module: $module,
342 r#type: <__TypeAliasImpl as $crate::PyStubType>::type_output,
343 doc: "",
344 }
345 }
346 };
347 };
348
349 // Pattern 3: Single types with docstring
350 ($module:expr, $name:ident = $ty:ty, $doc:expr) => {
351 $crate::inventory::submit! {
352 $crate::type_info::TypeAliasInfo {
353 name: stringify!($name),
354 module: $module,
355 r#type: <$ty as $crate::PyStubType>::type_output,
356 doc: $doc,
357 }
358 }
359 };
360
361 // Pattern 4: Single types without docstring (backward compatible)
362 ($module:expr, $name:ident = $ty:ty) => {
363 $crate::inventory::submit! {
364 $crate::type_info::TypeAliasInfo {
365 name: stringify!($name),
366 module: $module,
367 r#type: <$ty as $crate::PyStubType>::type_output,
368 doc: "",
369 }
370 }
371 };
372}
373
374/// Re-export items from another module into __all__
375///
376/// # Wildcard re-export
377/// ```rust
378/// pyo3_stub_gen::reexport_module_members!("target.module", "source.module");
379/// ```
380///
381/// # Specific items re-export
382/// ```rust
383/// pyo3_stub_gen::reexport_module_members!("target.module", "source.module", "item1", "item2");
384/// ```
385#[macro_export]
386macro_rules! reexport_module_members {
387 // Wildcard: reexport_module_members!("target", "source")
388 ($target:expr, $source:expr) => {
389 $crate::inventory::submit! {
390 $crate::type_info::ReexportModuleMembers {
391 target_module: $target,
392 source_module: $source,
393 items: None,
394 }
395 }
396 };
397 // Specific items: reexport_module_members!("target", "source", "item1", "item2")
398 ($target:expr, $source:expr, $($item:expr),+) => {
399 $crate::inventory::submit! {
400 $crate::type_info::ReexportModuleMembers {
401 target_module: $target,
402 source_module: $source,
403 items: Some(&[$($item),+]),
404 }
405 }
406 };
407}
408
409/// Add verbatim entry to __all__
410///
411/// # Example
412/// ```rust
413/// pyo3_stub_gen::export_verbatim!("my.module", "my_name");
414/// ```
415#[macro_export]
416macro_rules! export_verbatim {
417 ($module:expr, $name:expr) => {
418 $crate::inventory::submit! {
419 $crate::type_info::ExportVerbatim {
420 target_module: $module,
421 name: $name,
422 }
423 }
424 };
425}
426
427/// Exclude specific items from __all__
428///
429/// # Example
430/// ```rust
431/// pyo3_stub_gen::exclude_from_all!("my.module", "internal_function");
432/// ```
433#[macro_export]
434macro_rules! exclude_from_all {
435 ($module:expr, $name:expr) => {
436 $crate::inventory::submit! {
437 $crate::type_info::ExcludeFromAll {
438 target_module: $module,
439 name: $name,
440 }
441 }
442 };
443}
444
445#[doc = include_str!("../README.md")]
446mod readme {}