use std::cell::OnceCell; use std::ffi::CString; use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe}; use std::path::Path; use anysystem::python::PyProcessFactory; use anysystem::test::TestResult; use pyo3::prelude::*; use pyo3::types::{PyList, PyModule}; use crate::common::TestConfig; // AnySystem 0.3 prints the Python traceback and then unwraps the same error. // Suppress this duplicate diagnostic only at those bridge sites. pub fn install_panic_hook() { let default = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { let site = info .location() .map(|l| l.file().replace('\\', "/")) .unwrap_or_default(); let message = info.payload_as_str().unwrap_or(""); let python = site.ends_with("/anysystem-0.3.0/src/python/mod.rs") && (message.contains("PyErr {") || message.contains("Error when creating Python process")); let callback = (site.ends_with("/anysystem-0.3.0/src/node.rs") || site.ends_with("/anysystem-0.3.0/src/mc/node.rs")) && message.contains("Error when calling process"); if !python && !callback { default(info); } })); } pub struct Solution { factory: PyProcessFactory, errors: Py, } impl Solution { pub fn load(path: &str) -> Result { let path = Path::new(path).canonicalize().map_err(|e| e.to_string())?; let path = path.to_str().ok_or("Solution path is not UTF-8")?; // AnySystem unwraps Python errors during import. Preserve unrelated loader panics. let factory = catch_unwind(|| PyProcessFactory::new(path, "StorageNode")) .map_err(|panic| format!("Cannot load StorageNode: {}", python_panic(panic)))?; let errors = Python::attach(|py| -> PyResult<_> { // AnySystem 0.3 registers the solution under its canonical filename without ".py". let modules = PyModule::import(py, "sys")?.getattr("modules")?; let class = modules .get_item(path.replace(".py", ""))? .getattr("StorageNode")?; let code = CString::new(include_str!("../python_errors.py")).unwrap(); let adapter = PyModule::from_code(py, &code, c"python_errors.py", c"hw8_python_errors")?; Ok(adapter .getattr("watch")? .call1((class,))? .extract::>()?) }) .map_err(|error| error.to_string())?; Ok(Self { factory, errors }) } } fn python_panic(panic: Box) -> String { if let Some(message) = panic.downcast_ref::() { if let Some(start) = message.find("PyErr {") { return message[start..].to_string(); } } resume_unwind(panic) } pub type Case = fn(&TestConfig) -> TestResult; pub struct CaseConfig<'a> { pub solution: &'a Result, pub proc_count: u32, pub seed: u64, } pub fn run_case((config, test): &(&CaseConfig, Case)) -> TestResult { let solution = config.solution.as_ref().map_err(Clone::clone)?; let count_keys_error = OnceCell::new(); let config = TestConfig { count_keys_error: &count_keys_error, proc_factory: &solution.factory, proc_count: config.proc_count, seed: config.seed, }; // Each case owns its simulator. Unwinding drops all nodes from the failed case. match catch_unwind(AssertUnwindSafe(|| test(&config))) { Ok(result) => count_keys_error.into_inner().map_or(result, Err), Err(panic) => { let error = Python::attach(|py| { solution .errors .bind(py) .call_method0("pop") .and_then(|item| item.extract::()) .ok() }); match error { Some(error) => Err(format!("Python exception in {error}")), // PyO3 can also report Python errors outside a callback, for example in deepcopy. None => Err(format!("Python exception: {}", python_panic(panic))), } } } }