use super::Pyo3Backend;
use crate::core::backend::Backend;
use crate::core::config::{NewAlefConfig, ResolvedCrateConfig};
use crate::core::ir::{ApiSurface, EnumDef, EnumVariant};
fn pyo3_config_with_feature(configured_feature: Option<&str>) -> ResolvedCrateConfig {
let features_line = configured_feature
.map(|f| format!("features = [\"{f}\"]\n"))
.unwrap_or_default();
let toml_src = format!(
"[workspace]\nlanguages = [\"python\"]\n[[crates]]\nname = \"test-lib\"\nsources = [\"src/lib.rs\"]\n\
[crates.python]\nmodule_name = \"test_lib\"\n{features_line}"
);
let cfg: NewAlefConfig = toml::from_str(&toml_src).unwrap();
cfg.resolve().unwrap().remove(0)
}
fn foreign_cfg_enum_api() -> ApiSurface {
ApiSurface {
crate_name: "test-lib".to_string(),
version: "0.1.0".to_string(),
enums: vec![EnumDef {
name: "RoutingStrategy".to_string(),
rust_path: "dep_crate::RoutingStrategy".to_string(),
variants: vec![
EnumVariant {
name: "Primary".to_string(),
..Default::default()
},
EnumVariant {
name: "Extra".to_string(),
cfg: Some(r#"feature = "extra-tier""#.to_string()),
..Default::default()
},
],
..Default::default()
}],
..Default::default()
}
}
fn lib_rs_content(files: &[crate::core::backend::GeneratedFile]) -> &str {
&files
.iter()
.find(|f| f.path.to_string_lossy().ends_with("lib.rs"))
.expect("generate_bindings must emit lib.rs")
.content
}
fn core_to_binding_conversion(lib_rs: &str) -> &str {
let start = lib_rs
.find("impl From<dep_crate::RoutingStrategy> for RoutingStrategy {")
.expect("generated crate must convert the foreign enum from core to the binding type");
let end = lib_rs[start..]
.find("\n}")
.map(|i| start + i + 2)
.expect("conversion impl must close");
&lib_rs[start..end]
}
#[test]
fn generate_bindings_omits_unreachable_catch_all_for_foreign_variant_proven_unreachable_end_to_end() {
let api = foreign_cfg_enum_api();
let config = pyo3_config_with_feature(None);
let files = Pyo3Backend.generate_bindings(&api, &config).unwrap();
let lib_rs = lib_rs_content(&files);
let conversion = core_to_binding_conversion(lib_rs);
assert!(
!conversion.contains("_ => Default::default(),"),
"a foreign cfg-gated variant proven unreachable by this binding's own configured feature \
set must not leave behind an unreachable catch-all (a cargo clippy -D warnings failure), \
got:\n{conversion}"
);
}
#[test]
fn generate_bindings_keeps_catch_all_for_foreign_variant_not_proven_unreachable_end_to_end() {
let api = foreign_cfg_enum_api();
let config = pyo3_config_with_feature(Some("extra-tier"));
let files = Pyo3Backend.generate_bindings(&api, &config).unwrap();
let lib_rs = lib_rs_content(&files);
let conversion = core_to_binding_conversion(lib_rs);
assert!(
conversion.contains("_ => Default::default(),"),
"a foreign cfg-gated variant that is NOT proven unreachable must keep the catch-all so the \
match stays exhaustive, got:\n{conversion}"
);
}