pyo3-introspection-0.28.3/.cargo_vcs_info.json0000644000000001601046102023000147350ustar { "git": { "sha1": "743af645e7143be6abe2217aafaa0540cf532af4" }, "path_in_vcs": "pyo3-introspection" }pyo3-introspection-0.28.3/Cargo.lock0000644000000277441046102023000127310ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "anyhow" version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" [[package]] name = "bitflags" version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" [[package]] name = "cfg-if" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "equivalent" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "errno" version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", "windows-sys", ] [[package]] name = "fastrand" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "foldhash" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" [[package]] name = "getrandom" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ "cfg-if", "libc", "r-efi", "wasip2", "wasip3", ] [[package]] name = "goblin" version = "0.10.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "983a6aafb3b12d4c41ea78d39e189af4298ce747353945ff5105b54a056e5cd9" dependencies = [ "log", "plain", "scroll", ] [[package]] name = "hashbrown" version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ "foldhash", ] [[package]] name = "hashbrown" version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" [[package]] name = "heck" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "id-arena" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" [[package]] name = "indexmap" version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" dependencies = [ "equivalent", "hashbrown 0.16.1", "serde", "serde_core", ] [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "leb128fmt" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" [[package]] name = "libc" version = "0.2.184" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48f5d2a454e16a5ea0f4ced81bd44e4cfc7bd3a507b61887c99fd3538b28e4af" [[package]] name = "linux-raw-sys" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "log" version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" [[package]] name = "memchr" version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "plain" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" [[package]] name = "prettyplease" version = "0.2.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" dependencies = [ "proc-macro2", "syn", ] [[package]] name = "proc-macro2" version = "1.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" dependencies = [ "unicode-ident", ] [[package]] name = "pyo3-introspection" version = "0.28.3" dependencies = [ "anyhow", "goblin", "serde", "serde_json", "tempfile", ] [[package]] name = "quote" version = "1.0.45" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" dependencies = [ "proc-macro2", ] [[package]] name = "r-efi" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rustix" version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys", ] [[package]] name = "scroll" version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1257cd4248b4132760d6524d6dda4e053bc648c9070b960929bf50cfb1e7add" dependencies = [ "scroll_derive", ] [[package]] name = "scroll_derive" version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed76efe62313ab6610570951494bdaa81568026e0318eaa55f167de70eeea67d" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "semver" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" [[package]] name = "serde" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ "serde_core", "serde_derive", ] [[package]] name = "serde_core" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.149" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" dependencies = [ "itoa", "memchr", "serde", "serde_core", "zmij", ] [[package]] name = "syn" version = "2.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "tempfile" version = "3.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", "getrandom", "once_cell", "rustix", "windows-sys", ] [[package]] name = "unicode-ident" version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "unicode-xid" version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" [[package]] name = "wasip2" version = "1.0.2+wasi-0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" dependencies = [ "wit-bindgen", ] [[package]] name = "wasip3" version = "0.4.0+wasi-0.3.0-rc-2026-01-06" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" dependencies = [ "wit-bindgen", ] [[package]] name = "wasm-encoder" version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" dependencies = [ "leb128fmt", "wasmparser", ] [[package]] name = "wasm-metadata" version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" dependencies = [ "anyhow", "indexmap", "wasm-encoder", "wasmparser", ] [[package]] name = "wasmparser" version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" dependencies = [ "bitflags", "hashbrown 0.15.5", "indexmap", "semver", ] [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" [[package]] name = "windows-sys" version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ "windows-link", ] [[package]] name = "wit-bindgen" version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" dependencies = [ "wit-bindgen-rust-macro", ] [[package]] name = "wit-bindgen-core" version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" dependencies = [ "anyhow", "heck", "wit-parser", ] [[package]] name = "wit-bindgen-rust" version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" dependencies = [ "anyhow", "heck", "indexmap", "prettyplease", "syn", "wasm-metadata", "wit-bindgen-core", "wit-component", ] [[package]] name = "wit-bindgen-rust-macro" version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" dependencies = [ "anyhow", "prettyplease", "proc-macro2", "quote", "syn", "wit-bindgen-core", "wit-bindgen-rust", ] [[package]] name = "wit-component" version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" dependencies = [ "anyhow", "bitflags", "indexmap", "log", "serde", "serde_derive", "serde_json", "wasm-encoder", "wasm-metadata", "wasmparser", "wit-parser", ] [[package]] name = "wit-parser" version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" dependencies = [ "anyhow", "id-arena", "indexmap", "log", "semver", "serde", "serde_derive", "serde_json", "unicode-xid", "wasmparser", ] [[package]] name = "zmij" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" pyo3-introspection-0.28.3/Cargo.toml0000644000000036721046102023000127460ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "pyo3-introspection" version = "0.28.3" authors = ["PyO3 Project and Contributors "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Introspect dynamic libraries built with PyO3 to get metadata about the exported Python types" homepage = "https://github.com/pyo3/pyo3" readme = false license = "MIT OR Apache-2.0" repository = "https://github.com/pyo3/pyo3" [lib] name = "pyo3_introspection" path = "src/lib.rs" [[test]] name = "test" path = "tests/test.rs" [dependencies.anyhow] version = "1" [dependencies.goblin] version = ">=0.9, <0.11" [dependencies.serde] version = "1" features = ["derive"] [dependencies.serde_json] version = "1" [dev-dependencies.tempfile] version = "3.12.0" [lints.clippy] checked_conversions = "warn" dbg_macro = "warn" explicit_into_iter_loop = "warn" explicit_iter_loop = "warn" filter_map_next = "warn" flat_map_option = "warn" let_unit_value = "warn" manual_assert = "warn" manual_ok_or = "warn" todo = "warn" undocumented_unsafe_blocks = "allow" unnecessary_wraps = "warn" used_underscore_binding = "warn" useless_transmute = "warn" [lints.rust] elided_lifetimes_in_paths = "warn" invalid_doc_attributes = "warn" rust_2021_prelude_collisions = "warn" unsafe_op_in_unsafe_fn = "warn" unused_lifetimes = "warn" [lints.rust.rust_2018_idioms] level = "warn" priority = -1 [lints.rustdoc] bare_urls = "warn" broken_intra_doc_links = "warn" pyo3-introspection-0.28.3/Cargo.toml.orig000064400000000000000000000010521046102023000163730ustar 00000000000000[package] name = "pyo3-introspection" version = "0.28.3" description = "Introspect dynamic libraries built with PyO3 to get metadata about the exported Python types" authors = ["PyO3 Project and Contributors "] homepage = "https://github.com/pyo3/pyo3" repository = "https://github.com/pyo3/pyo3" license = "MIT OR Apache-2.0" edition = "2021" [dependencies] anyhow = "1" goblin = ">=0.9, <0.11" serde = { version = "1", features = ["derive"] } serde_json = "1" [dev-dependencies] tempfile = "3.12.0" [lints] workspace = true pyo3-introspection-0.28.3/LICENSE-APACHE000064400000000000000000000231171046102023000154360ustar 00000000000000Copyright (c) 2017-present PyO3 Project and Contributors. https://github.com/PyO3 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS pyo3-introspection-0.28.3/LICENSE-MIT000064400000000000000000000021231046102023000151400ustar 00000000000000Copyright (c) 2023-present PyO3 Project and Contributors. https://github.com/PyO3 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pyo3-introspection-0.28.3/src/introspection.rs000064400000000000000000000574301046102023000175540ustar 00000000000000use crate::model::{ Argument, Arguments, Attribute, Class, Constant, Expr, Function, Module, Operator, VariableLengthArgument, }; use anyhow::{anyhow, bail, ensure, Context, Result}; use goblin::elf::section_header::SHN_XINDEX; use goblin::elf::Elf; use goblin::mach::load_command::CommandVariant; 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 std::borrow::Cow; use std::cmp::Ordering; use std::collections::HashMap; use std::path::Path; use std::{fs, str}; /// Introspect a cdylib built with PyO3 and returns the definition of a Python module. /// /// This function currently supports the ELF (most *nix including Linux), Match-O (macOS) and PE (Windows) formats. pub fn introspect_cdylib(library_path: impl AsRef, main_module_name: &str) -> Result { let chunks = find_introspection_chunks_in_binary_object(library_path.as_ref())?; parse_chunks(&chunks, main_module_name) } /// Parses the introspection chunks found in the binary fn parse_chunks(chunks: &[Chunk], main_module_name: &str) -> Result { let mut chunks_by_id = HashMap::<&str, &Chunk>::new(); let mut chunks_by_parent = HashMap::<&str, Vec<&Chunk>>::new(); for chunk in chunks { let (id, parent) = match chunk { Chunk::Module { id, .. } => (Some(id.as_str()), None), Chunk::Class { id, parent, .. } => (Some(id.as_str()), parent.as_deref()), Chunk::Function { id, parent, .. } | Chunk::Attribute { id, parent, .. } => { (id.as_deref(), parent.as_deref()) } }; if let Some(id) = id { chunks_by_id.insert(id, chunk); } if let Some(parent) = parent { chunks_by_parent.entry(parent).or_default().push(chunk); } } // We look for the root chunk for chunk in chunks { if let Chunk::Module { id, name, members, incomplete, } = chunk { if name == main_module_name { let type_hint_for_annotation_id = introspection_id_to_type_hint_for_root_module( chunk, &chunks_by_id, &chunks_by_parent, ); return convert_module( id, name, members, *incomplete, &chunks_by_id, &chunks_by_parent, &type_hint_for_annotation_id, ); } } } bail!("No module named {main_module_name} found") } fn convert_module( id: &str, name: &str, members: &[String], mut incomplete: bool, chunks_by_id: &HashMap<&str, &Chunk>, chunks_by_parent: &HashMap<&str, Vec<&Chunk>>, type_hint_for_annotation_id: &HashMap, ) -> Result { let mut member_chunks = chunks_by_parent .get(&id) .into_iter() .flatten() .copied() .collect::>(); for member in members { if let Some(c) = chunks_by_id.get(member.as_str()) { member_chunks.push(*c); } else { incomplete = true; // We don't find an element } } let (modules, classes, functions, attributes) = convert_members( member_chunks, chunks_by_id, chunks_by_parent, type_hint_for_annotation_id, )?; Ok(Module { name: name.into(), modules, classes, functions, attributes, incomplete, }) } type Members = (Vec, Vec, Vec, Vec); /// Convert a list of members of a module or a class fn convert_members<'a>( chunks: impl IntoIterator, chunks_by_id: &HashMap<&str, &Chunk>, chunks_by_parent: &HashMap<&str, Vec<&Chunk>>, type_hint_for_annotation_id: &HashMap, ) -> Result { let mut modules = Vec::new(); let mut classes = Vec::new(); let mut functions = Vec::new(); let mut attributes = Vec::new(); for chunk in chunks { match chunk { Chunk::Module { name, id, members, incomplete, } => { modules.push(convert_module( id, name, members, *incomplete, chunks_by_id, chunks_by_parent, type_hint_for_annotation_id, )?); } Chunk::Class { name, id, bases, decorators, parent: _, } => classes.push(convert_class( id, name, bases, decorators, chunks_by_id, chunks_by_parent, type_hint_for_annotation_id, )?), Chunk::Function { name, id: _, arguments, parent: _, decorators, is_async, returns, } => functions.push(convert_function( name, arguments, decorators, returns, *is_async, type_hint_for_annotation_id, )), Chunk::Attribute { name, id: _, parent: _, value, annotation, } => attributes.push(convert_attribute( name, value, annotation, type_hint_for_annotation_id, )), } } // We sort elements to get a stable output modules.sort_by(|l, r| l.name.cmp(&r.name)); classes.sort_by(|l, r| l.name.cmp(&r.name)); functions.sort_by(|l, r| match l.name.cmp(&r.name) { Ordering::Equal => { fn decorator_expr_key(expr: &Expr) -> (u32, Cow<'_, str>) { // We put plain names before attributes for @property to be before @foo.property match expr { Expr::Name { id, .. } => (0, Cow::Borrowed(id)), Expr::Attribute { value, attr } => { let (c, v) = decorator_expr_key(value); (c + 1, Cow::Owned(format!("{v}.{attr}"))) } _ => (0, Cow::Borrowed("")), // We don't care } } // We pick an ordering based on decorators l.decorators .iter() .map(decorator_expr_key) .cmp(r.decorators.iter().map(decorator_expr_key)) } o => o, }); attributes.sort_by(|l, r| l.name.cmp(&r.name)); Ok((modules, classes, functions, attributes)) } fn convert_class( id: &str, name: &str, bases: &[ChunkExpr], decorators: &[ChunkExpr], chunks_by_id: &HashMap<&str, &Chunk>, chunks_by_parent: &HashMap<&str, Vec<&Chunk>>, type_hint_for_annotation_id: &HashMap, ) -> Result { let (nested_modules, nested_classes, methods, attributes) = convert_members( chunks_by_parent.get(&id).into_iter().flatten().copied(), chunks_by_id, chunks_by_parent, type_hint_for_annotation_id, )?; ensure!( nested_modules.is_empty(), "Classes cannot contain nested modules" ); Ok(Class { name: name.into(), bases: bases .iter() .map(|e| convert_expr(e, type_hint_for_annotation_id)) .collect(), methods, attributes, decorators: decorators .iter() .map(|e| convert_expr(e, type_hint_for_annotation_id)) .collect(), inner_classes: nested_classes, }) } fn convert_function( name: &str, arguments: &ChunkArguments, decorators: &[ChunkExpr], returns: &Option, is_async: bool, type_hint_for_annotation_id: &HashMap, ) -> Function { Function { name: name.into(), decorators: decorators .iter() .map(|e| convert_expr(e, type_hint_for_annotation_id)) .collect(), arguments: Arguments { positional_only_arguments: arguments .posonlyargs .iter() .map(|a| convert_argument(a, type_hint_for_annotation_id)) .collect(), arguments: arguments .args .iter() .map(|a| convert_argument(a, type_hint_for_annotation_id)) .collect(), vararg: arguments .vararg .as_ref() .map(|a| convert_variable_length_argument(a, type_hint_for_annotation_id)), keyword_only_arguments: arguments .kwonlyargs .iter() .map(|e| convert_argument(e, type_hint_for_annotation_id)) .collect(), kwarg: arguments .kwarg .as_ref() .map(|a| convert_variable_length_argument(a, type_hint_for_annotation_id)), }, returns: returns .as_ref() .map(|a| convert_expr(a, type_hint_for_annotation_id)), is_async, } } fn convert_argument( arg: &ChunkArgument, type_hint_for_annotation_id: &HashMap, ) -> Argument { Argument { name: arg.name.clone(), default_value: arg .default .as_ref() .map(|e| convert_expr(e, type_hint_for_annotation_id)), annotation: arg .annotation .as_ref() .map(|a| convert_expr(a, type_hint_for_annotation_id)), } } fn convert_variable_length_argument( arg: &ChunkArgument, type_hint_for_annotation_id: &HashMap, ) -> VariableLengthArgument { VariableLengthArgument { name: arg.name.clone(), annotation: arg .annotation .as_ref() .map(|a| convert_expr(a, type_hint_for_annotation_id)), } } fn convert_attribute( name: &str, value: &Option, annotation: &Option, type_hint_for_annotation_id: &HashMap, ) -> Attribute { Attribute { name: name.into(), value: value .as_ref() .map(|v| convert_expr(v, type_hint_for_annotation_id)), annotation: annotation .as_ref() .map(|a| convert_expr(a, type_hint_for_annotation_id)), } } fn convert_expr(expr: &ChunkExpr, type_hint_for_annotation_id: &HashMap) -> Expr { match expr { ChunkExpr::Name { id } => Expr::Name { id: id.clone() }, ChunkExpr::Attribute { value, attr } => Expr::Attribute { value: Box::new(convert_expr(value, type_hint_for_annotation_id)), attr: attr.clone(), }, ChunkExpr::BinOp { left, op, right } => Expr::BinOp { left: Box::new(convert_expr(left, type_hint_for_annotation_id)), op: match op { ChunkOperator::BitOr => Operator::BitOr, }, right: Box::new(convert_expr(right, type_hint_for_annotation_id)), }, ChunkExpr::Subscript { value, slice } => Expr::Subscript { value: Box::new(convert_expr(value, type_hint_for_annotation_id)), slice: Box::new(convert_expr(slice, type_hint_for_annotation_id)), }, ChunkExpr::Tuple { elts } => Expr::Tuple { elts: elts .iter() .map(|e| convert_expr(e, type_hint_for_annotation_id)) .collect(), }, ChunkExpr::List { elts } => Expr::List { elts: elts .iter() .map(|e| convert_expr(e, type_hint_for_annotation_id)) .collect(), }, ChunkExpr::Constant { value } => Expr::Constant { value: match value { ChunkConstant::None => Constant::None, ChunkConstant::Bool { value } => Constant::Bool(*value), ChunkConstant::Int { value } => Constant::Int(value.clone()), ChunkConstant::Float { value } => Constant::Float(value.clone()), ChunkConstant::Str { value } => Constant::Str(value.clone()), ChunkConstant::Ellipsis => Constant::Ellipsis, }, }, ChunkExpr::Id { id } => { if let Some(expr) = type_hint_for_annotation_id.get(id) { expr.clone() } else { // This is a pyclass not exposed, we fallback to Any Expr::Attribute { value: Box::new(Expr::Name { id: "typing".into(), }), attr: "Any".to_string(), } } } } } /// Returns the type hint for each class introspection id defined in the module and its submodule fn introspection_id_to_type_hint_for_root_module( module_chunk: &Chunk, chunks_by_id: &HashMap<&str, &Chunk>, chunks_by_parent: &HashMap<&str, Vec<&Chunk>>, ) -> HashMap { fn add_introspection_id_to_type_hint_for_module_members( module_id: &str, module_full_name: &str, module_members: &[String], chunks_by_id: &HashMap<&str, &Chunk>, chunks_by_parent: &HashMap<&str, Vec<&Chunk>>, output: &mut HashMap, ) { for member in chunks_by_parent .get(&module_id) .into_iter() .flatten() .chain( module_members .iter() .filter_map(|id| chunks_by_id.get(id.as_str())), ) .copied() { match member { Chunk::Module { name, id, members, .. } => { add_introspection_id_to_type_hint_for_module_members( id, &format!("{}.{}", module_full_name, name), members, chunks_by_id, chunks_by_parent, output, ); } Chunk::Class { id, name, .. } => { output.insert( id.clone(), Expr::Attribute { value: Box::new(Expr::Name { id: module_full_name.into(), }), attr: name.clone(), }, ); add_introspection_id_to_type_hint_for_class_subclasses( id, name, module_full_name, chunks_by_parent, output, ); } _ => (), } } } fn add_introspection_id_to_type_hint_for_class_subclasses( class_id: &str, class_name: &str, class_module: &str, chunks_by_parent: &HashMap<&str, Vec<&Chunk>>, output: &mut HashMap, ) { for member in chunks_by_parent.get(&class_id).into_iter().flatten() { if let Chunk::Class { id, name, .. } = member { let class_name = format!("{}.{}", class_name, name); add_introspection_id_to_type_hint_for_class_subclasses( id, &class_name, class_module, chunks_by_parent, output, ); output.insert( id.clone(), Expr::Attribute { value: Box::new(Expr::Name { id: class_module.into(), }), attr: class_name, }, ); } } } let mut output = HashMap::new(); let Chunk::Module { id, name, members, .. } = module_chunk else { unreachable!("The chunk must be a module") }; add_introspection_id_to_type_hint_for_module_members( id, name, members, chunks_by_id, chunks_by_parent, &mut output, ); output } fn find_introspection_chunks_in_binary_object(path: &Path) -> Result> { let library_content = fs::read(path).with_context(|| format!("Failed to read {}", path.display()))?; match Object::parse(&library_content) .context("The built library is not valid or not supported by our binary parser")? { Object::Elf(elf) => find_introspection_chunks_in_elf(&elf, &library_content), Object::Mach(Mach::Binary(macho)) => { find_introspection_chunks_in_macho(&macho, &library_content) } Object::Mach(Mach::Fat(multi_arch)) => { for arch in &multi_arch { match arch? { SingleArch::MachO(macho) => { return find_introspection_chunks_in_macho(&macho, &library_content) } SingleArch::Archive(_) => (), } } bail!("No Mach-o chunk found in the multi-arch Mach-o container") } Object::PE(pe) => find_introspection_chunks_in_pe(&pe, &library_content), other => { bail!( "Only ELF, Mach-o and PE containers can be introspected, got {other:?} from file {path:?}", path = path.display() ) } } } fn find_introspection_chunks_in_elf(elf: &Elf<'_>, library_content: &[u8]) -> Result> { let mut chunks = Vec::new(); for sym in &elf.syms { if is_introspection_symbol(elf.strtab.get_at(sym.st_name).unwrap_or_default()) { ensure!(u32::try_from(sym.st_shndx)? != SHN_XINDEX, "Section names length is greater than SHN_LORESERVE in ELF, this is not supported by PyO3 yet"); let section_header = &elf.section_headers[sym.st_shndx]; let data_offset = sym.st_value + section_header.sh_offset - section_header.sh_addr; chunks.push(deserialize_chunk( &library_content[usize::try_from(data_offset).context("File offset overflow")?..], elf.little_endian, )?); } } Ok(chunks) } fn find_introspection_chunks_in_macho( macho: &MachO<'_>, library_content: &[u8], ) -> Result> { if !macho.little_endian { bail!("Only little endian Mach-o binaries are supported"); } ensure!( !macho.load_commands.iter().any(|command| { matches!(command.command, CommandVariant::DyldChainedFixups(_)) }), "Mach-O binaries with fixup chains are not supported yet, to avoid using fixup chains, use `--codegen=link-arg=-no_fixup_chains` option." ); let sections = macho .segments .sections() .flatten() .map(|t| t.map(|s| s.0)) .collect::, _>>()?; let mut chunks = Vec::new(); for symbol in macho.symbols() { let (name, nlist) = symbol?; if nlist.is_global() && nlist.get_type() == N_SECT && nlist.n_sect != NO_SECT as usize && is_introspection_symbol(name) { let section = §ions[nlist.n_sect - 1]; // Sections are counted from 1 let data_offset = nlist.n_value + u64::from(section.offset) - section.addr; chunks.push(deserialize_chunk( &library_content[usize::try_from(data_offset).context("File offset overflow")?..], macho.little_endian, )?); } } Ok(chunks) } fn find_introspection_chunks_in_pe(pe: &PE<'_>, library_content: &[u8]) -> Result> { let mut chunks = Vec::new(); for export in &pe.exports { if is_introspection_symbol(export.name.unwrap_or_default()) { chunks.push(deserialize_chunk( &library_content[export.offset.context("No symbol offset")?..], true, )?); } } Ok(chunks) } fn deserialize_chunk( content_with_chunk_at_the_beginning: &[u8], is_little_endian: bool, ) -> Result { let length = content_with_chunk_at_the_beginning .split_at(4) .0 .try_into() .context("The introspection chunk must contain a length")?; let length = if is_little_endian { u32::from_le_bytes(length) } else { u32::from_be_bytes(length) }; let chunk = content_with_chunk_at_the_beginning .get(4..4 + length as usize) .ok_or_else(|| { anyhow!("The introspection chunk length {length} is greater that the binary size") })?; serde_json::from_slice(chunk).with_context(|| { format!( "Failed to parse introspection chunk: {:?}", String::from_utf8_lossy(chunk) ) }) } fn is_introspection_symbol(name: &str) -> bool { name.strip_prefix('_') .unwrap_or(name) .starts_with("PYO3_INTROSPECTION_1_") } #[derive(Deserialize)] #[serde(tag = "type", rename_all = "lowercase")] enum Chunk { Module { id: String, name: String, members: Vec, incomplete: bool, }, Class { id: String, name: String, #[serde(default)] bases: Vec, #[serde(default)] decorators: Vec, #[serde(default)] parent: Option, }, Function { #[serde(default)] id: Option, name: String, arguments: Box, #[serde(default)] parent: Option, #[serde(default)] decorators: Vec, #[serde(default)] returns: Option, #[serde(default, rename = "async")] is_async: bool, }, Attribute { #[serde(default)] id: Option, #[serde(default)] parent: Option, name: String, #[serde(default)] value: Option, #[serde(default)] annotation: Option, }, } #[derive(Deserialize)] struct ChunkArguments { #[serde(default)] posonlyargs: Vec, #[serde(default)] args: Vec, #[serde(default)] vararg: Option, #[serde(default)] kwonlyargs: Vec, #[serde(default)] kwarg: Option, } #[derive(Deserialize)] struct ChunkArgument { name: String, #[serde(default)] default: Option, #[serde(default)] annotation: Option, } #[derive(Deserialize)] #[serde(tag = "type", rename_all = "lowercase")] enum ChunkExpr { /// A constant like `None` or `123` Constant { #[serde(flatten)] value: ChunkConstant, }, /// A name Name { id: String }, /// An attribute `value.attr` Attribute { value: Box, attr: String }, /// A binary operator BinOp { left: Box, op: ChunkOperator, right: Box, }, /// A tuple Tuple { elts: Vec }, /// A list List { elts: Vec }, /// A subscript `value[slice]` Subscript { value: Box, slice: Box }, /// An introspection id Id { id: String }, } #[derive(Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum ChunkConstant { None, Bool { value: bool }, Int { value: String }, Float { value: String }, Str { value: String }, Ellipsis, } #[derive(Deserialize)] #[serde(rename_all = "lowercase")] pub enum ChunkOperator { BitOr, } pyo3-introspection-0.28.3/src/lib.rs000064400000000000000000000004231046102023000154100ustar 00000000000000//! Utilities to introspect cdylib built using PyO3 and generate [type stubs](https://typing.readthedocs.io/en/latest/source/stubs.html). pub use crate::introspection::introspect_cdylib; pub use crate::stubs::module_stub_files; mod introspection; pub mod model; mod stubs; pyo3-introspection-0.28.3/src/model.rs000064400000000000000000000064011046102023000157440ustar 00000000000000#[derive(Debug, Eq, PartialEq, Clone, Hash)] pub struct Module { pub name: String, pub modules: Vec, pub classes: Vec, pub functions: Vec, pub attributes: Vec, pub incomplete: bool, } #[derive(Debug, Eq, PartialEq, Clone, Hash)] pub struct Class { pub name: String, pub bases: Vec, pub methods: Vec, pub attributes: Vec, /// decorator like 'typing.final' pub decorators: Vec, pub inner_classes: Vec, } #[derive(Debug, Eq, PartialEq, Clone, Hash)] pub struct Function { pub name: String, /// decorator like 'property' or 'staticmethod' pub decorators: Vec, pub arguments: Arguments, /// return type pub returns: Option, pub is_async: bool, } #[derive(Debug, Eq, PartialEq, Clone, Hash)] pub struct Attribute { pub name: String, /// Value as a Python expression if easily expressible pub value: Option, /// Type annotation as a Python expression pub annotation: Option, } #[derive(Debug, Eq, PartialEq, Clone, Hash)] pub struct Arguments { /// Arguments before / pub positional_only_arguments: Vec, /// Regular arguments (between / and *) pub arguments: Vec, /// *vararg pub vararg: Option, /// Arguments after * pub keyword_only_arguments: Vec, /// **kwarg pub kwarg: Option, } #[derive(Debug, Eq, PartialEq, Clone, Hash)] pub struct Argument { pub name: String, /// Default value as a Python expression pub default_value: Option, /// Type annotation as a Python expression pub annotation: Option, } /// 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, } /// A python expression /// /// This is the `expr` production of the [Python `ast` module grammar](https://docs.python.org/3/library/ast.html#abstract-grammar) #[derive(Debug, Eq, PartialEq, Clone, Hash)] pub enum Expr { /// A constant like `None` or `123` Constant { value: Constant }, /// A name Name { id: String }, /// An attribute `value.attr` Attribute { value: Box, attr: String }, /// A binary operator BinOp { left: Box, op: Operator, right: Box, }, /// A tuple Tuple { elts: Vec }, /// A list List { elts: Vec }, /// A subscript `value[slice]` Subscript { value: Box, slice: Box }, } /// A PyO3 extension to the Python AST to know more about [`Expr::Constant`]. /// /// This enables advanced features like escaping. #[derive(Debug, Eq, PartialEq, Clone, Hash)] pub enum Constant { /// `None` None, /// `True` or `False` Bool(bool), /// An integer in base 10 Int(String), /// A float in base 10 (does not include Inf and NaN) Float(String), /// A string (unescaped!) Str(String), /// `...` Ellipsis, } /// An operator used in [`Expr::BinOp`]. #[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)] pub enum Operator { /// `|` operator BitOr, } pyo3-introspection-0.28.3/src/stubs.rs000064400000000000000000000717141046102023000160150ustar 00000000000000use crate::model::{ Argument, Arguments, Attribute, Class, Constant, Expr, Function, Module, Operator, VariableLengthArgument, }; use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::fmt::Write; use std::iter::once; use std::path::PathBuf; use std::str::FromStr; /// Generates the [type stubs](https://typing.readthedocs.io/en/latest/source/stubs.html) of a given module. /// It returns a map between the file name and the file content. /// The root module stubs will be in the `__init__.pyi` file and the submodules directory /// in files with a relevant name. pub fn module_stub_files(module: &Module) -> HashMap { let mut output_files = HashMap::new(); add_module_stub_files(module, &[], &mut output_files); output_files } fn add_module_stub_files( module: &Module, module_path: &[&str], output_files: &mut HashMap, ) { let mut file_path = PathBuf::new(); for e in module_path { file_path = file_path.join(e); } output_files.insert( file_path.join("__init__.pyi"), module_stubs(module, module_path), ); let mut module_path = module_path.to_vec(); module_path.push(&module.name); for submodule in &module.modules { if submodule.modules.is_empty() { output_files.insert( file_path.join(format!("{}.pyi", submodule.name)), module_stubs(submodule, &module_path), ); } else { add_module_stub_files(submodule, &module_path, output_files); } } } /// Generates the module stubs to a String, not including submodules fn module_stubs(module: &Module, parents: &[&str]) -> String { let imports = Imports::create(module, parents); let mut elements = Vec::new(); for attribute in &module.attributes { elements.push(attribute_stubs(attribute, &imports)); } for class in &module.classes { elements.push(class_stubs(class, &imports)); } for function in &module.functions { elements.push(function_stubs(function, &imports, None)); } // We generate a __getattr__ method to tag incomplete stubs // See https://typing.python.org/en/latest/guides/writing_stubs.html#incomplete-stubs if module.incomplete && !module.functions.iter().any(|f| f.name == "__getattr__") { elements.push(function_stubs( &Function { name: "__getattr__".into(), decorators: Vec::new(), arguments: Arguments { positional_only_arguments: Vec::new(), arguments: vec![Argument { name: "name".to_string(), default_value: None, annotation: Some(Expr::Name { id: "str".into() }), }], vararg: None, keyword_only_arguments: Vec::new(), kwarg: None, }, returns: Some(Expr::Attribute { value: Box::new(Expr::Name { id: "_typeshed".into(), }), attr: "Incomplete".into(), }), is_async: false, }, &imports, None, )); } let mut final_elements = imports.imports; final_elements.extend(elements); let mut output = String::new(); // We insert two line jumps (i.e. empty strings) only above and below multiple line elements (classes with methods, functions with decorators) for element in final_elements { let is_multiline = element.contains('\n'); if is_multiline && !output.is_empty() && !output.ends_with("\n\n") { output.push('\n'); } output.push_str(&element); output.push('\n'); if is_multiline { output.push('\n'); } } // We remove a line jump at the end if they are two if output.ends_with("\n\n") { output.pop(); } output } fn class_stubs(class: &Class, imports: &Imports) -> String { let mut buffer = String::new(); for decorator in &class.decorators { buffer.push('@'); imports.serialize_expr(decorator, &mut buffer); buffer.push('\n'); } buffer.push_str("class "); buffer.push_str(&class.name); if !class.bases.is_empty() { buffer.push('('); for (i, base) in class.bases.iter().enumerate() { if i > 0 { buffer.push_str(", "); } imports.serialize_expr(base, &mut buffer); } buffer.push(')'); } buffer.push(':'); if class.methods.is_empty() && class.attributes.is_empty() && class.inner_classes.is_empty() { buffer.push_str(" ..."); return buffer; } for attribute in &class.attributes { // We do the indentation buffer.push_str("\n "); buffer.push_str(&attribute_stubs(attribute, imports).replace('\n', "\n ")); } for method in &class.methods { // We do the indentation buffer.push_str("\n "); buffer .push_str(&function_stubs(method, imports, Some(&class.name)).replace('\n', "\n ")); } for inner_class in &class.inner_classes { // We do the indentation buffer.push_str("\n "); buffer.push_str(&class_stubs(inner_class, imports).replace('\n', "\n ")); } buffer } fn function_stubs(function: &Function, imports: &Imports, class_name: Option<&str>) -> String { // Signature let mut parameters = Vec::new(); for argument in &function.arguments.positional_only_arguments { parameters.push(argument_stub(argument, imports)); } if !function.arguments.positional_only_arguments.is_empty() { parameters.push("/".into()); } for argument in &function.arguments.arguments { parameters.push(argument_stub(argument, imports)); } if let Some(argument) = &function.arguments.vararg { parameters.push(format!( "*{}", variable_length_argument_stub(argument, imports) )); } else if !function.arguments.keyword_only_arguments.is_empty() { parameters.push("*".into()); } for argument in &function.arguments.keyword_only_arguments { parameters.push(argument_stub(argument, imports)); } if let Some(argument) = &function.arguments.kwarg { parameters.push(format!( "**{}", variable_length_argument_stub(argument, imports) )); } let mut buffer = String::new(); for decorator in &function.decorators { buffer.push('@'); // We remove the class name if it's a prefix to get nicer decorators let mut decorator_buffer = String::new(); imports.serialize_expr(decorator, &mut decorator_buffer); if let Some(class_name) = class_name { if let Some(decorator) = decorator_buffer.strip_prefix(&format!("{class_name}.")) { decorator_buffer = decorator.into(); } } buffer.push_str(&decorator_buffer); buffer.push('\n'); } if function.is_async { buffer.push_str("async "); } buffer.push_str("def "); buffer.push_str(&function.name); buffer.push('('); buffer.push_str(¶meters.join(", ")); buffer.push(')'); if let Some(returns) = &function.returns { buffer.push_str(" -> "); imports.serialize_expr(returns, &mut buffer); } buffer.push_str(": ..."); buffer } fn attribute_stubs(attribute: &Attribute, imports: &Imports) -> String { let mut buffer = attribute.name.clone(); if let Some(annotation) = &attribute.annotation { buffer.push_str(": "); imports.serialize_expr(annotation, &mut buffer); } if let Some(value) = &attribute.value { buffer.push_str(" = "); imports.serialize_expr(value, &mut buffer); } buffer } fn argument_stub(argument: &Argument, imports: &Imports) -> String { let mut buffer = argument.name.clone(); if let Some(annotation) = &argument.annotation { buffer.push_str(": "); imports.serialize_expr(annotation, &mut buffer); } if let Some(default_value) = &argument.default_value { buffer.push_str(if argument.annotation.is_some() { " = " } else { "=" }); imports.serialize_expr(default_value, &mut buffer); } buffer } fn variable_length_argument_stub(argument: &VariableLengthArgument, imports: &Imports) -> String { let mut buffer = argument.name.clone(); if let Some(annotation) = &argument.annotation { buffer.push_str(": "); imports.serialize_expr(annotation, &mut buffer); } buffer } /// Datastructure to deduplicate, validate and generate imports #[derive(Default)] struct Imports { /// Import lines ready to use imports: Vec, /// Renaming map: from module name and member name return the name to use in type hints renaming: BTreeMap<(String, String), String>, } impl Imports { /// This generates a map from the builtin or module name to the actual alias used in the file /// /// For Python builtins and elements declared by the module the alias is always the actual name. /// /// For other elements, we can alias them using the `from X import Y as Z` syntax. /// So, we first list all builtins and local elements, then iterate on imports /// and create the aliases when needed. fn create(module: &Module, module_parents: &[&str]) -> Self { let mut elements_used_in_annotations = ElementsUsedInAnnotations::new(); elements_used_in_annotations.walk_module(module); let mut imports = Vec::new(); let mut renaming = BTreeMap::new(); let mut local_name_to_module_and_attribute = BTreeMap::new(); // We get the current module full name let current_module_name = module_parents .iter() .copied() .chain(once(module.name.as_str())) .collect::>() .join("."); // We first list local elements, they are never aliased or imported for name in module .classes .iter() .map(|c| c.name.clone()) .chain(module.functions.iter().map(|f| f.name.clone())) .chain(module.attributes.iter().map(|a| a.name.clone())) { local_name_to_module_and_attribute .insert(name.clone(), (current_module_name.clone(), name.clone())); } // We don't process the current module elements, no need to care about them local_name_to_module_and_attribute.remove(¤t_module_name); // We process then imports, normalizing local imports for (module, attrs) in &elements_used_in_annotations.module_to_name { let mut import_for_module = Vec::new(); for attr in attrs { // We split nested classes A.B in "A" (the part that must be imported and can have naming conflicts) and ".B" let (root_attr, attr_path) = attr .split_once('.') .map_or((attr.as_str(), None), |(root, path)| (root, Some(path))); let mut local_name = root_attr.to_owned(); let mut already_imported = false; while let Some((possible_conflict_module, possible_conflict_attr)) = local_name_to_module_and_attribute.get(&local_name) { if possible_conflict_module == module && *possible_conflict_attr == root_attr { // It's the same already_imported = true; break; } // We generate a new local name // TODO: we use currently a format like Foo2. It might be nicer to use something like ModFoo let number_of_digits_at_the_end = local_name .bytes() .rev() .take_while(|b| b.is_ascii_digit()) .count(); let (local_name_prefix, local_name_number) = local_name.split_at(local_name.len() - number_of_digits_at_the_end); local_name = format!( "{local_name_prefix}{}", u64::from_str(local_name_number).unwrap_or(1) + 1 ); } renaming.insert( (module.clone(), attr.clone()), if let Some(attr_path) = attr_path { format!("{local_name}.{attr_path}") } else { local_name.clone() }, ); if !already_imported { local_name_to_module_and_attribute .insert(local_name.clone(), (module.clone(), root_attr.to_owned())); let is_not_aliased_builtin = module == "builtins" && local_name == root_attr; if !is_not_aliased_builtin { import_for_module.push(if local_name == root_attr { local_name } else { format!("{root_attr} as {local_name}") }); } } } if !import_for_module.is_empty() { imports.push(format!( "from {module} import {}", import_for_module.join(", ") )); } } imports.sort(); // We make sure they are sorted Self { imports, renaming } } fn serialize_expr(&self, expr: &Expr, buffer: &mut String) { match expr { Expr::Constant { value } => match value { Constant::None => buffer.push_str("None"), Constant::Bool(value) => buffer.push_str(if *value { "True" } else { "False" }), Constant::Int(value) => buffer.push_str(value), Constant::Float(value) => { buffer.push_str(value); if !value.contains(['.', 'e', 'E']) { buffer.push('.'); // We make sure it's not parsed as an int } } Constant::Str(value) => { buffer.push('"'); for c in value.chars() { match c { '"' => buffer.push_str("\\\""), '\n' => buffer.push_str("\\n"), '\r' => buffer.push_str("\\r"), '\t' => buffer.push_str("\\t"), '\\' => buffer.push_str("\\\\"), '\0' => buffer.push_str("\\0"), c @ '\x00'..'\x20' => { write!(buffer, "\\x{:02x}", u32::from(c)).unwrap() } c => buffer.push(c), } } buffer.push('"'); } Constant::Ellipsis => buffer.push_str("..."), }, Expr::Name { id } => { buffer.push_str( self.renaming .get(&("builtins".into(), id.clone())) .expect("All type hint attributes should have been visited"), ); } Expr::Attribute { value, attr } => { if let Expr::Name { id, .. } = &**value { buffer.push_str( self.renaming .get(&(id.clone(), attr.clone())) .expect("All type hint attributes should have been visited"), ); } else { self.serialize_expr(value, buffer); buffer.push('.'); buffer.push_str(attr); } } Expr::BinOp { left, op, right } => { self.serialize_expr(left, buffer); buffer.push(' '); buffer.push(match op { Operator::BitOr => '|', }); self.serialize_expr(right, buffer); } Expr::Tuple { elts } => { buffer.push('('); self.serialize_elts(elts, buffer); if elts.len() == 1 { buffer.push(','); } buffer.push(')') } Expr::List { elts } => { buffer.push('['); self.serialize_elts(elts, buffer); buffer.push(']') } Expr::Subscript { value, slice } => { self.serialize_expr(value, buffer); buffer.push('['); if let Expr::Tuple { elts } = &**slice { // We don't display the tuple parentheses self.serialize_elts(elts, buffer); } else { self.serialize_expr(slice, buffer); } buffer.push(']'); } } } fn serialize_elts(&self, elts: &[Expr], buffer: &mut String) { for (i, elt) in elts.iter().enumerate() { if i > 0 { buffer.push_str(", "); } self.serialize_expr(elt, buffer); } } } /// Lists all the elements used in annotations struct ElementsUsedInAnnotations { /// module -> name where module is global (from the root of the interpreter). module_to_name: BTreeMap>, } impl ElementsUsedInAnnotations { fn new() -> Self { Self { module_to_name: BTreeMap::new(), } } fn walk_module(&mut self, module: &Module) { for attr in &module.attributes { self.walk_attribute(attr); } for class in &module.classes { self.walk_class(class); } for function in &module.functions { self.walk_function(function); } if module.incomplete { self.module_to_name .entry("builtins".into()) .or_default() .insert("str".into()); self.module_to_name .entry("_typeshed".into()) .or_default() .insert("Incomplete".into()); } } fn walk_class(&mut self, class: &Class) { for base in &class.bases { self.walk_expr(base); } for decorator in &class.decorators { self.walk_expr(decorator); } for method in &class.methods { self.walk_function(method); } for attr in &class.attributes { self.walk_attribute(attr); } for class in &class.inner_classes { self.walk_class(class); } } fn walk_attribute(&mut self, attribute: &Attribute) { if let Some(type_hint) = &attribute.annotation { self.walk_expr(type_hint); } } fn walk_function(&mut self, function: &Function) { for decorator in &function.decorators { self.walk_expr(decorator); } for arg in function .arguments .positional_only_arguments .iter() .chain(&function.arguments.arguments) .chain(&function.arguments.keyword_only_arguments) { if let Some(type_hint) = &arg.annotation { self.walk_expr(type_hint); } } for arg in function .arguments .vararg .as_ref() .iter() .chain(&function.arguments.kwarg.as_ref()) { if let Some(type_hint) = &arg.annotation { self.walk_expr(type_hint); } } if let Some(type_hint) = &function.returns { self.walk_expr(type_hint); } } fn walk_expr(&mut self, expr: &Expr) { match expr { Expr::Name { id } => { self.module_to_name .entry("builtins".into()) .or_default() .insert(id.clone()); } Expr::Attribute { value, attr } => { if let Expr::Name { id } = &**value { self.module_to_name .entry(id.into()) .or_default() .insert(attr.clone()); } else { self.walk_expr(value) } } Expr::BinOp { left, right, .. } => { self.walk_expr(left); self.walk_expr(right); } Expr::Subscript { value, slice } => { self.walk_expr(value); self.walk_expr(slice); } Expr::Tuple { elts } | Expr::List { elts } => { for elt in elts { self.walk_expr(elt) } } Expr::Constant { .. } => (), } } } #[cfg(test)] mod tests { use super::*; use crate::model::Arguments; #[test] fn function_stubs_with_variable_length() { let function = Function { name: "func".into(), decorators: Vec::new(), arguments: Arguments { positional_only_arguments: vec![Argument { name: "posonly".into(), default_value: None, annotation: None, }], arguments: vec![Argument { name: "arg".into(), default_value: None, annotation: None, }], vararg: Some(VariableLengthArgument { name: "varargs".into(), annotation: None, }), keyword_only_arguments: vec![Argument { name: "karg".into(), default_value: None, annotation: Some(Expr::Constant { value: Constant::Str("str".into()), }), }], kwarg: Some(VariableLengthArgument { name: "kwarg".into(), annotation: Some(Expr::Constant { value: Constant::Str("str".into()), }), }), }, returns: Some(Expr::Constant { value: Constant::Str("list[str]".into()), }), is_async: false, }; assert_eq!( "def func(posonly, /, arg, *varargs, karg: \"str\", **kwarg: \"str\") -> \"list[str]\": ...", function_stubs(&function, &Imports::default(), None) ) } #[test] fn function_stubs_without_variable_length() { let function = Function { name: "afunc".into(), decorators: Vec::new(), arguments: Arguments { positional_only_arguments: vec![Argument { name: "posonly".into(), default_value: Some(Expr::Constant { value: Constant::Int("1".into()), }), annotation: None, }], arguments: vec![Argument { name: "arg".into(), default_value: Some(Expr::Constant { value: Constant::Bool(true), }), annotation: None, }], vararg: None, keyword_only_arguments: vec![Argument { name: "karg".into(), default_value: Some(Expr::Constant { value: Constant::Str("foo".into()), }), annotation: Some(Expr::Constant { value: Constant::Str("str".into()), }), }], kwarg: None, }, returns: None, is_async: false, }; assert_eq!( "def afunc(posonly=1, /, arg=True, *, karg: \"str\" = \"foo\"): ...", function_stubs(&function, &Imports::default(), None) ) } #[test] fn test_function_async() { let function = Function { name: "foo".into(), decorators: Vec::new(), arguments: Arguments { positional_only_arguments: Vec::new(), arguments: Vec::new(), vararg: None, keyword_only_arguments: Vec::new(), kwarg: None, }, returns: None, is_async: true, }; assert_eq!( "async def foo(): ...", function_stubs(&function, &Imports::default(), None) ) } #[test] fn test_import() { let big_type = Expr::Subscript { value: Box::new(Expr::Name { id: "dict".into() }), slice: Box::new(Expr::Tuple { elts: vec![ Expr::Attribute { value: Box::new(Expr::Name { id: "foo.bar".into(), }), attr: "A".into(), }, Expr::Tuple { elts: vec![ Expr::Attribute { value: Box::new(Expr::Name { id: "foo".into() }), attr: "A.C".into(), }, Expr::Attribute { value: Box::new(Expr::Attribute { value: Box::new(Expr::Name { id: "foo".into() }), attr: "A".into(), }), attr: "D".into(), }, Expr::Attribute { value: Box::new(Expr::Name { id: "foo".into() }), attr: "B".into(), }, Expr::Attribute { value: Box::new(Expr::Name { id: "bat".into() }), attr: "A".into(), }, Expr::Attribute { value: Box::new(Expr::Name { id: "foo.bar".into(), }), attr: "int".into(), }, Expr::Name { id: "int".into() }, Expr::Name { id: "float".into() }, ], }, ], }), }; let imports = Imports::create( &Module { name: "bar".into(), modules: Vec::new(), classes: vec![ Class { name: "A".into(), bases: vec![Expr::Name { id: "dict".into() }], methods: Vec::new(), attributes: Vec::new(), decorators: vec![Expr::Attribute { value: Box::new(Expr::Name { id: "typing".into(), }), attr: "final".into(), }], inner_classes: Vec::new(), }, Class { name: "int".into(), bases: Vec::new(), methods: Vec::new(), attributes: Vec::new(), decorators: Vec::new(), inner_classes: Vec::new(), }, ], functions: vec![Function { name: String::new(), decorators: Vec::new(), arguments: Arguments { positional_only_arguments: Vec::new(), arguments: Vec::new(), vararg: None, keyword_only_arguments: Vec::new(), kwarg: None, }, returns: Some(big_type.clone()), is_async: false, }], attributes: Vec::new(), incomplete: true, }, &["foo"], ); assert_eq!( &imports.imports, &[ "from _typeshed import Incomplete", "from bat import A as A2", "from builtins import int as int2", "from foo import A as A3, B", "from typing import final" ] ); let mut output = String::new(); imports.serialize_expr(&big_type, &mut output); assert_eq!(output, "dict[A, (A3.C, A3.D, B, A2, int, int2, float)]"); } } pyo3-introspection-0.28.3/tests/test.rs000064400000000000000000000062161046102023000162020ustar 00000000000000use anyhow::{ensure, Result}; use pyo3_introspection::{introspect_cdylib, module_stub_files}; use std::collections::HashMap; use std::io::{Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use std::process::Command; use std::{env, fs}; use tempfile::NamedTempFile; #[test] fn pytests_stubs() -> Result<()> { // We run the introspection let binary = env::var_os("PYO3_PYTEST_LIB_PATH") .expect("The PYO3_PYTEST_LIB_PATH constant must be set and target the pyo3-pytests cdylib"); let module = introspect_cdylib(binary, "pyo3_pytests")?; let actual_stubs = module_stub_files(&module); // We read the expected stubs let expected_subs_dir = Path::new(env!("CARGO_MANIFEST_DIR")) .parent() .unwrap() .join("pytests") .join("stubs"); let mut expected_subs = HashMap::new(); add_dir_files( &expected_subs_dir, &expected_subs_dir.canonicalize()?, &mut expected_subs, )?; // We ensure we do not have extra generated files for file_name in actual_stubs.keys() { assert!( expected_subs.contains_key(file_name), "The generated file {} is not in the expected stubs directory pytests/stubs", file_name.display() ); } // We ensure the expected files are generated properly for (file_name, expected_file_content) in &expected_subs { let actual_file_content = actual_stubs.get(file_name).unwrap_or_else(|| { panic!( "The expected stub file {} has not been generated", file_name.display() ) }); let actual_file_content = format_with_ruff(actual_file_content)?; // We normalize line jumps for compatibility with Windows assert_eq!( expected_file_content.replace('\r', ""), actual_file_content.replace('\r', ""), "The content of file {} is different", file_name.display() ) } Ok(()) } fn add_dir_files( dir_path: &Path, base_dir_path: &Path, output: &mut HashMap, ) -> Result<()> { for entry in fs::read_dir(dir_path)? { let entry = entry?; if entry.file_type()?.is_dir() { add_dir_files(&entry.path(), base_dir_path, output)?; } else { output.insert( entry .path() .canonicalize()? .strip_prefix(base_dir_path)? .into(), fs::read_to_string(entry.path())?, ); } } Ok(()) } fn format_with_ruff(code: &str) -> Result { let temp_file = NamedTempFile::with_suffix(".pyi")?; // Write to file { let mut file = temp_file.as_file(); file.write_all(code.as_bytes())?; file.flush()?; file.seek(SeekFrom::Start(0))?; } ensure!( Command::new("ruff") .arg("format") .arg(temp_file.path()) .status()? .success(), "Failed to run ruff" ); let mut content = String::new(); temp_file.as_file().read_to_string(&mut content)?; Ok(content) }