Avoid generating functions that are only ever const evaluated with declarative modules (#4297)

Refs #4286
This commit is contained in:
Alex Gaynor 2024-07-01 17:54:50 -04:00 committed by GitHub
parent 872bd7e6f7
commit f3603a0a48
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 16 additions and 19 deletions

View File

@ -0,0 +1 @@
stop generating code that will never be covered with declarative modules

View File

@ -286,17 +286,7 @@ pub fn pymodule_module_impl(mut module: syn::ItemMod) -> Result<TokenStream> {
}
}
let initialization = module_initialization(&name, ctx);
Ok(quote!(
#(#attrs)*
#vis mod #ident {
#(#items)*
#initialization
#[allow(unknown_lints, non_local_definitions)]
impl MakeDef {
const fn make_def() -> #pyo3_path::impl_::pymodule::ModuleDef {
let module_def = quote! {{
use #pyo3_path::impl_::pymodule as impl_;
const INITIALIZER: impl_::ModuleInitializer = impl_::ModuleInitializer(__pyo3_pymodule);
unsafe {
@ -306,8 +296,14 @@ pub fn pymodule_module_impl(mut module: syn::ItemMod) -> Result<TokenStream> {
INITIALIZER
)
}
}
}
}};
let initialization = module_initialization(&name, ctx, module_def);
Ok(quote!(
#(#attrs)*
#vis mod #ident {
#(#items)*
#initialization
fn __pyo3_pymodule(module: &#pyo3_path::Bound<'_, #pyo3_path::types::PyModule>) -> #pyo3_path::PyResult<()> {
use #pyo3_path::impl_::pymodule::PyAddToModule;
@ -335,7 +331,7 @@ pub fn pymodule_function_impl(mut function: syn::ItemFn) -> Result<TokenStream>
let vis = &function.vis;
let doc = get_doc(&function.attrs, None, ctx);
let initialization = module_initialization(&name, ctx);
let initialization = module_initialization(&name, ctx, quote! { MakeDef::make_def() });
// Module function called with optional Python<'_> marker as first arg, followed by the module.
let mut module_args = Vec::new();
@ -400,7 +396,7 @@ pub fn pymodule_function_impl(mut function: syn::ItemFn) -> Result<TokenStream>
})
}
fn module_initialization(name: &syn::Ident, ctx: &Ctx) -> TokenStream {
fn module_initialization(name: &syn::Ident, ctx: &Ctx, module_def: TokenStream) -> TokenStream {
let Ctx { pyo3_path, .. } = ctx;
let pyinit_symbol = format!("PyInit_{}", name);
let name = name.to_string();
@ -412,7 +408,7 @@ fn module_initialization(name: &syn::Ident, ctx: &Ctx) -> TokenStream {
pub(super) struct MakeDef;
#[doc(hidden)]
pub static _PYO3_DEF: #pyo3_path::impl_::pymodule::ModuleDef = MakeDef::make_def();
pub static _PYO3_DEF: #pyo3_path::impl_::pymodule::ModuleDef = #module_def;
/// This autogenerated function is called by the python interpreter when importing
/// the module.