diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 4ee3c5155..616515fe5 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1030,6 +1030,10 @@ pub struct FeatureResult { pub id: u64, pub name: String, pub error: Option, + /// `error` is the kernel's internal error (a panic it caught, [`kernel::KernelError::Internal`]), + /// not the feature's failure: the command that made the feature reports it as one. + #[serde(skip)] + pub internal: bool, pub warning: Option, /// An Import feature's warnings by kind and part, with what came in of the file's parts /// (`warning` is the first of them as the kernel words them). @@ -2085,6 +2089,7 @@ impl Model { id: f.id, name: f.name.clone(), error: None, + internal: false, warning: None, import_report: None, repair: None, @@ -2118,6 +2123,7 @@ impl Model { id: f.id, name: f.name.clone(), error: Some(e), + internal: false, warning: None, import_report: None, repair: None, @@ -2156,6 +2162,7 @@ impl Model { id: f.id, name: f.name.clone(), error: c.error, + internal: false, warning: c.warning, import_report: c.import_report, repair: c.repair, @@ -2224,7 +2231,11 @@ impl Model { None => kernel::guard(&f.name, || { let (r, deferred) = kernel::validating(validation, || eval_feature(doc, &vals, f, &mut next, &mut warning, &mut import_report, &mut repair)); - r.map_err(|e| kernel::KernelError::Failed(e.in_feature(&f.name).to_string()))?; + r.map_err(|e| match e { + // A panic the kernel caught stays one. + crate::DocError::Kernel(kernel::KernelError::Internal(m)) => kernel::KernelError::Internal(m), + e => kernel::KernelError::Failed(e.in_feature(&f.name).to_string()), + })?; // The checks the feature's steps left to its end: the bodies it keeps. if deferred { check_kept(&state, &next) } else { Ok(()) } }), @@ -2244,6 +2255,7 @@ impl Model { note_join_apart(&state, &next, f, &mut warning); } let ms = t0.elapsed().as_secs_f64() * 1000.0; + let internal = matches!(r, Err(kernel::KernelError::Internal(_))); let error = match r { Ok(()) => { // Copies are named after their sources through the instance transforms. @@ -2287,7 +2299,8 @@ impl Model { } Err(e) => Some(e.to_string().trim_start_matches("the operation failed: ").to_string()), }; - if !self.no_cache && !watched.cancelled() { + // A panic is no result to reuse: the kernel was replaced after it. + if !self.no_cache && !watched.cancelled() && !internal { let e = CachedEval { error: error.clone(), warning: warning.clone(), @@ -2309,6 +2322,7 @@ impl Model { id: f.id, name: f.name.clone(), error, + internal, warning, import_report, repair, diff --git a/crates/doc/src/model_cache.rs b/crates/doc/src/model_cache.rs index c21126226..7a1e9b3c8 100644 --- a/crates/doc/src/model_cache.rs +++ b/crates/doc/src/model_cache.rs @@ -786,6 +786,7 @@ impl Model { id: f.id, name: f.name.clone(), error: None, + internal: false, warning: r.get("warning").map(|w| text(Some(w))).transpose()?, import_report: r .get("import_report") diff --git a/crates/engine/src/cmd/diagnostics.rs b/crates/engine/src/cmd/diagnostics.rs index 24e1574ac..e257fc46f 100644 --- a/crates/engine/src/cmd/diagnostics.rs +++ b/crates/engine/src/cmd/diagnostics.rs @@ -131,9 +131,7 @@ fn crash_test(_: &mut Session, p: &Value) -> Result { match str_(p, "mode") { Some("panic") => std::panic::panic_any(String::from("crash test: an internal error in a command")), Some("kernel") => { - solidcraft_kernel::guard("crash test", || -> solidcraft_kernel::Result<()> { - std::panic::panic_any(String::from("an internal error in the kernel")) - })?; + solidcraft_kernel::crash_test()?; Err(EngineError::Other("crash test: the kernel error was not caught".into())) } Some("abort") => std::process::abort(), diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 32b1766e3..270ac6642 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -826,8 +826,10 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> } } let r = s.model.result(id).cloned(); - if let Some(e) = r.as_ref().and_then(|r| r.error.clone()) { - return Err(EngineError::Other(e)); + if let Some(r) = &r + && let Some(e) = r.error.clone() + { + return Err(EngineError::of_feature(r, e)); } let st = s.model.state(); let bodies: Vec<&str> = st.bodies.iter().map(|b| b.name.as_str()).collect(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 72bf80b26..3141aac26 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -84,7 +84,10 @@ pub enum EngineError { impl From for EngineError { fn from(e: solidcraft_doc::DocError) -> Self { - EngineError::Other(e.to_string()) + match e { + solidcraft_doc::DocError::Kernel(e) => e.into(), + e => EngineError::Other(e.to_string()), + } } } impl From for EngineError { @@ -94,7 +97,19 @@ impl From for EngineError { } impl From for EngineError { fn from(e: solidcraft_kernel::KernelError) -> Self { - EngineError::Other(e.to_string()) + match e { + // A panic the kernel caught: internal, as one in the command would be. The command's id + // is filled in where the command is run (`Session::execute`). + solidcraft_kernel::KernelError::Internal(m) => EngineError::Internal(String::new(), m), + e => EngineError::Other(e.to_string()), + } + } +} + +impl EngineError { + /// The error a failed feature's result reports: internal when the kernel caught a panic. + pub(crate) fn of_feature(r: &solidcraft_doc::FeatureResult, error: String) -> EngineError { + if r.internal { EngineError::Internal(String::new(), error) } else { EngineError::Other(error) } } } impl From for EngineError { @@ -1648,6 +1663,11 @@ impl Session { Err(EngineError::Internal(spec.id.to_string(), msg)) } }; + // The kernel's internal errors come up without the command's id. + let r = r.map_err(|e| match e { + EngineError::Internal(id, msg) if id.is_empty() => EngineError::Internal(spec.id.to_string(), msg), + e => e, + }); // A value typed as `name = expression` defines the user parameter `name` (#4071), in the // same undo step; a refused definition fails the command, which leaves the design as it was. let r = match r { @@ -2174,8 +2194,10 @@ impl Session { { self.doc_mut().marker = Some(idx + 1); self.refresh(); - if let Some(e) = self.model.result(fid).and_then(|r| r.error.clone()) { - return Err(EngineError::Other(e)); + if let Some(r) = self.model.result(fid) + && let Some(e) = r.error.clone() + { + return Err(EngineError::of_feature(r, e)); } } } diff --git a/crates/kernel/src/blend_smlib.rs b/crates/kernel/src/blend_smlib.rs index 4e4088a88..d325f42e2 100644 --- a/crates/kernel/src/blend_smlib.rs +++ b/crates/kernel/src/blend_smlib.rs @@ -123,8 +123,8 @@ mod imp { use crate::native::{body_from_smlib_ordered, smlib_body_ordered}; use crate::{KernelError, Result, guard, record}; - fn failed(what: &str, step: &str, e: impl std::fmt::Display) -> KernelError { - KernelError::Failed(format!("SMLib {what}: {step}: {e}")) + fn failed(what: &str, step: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib {what}: {step}"), e) } /// How far a pick may lie from its edge. diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index fb15a4df0..c4b7315d2 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -420,6 +420,8 @@ pub struct Refusal { pub surface: Option, /// SMLib's reason for the whole body, as the log words it. pub why: String, + /// The reason is a panic the wrapper caught, not a refusal ([`KernelError::Internal`]). + pub internal: bool, } /// Where a point lies against a body ([`Body::classify_point`]). @@ -451,13 +453,16 @@ const MAX_REFUSAL_PROBES: usize = 20_000; impl Refusal { /// The refusal of `record` for `error`, with the face SMLib refuses on its own. fn of(record: &Brep, error: &solidcraft_smlib::Error) -> Refusal { + if let solidcraft_smlib::Error::Internal(why) = error { + return Refusal { face: None, surface: None, why: why.clone(), internal: true }; + } let _span = solidcraft_profile::span("kernel", "smlib_refusal_face"); let alone = |f: usize| crate::surfaces::Parts::of(record, &[(f, false)]).and_then(|p| p.canonical()).map(|c| c.brep); let face = (record.faces.len() <= MAX_REFUSAL_PROBES) .then(|| (0..record.faces.len()).find(|&f| alone(f).is_ok_and(|r| solidcraft_smlib::Brep::from_record(&r, true).is_err()))) .flatten(); let surface = face.and_then(|f| record.faces.get(f)).map(|f| SurfaceKind::of(&f.surface)); - Refusal { face, surface, why: error.to_string() } + Refusal { face, surface, why: error.to_string(), internal: false } } } @@ -540,7 +545,7 @@ impl Body { self.smlib .get_or_init(|| solidcraft_smlib::Brep::from_record(&self.record, true).map_err(|e| Refusal::of(&self.record, &e))) .as_ref() - .map_err(|r| KernelError::Failed(format!("SMLib: {}", r.why))) + .map_err(|r| if r.internal { KernelError::Internal(format!("SMLib: {}", r.why)) } else { KernelError::Failed(format!("SMLib: {}", r.why)) }) } /// Why SMLib refuses the body, if it does: the body is sent into SMLib as an operation @@ -1047,7 +1052,7 @@ impl Body { if self.is_mesh() { return Ok(self.outline_bounds()); } - let (lo, hi) = self.smlib()?.bounds().map_err(|e| KernelError::Failed(format!("SMLib bounds: {e}")))?; + let (lo, hi) = self.smlib()?.bounds().map_err(|e| KernelError::smlib("SMLib bounds", e))?; Ok(Aabb3 { min: v3(lo), max: v3(hi) }) } @@ -1380,7 +1385,7 @@ impl Body { PointClass::Outside }); } - let class = self.smlib()?.classify_point([p.x, p.y, p.z]).map_err(|e| KernelError::Failed(format!("SMLib point classification: {e}")))?; + let class = self.smlib()?.classify_point([p.x, p.y, p.z]).map_err(|e| KernelError::smlib("SMLib point classification", e))?; Ok(match class { solidcraft_smlib::PointClass::Inside => PointClass::Inside, solidcraft_smlib::PointClass::Outside => PointClass::Outside, diff --git a/crates/kernel/src/fair.rs b/crates/kernel/src/fair.rs index 5be51db6b..eabec47ec 100644 --- a/crates/kernel/src/fair.rs +++ b/crates/kernel/src/fair.rs @@ -919,7 +919,7 @@ pub fn fair_faces(body: &Body, faces: &[usize], opts: &FairOptions) -> Result<(B if changed.is_empty() { return Ok((body.clone(), report)); } - let smlib = solidcraft_smlib::Brep::from_record(&record, true).map_err(|e| KernelError::Failed(format!("fair: SMLib: {e}")))?; + let smlib = solidcraft_smlib::Brep::from_record(&record, true).map_err(|e| KernelError::smlib("fair: SMLib", e))?; let (result, order) = crate::native::body_from_smlib_ordered(&smlib)?; // The topology is the body's own, so SMLib's order is the body's: each face kept or // modified, each edge kept. Where SMLib's order is not the record's the history is not known. diff --git a/crates/kernel/src/fill.rs b/crates/kernel/src/fill.rs index f7c2e095f..3a8b5ea9a 100644 --- a/crates/kernel/src/fill.rs +++ b/crates/kernel/src/fill.rs @@ -795,7 +795,7 @@ fn patch_body(body: &Body, record: &b::Brep, chain: &[(usize, bool)], surface: b } let mut made = assemble(Parts { vertices, edges, faces: vec![PartFace { surface, forward: true, loops: vec![uses] }], tolerance: tol }, false)?; hold_gap(&mut made.brep, tol); - let smlib = solidcraft_smlib::Brep::from_record(&made.brep, true).map_err(|e| KernelError::Failed(format!("patch: SMLib: {e}")))?; + let smlib = solidcraft_smlib::Brep::from_record(&made.brep, true).map_err(|e| KernelError::smlib("patch: SMLib", e))?; let (patch, order) = crate::native::body_from_smlib_ordered(&smlib)?; // The patch's edges in its own order, each from the loop edge it is. let Some(order) = order else { return Ok(patch) }; @@ -920,7 +920,7 @@ fn quilt_body(body: &Body, record: &b::Brep, chain: &[Piece], fill: &IsoFill, to } let mut made = assemble(Parts { vertices, edges, faces, tolerance: tol }, false)?; hold_gap(&mut made.brep, tol); - let smlib = solidcraft_smlib::Brep::from_record(&made.brep, true).map_err(|e| KernelError::Failed(format!("patch: SMLib: {e}")))?; + let smlib = solidcraft_smlib::Brep::from_record(&made.brep, true).map_err(|e| KernelError::smlib("patch: SMLib", e))?; let (sheet, order) = crate::native::body_from_smlib_ordered(&smlib)?; let Some(order) = order else { return Ok(sheet) }; let place = |list: &[usize], c: usize| if list.is_empty() { Some(c) } else { list.get(c).copied() }; diff --git a/crates/kernel/src/intersection.rs b/crates/kernel/src/intersection.rs index 93aec0bdb..fe5af4a98 100644 --- a/crates/kernel/src/intersection.rs +++ b/crates/kernel/src/intersection.rs @@ -22,8 +22,8 @@ pub struct MeetingEdge { pub points: Vec, } -fn failed(what: &str, e: impl std::fmt::Display) -> KernelError { - KernelError::Failed(format!("SMLib intersection curve: {what}: {e}")) +fn failed(what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib intersection curve: {what}"), e) } /// `body` itself, or its faces `faces` (in its face order) alone as a surface body. diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index a4bd3519e..0bee1456e 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -256,6 +256,48 @@ pub enum KernelError { pub type Result = std::result::Result; +/// Why a kernel step failed: a message, or an error of the solidcore wrapper, which may be a +/// panic the wrapper caught ([`solidcraft_smlib::Error::Internal`]). +pub(crate) trait Cause: std::fmt::Display { + /// The panic's message, when the cause is one. + fn panic(&self) -> Option<&str> { + None + } +} + +impl Cause for solidcraft_smlib::Error { + fn panic(&self) -> Option<&str> { + match self { + solidcraft_smlib::Error::Internal(m) => Some(m), + _ => None, + } + } +} + +impl Cause for str {} +impl Cause for String {} +impl Cause for solidcraft_smlib::CheckReport {} +impl Cause for solidcraft_smlib::export::ExportError {} +impl Cause for solidcraft_geom::brep::history::Failed {} +impl Cause for solidcraft_geom::brep::pcurve::Error {} +impl Cause for &T { + fn panic(&self) -> Option<&str> { + (**self).panic() + } +} + +impl KernelError { + /// A kernel step's failure, `context` before its cause: a panic the solidcore wrapper caught + /// (its kernel replaced by a fresh one) stays an internal error ([`KernelError::Internal`]), + /// so the engine reports it as one; any other cause is the operation's failure. + pub(crate) fn smlib(context: impl std::fmt::Display, e: impl Cause) -> KernelError { + match e.panic() { + Some(m) => KernelError::Internal(format!("{context}: {m}")), + None => KernelError::Failed(format!("{context}: {e}")), + } + } +} + /// The native kernel call running right now (SMLib), for crash reports. pub fn native_call_in_flight() -> Option { solidcraft_smlib::current_call() @@ -268,7 +310,13 @@ thread_local! { /// Is this thread inside [`guard`]? (A panic now will be caught and turned into an error; the /// engine's crash reports mark it recovered.) pub fn guarded() -> bool { - GUARDED.with(std::cell::Cell::get) > 0 + GUARDED.with(std::cell::Cell::get) > 0 || solidcraft_smlib::in_call() +} + +/// A panic inside a solidcore call, caught there and reported as the kernel's internal error +/// ([`KernelError::Internal`]): the crash-report check (`diagnostics.crash_test`'s kernel mode). +pub fn crash_test() -> Result<()> { + solidcraft_smlib::crash_test().map_err(|e| KernelError::smlib("crash test", e)) } /// Run third-party kernel code, converting a panic into an error. diff --git a/crates/kernel/src/measure.rs b/crates/kernel/src/measure.rs index 0915b0337..cad99b239 100644 --- a/crates/kernel/src/measure.rs +++ b/crates/kernel/src/measure.rs @@ -102,7 +102,7 @@ pub fn measure_mass(b: &Body) -> Result { return Ok(MassMeasure { volume: m.volume, area: m.area, centroid: m.centroid, bbox: m.bbox, measured_by: m.measured_by, notes: m.notes }); } let m = crate::guard("SMLib mass properties", || { - b.smlib()?.mass_properties(ACCURACY).map_err(|e| crate::KernelError::Failed(format!("SMLib mass properties: {e}"))) + b.smlib()?.mass_properties(ACCURACY).map_err(|e| crate::KernelError::smlib("SMLib mass properties", e)) })?; let [x, y, z] = m.centroid; Ok(MassMeasure { volume: m.volume, area: m.area, centroid: Vec3::new(x, y, z), bbox: b.exact_bounds()?, measured_by: "smlib", notes: Vec::new() }) diff --git a/crates/kernel/src/native.rs b/crates/kernel/src/native.rs index d491d19eb..6856a5206 100644 --- a/crates/kernel/src/native.rs +++ b/crates/kernel/src/native.rs @@ -87,7 +87,7 @@ pub fn brep_record(body: &Body) -> Result { /// The body in SMLib (see [`Body::smlib`]), as an owned copy. pub fn smlib_body(body: &Body) -> Result { let _span = solidcraft_profile::span("kernel", "smlib_body"); - body.smlib()?.try_clone().map_err(|e| KernelError::Failed(format!("SMLib: {e}"))) + body.smlib()?.try_clone().map_err(|e| KernelError::smlib("SMLib", e)) } /// Decode bounded untrusted data. Validate indices before topology extraction. @@ -140,7 +140,7 @@ pub(crate) fn body_from_smlib_ordered(brep: &solidcraft_smlib::Brep) -> Result<( /// the body's record does. `None` where it does not. pub(crate) fn smlib_body_ordered(body: &Body) -> Result<(solidcraft_smlib::Brep, Option)> { let brep = smlib_body(body)?; - Ok((brep.try_clone().map_err(|e| KernelError::Failed(format!("SMLib: {e}")))?, numbering(body.record(), &brep))) + Ok((brep.try_clone().map_err(|e| KernelError::smlib("SMLib", e))?, numbering(body.record(), &brep))) } /// `record` in SMLib, imported as given (SMLib's own form; a record it refuses is an error that @@ -149,7 +149,7 @@ pub(crate) fn smlib_record_ordered( record: &solidcraft_geom::brep::Brep, ) -> Result<(solidcraft_smlib::Brep, Option)> { let _span = solidcraft_profile::span("kernel", "smlib_record_ordered"); - let brep = solidcraft_smlib::Brep::from_record(record, true).map_err(|e| KernelError::Failed(format!("SMLib: {e}")))?; + let brep = solidcraft_smlib::Brep::from_record(record, true).map_err(|e| KernelError::smlib("SMLib", e))?; let order = numbering(record, &brep); Ok((brep, order)) } diff --git a/crates/kernel/src/offset_backend.rs b/crates/kernel/src/offset_backend.rs index 4fb551cda..e21bd7dbd 100644 --- a/crates/kernel/src/offset_backend.rs +++ b/crates/kernel/src/offset_backend.rs @@ -22,8 +22,8 @@ use crate::history::{Change, EdgeOrigin, FaceOrigin, History}; use crate::native::{body_from_smlib_ordered, smlib_body_ordered}; use crate::{KernelError, Result, record}; -fn failed(op: &str, what: &str, e: impl std::fmt::Display) -> KernelError { - KernelError::Failed(format!("SMLib {op}: {what}: {e}")) +fn failed(op: &str, what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib {op}: {what}"), e) } /// The error for SMLib's refusal of `op`, in the words of the operation; `wall` is its wall's diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index ad550dd97..ff3c22f69 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -206,9 +206,9 @@ fn moved_from(history: Option<&History>, f: usize) -> Option { /// `body` moved by a matrix that is not a rigid motion, in SMLib, its history from SMLib's tags. fn transformed(body: &Body, m: &[[f64; 4]; 4]) -> Result { - let failed = |what: &str, e: &dyn std::fmt::Display| KernelError::Failed(format!("SMLib transform: {what}: {e}")); + let failed = |what: &str, e: solidcraft_smlib::Error| KernelError::smlib(format!("SMLib transform: {what}"), e); let (handle, order) = crate::native::smlib_body_ordered(body)?; - let moved = handle.tagged(0).map_err(|e| failed("tag", &e))?.transformed(m).map_err(|e| failed("operation", &e))?; + let moved = handle.tagged(0).map_err(|e| failed("tag", e))?.transformed(m).map_err(|e| failed("operation", e))?; let (result, result_order) = crate::native::body_from_smlib_ordered(&moved)?; let history = match (order, result_order) { (Some(o), Some(r)) => moved.history().ok().and_then(|h| h.history(&[o], &r).ok()), diff --git a/crates/kernel/src/planar_regularize.rs b/crates/kernel/src/planar_regularize.rs index 5f263c0c3..ea2b6e61f 100644 --- a/crates/kernel/src/planar_regularize.rs +++ b/crates/kernel/src/planar_regularize.rs @@ -21,8 +21,8 @@ fn edge_middle(e: &brep::Edge) -> Option { CurveEval::new(e.parameters()).ok()?.point(0.5 * (t0 + t1)) } -fn failed(e: impl std::fmt::Display) -> KernelError { - KernelError::Failed(format!("SMLib planar regularization: {e}")) +fn failed(e: impl crate::Cause) -> KernelError { + KernelError::smlib("SMLib planar regularization", e) } impl Body { diff --git a/crates/kernel/src/prism.rs b/crates/kernel/src/prism.rs index 6868a069c..e89b188b1 100644 --- a/crates/kernel/src/prism.rs +++ b/crates/kernel/src/prism.rs @@ -118,8 +118,8 @@ mod sheets { use super::*; use crate::prism_curve::{Run, projected}; - fn failed(what: &str, e: impl std::fmt::Display) -> KernelError { - KernelError::Failed(format!("SMLib planar regions: {what}: {e}")) + fn failed(what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib planar regions: {what}"), e) } /// `regions` (in the plane's own coordinates) as one sheet on z = 0. SMLib's face builder diff --git a/crates/kernel/src/sew.rs b/crates/kernel/src/sew.rs index 1be782c75..81d6ad68b 100644 --- a/crates/kernel/src/sew.rs +++ b/crates/kernel/src/sew.rs @@ -1221,7 +1221,7 @@ fn sew_impl(faces: &[FaceSpec], touching: bool, sources: Option<&[Option KernelError { - KernelError::Failed(format!("SMLib boolean: {what}: {e}")) + fn failed(what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib boolean: {what}"), e) } /// `a` and `b` combined by `op` in SMLib, with the history SMLib's tags give (none where a diff --git a/crates/kernel/src/smlib_sweeps.rs b/crates/kernel/src/smlib_sweeps.rs index 843c1a948..e326203bc 100644 --- a/crates/kernel/src/smlib_sweeps.rs +++ b/crates/kernel/src/smlib_sweeps.rs @@ -93,8 +93,8 @@ mod imp { use crate::provenance::{closest_on_tri, face_tris}; use crate::record; - fn failed(what: &str, e: impl std::fmt::Display) -> KernelError { - KernelError::Failed(format!("SMLib {what}: {e}")) + fn failed(what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib {what}"), e) } fn corner(c: crate::DraftCorner) -> DraftCorner { diff --git a/crates/kernel/src/splitface.rs b/crates/kernel/src/splitface.rs index ebf9765f9..1fc803192 100644 --- a/crates/kernel/src/splitface.rs +++ b/crates/kernel/src/splitface.rs @@ -49,8 +49,8 @@ fn invalid(what: impl Into) -> KernelError { KernelError::Invalid(what.into()) } -fn failed(what: &str, e: impl std::fmt::Display) -> KernelError { - KernelError::Failed(format!("SMLib {what}: {e}")) +fn failed(what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib {what}"), e) } fn a3(v: Vec3) -> [f64; 3] { diff --git a/crates/kernel/src/surface_extend.rs b/crates/kernel/src/surface_extend.rs index 8315b3b4c..8f8a04bf0 100644 --- a/crates/kernel/src/surface_extend.rs +++ b/crates/kernel/src/surface_extend.rs @@ -387,8 +387,8 @@ fn back_to_bounds(body: &Body, faces: &[usize]) -> Result { Ok(back) } -fn failed(what: &str, e: impl std::fmt::Display) -> KernelError { - KernelError::Failed(format!("SMLib extend: {what}: {e}")) +fn failed(what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib extend: {what}"), e) } #[cfg(test)] diff --git a/crates/kernel/src/surface_trim.rs b/crates/kernel/src/surface_trim.rs index ebb6ce5c0..8edd01858 100644 --- a/crates/kernel/src/surface_trim.rs +++ b/crates/kernel/src/surface_trim.rs @@ -102,7 +102,7 @@ pub fn trim_keep(body: &Body, tool: &SplitTool, keep: TrimKeep) -> Result fn face_sides(body: &Body, side: &ToolSide) -> Result> { let (sm, order) = crate::native::smlib_body_ordered(body)?; let order = order.ok_or_else(|| KernelError::Failed("trim: SMLib numbers the pieces' faces differently from their record".into()))?; - let points = sm.face_points().map_err(|e| KernelError::Failed(format!("SMLib trim: a point inside each piece: {e}")))?; + let points = sm.face_points().map_err(|e| KernelError::smlib("SMLib trim: a point inside each piece", e))?; let mut sides = vec![f64::NAN; points.len()]; for (i, p) in points.iter().enumerate() { let face = if order.faces.is_empty() { i } else { order.faces.get(i).copied().unwrap_or(usize::MAX) }; diff --git a/crates/kernel/src/surface_untrim.rs b/crates/kernel/src/surface_untrim.rs index fb8e5a793..ef0938147 100644 --- a/crates/kernel/src/surface_untrim.rs +++ b/crates/kernel/src/surface_untrim.rs @@ -102,8 +102,8 @@ pub fn untrim(body: &Body, face: usize, holes: UntrimHoles, outer: bool, in_plac Ok(out.with_checked_history(history, &crate::record::counts(&[body]))) } -fn failed(what: &str, e: impl std::fmt::Display) -> KernelError { - KernelError::Failed(format!("SMLib untrim: {what}: {e}")) +fn failed(what: &str, e: impl crate::Cause) -> KernelError { + KernelError::smlib(format!("SMLib untrim: {what}"), e) } /// A point inside face `face` of `body`: the centre of its largest mesh triangle. diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rs index 9cd0da5f6..6151ce9cc 100644 --- a/crates/kernel/src/surfaces.rs +++ b/crates/kernel/src/surfaces.rs @@ -1236,7 +1236,7 @@ mod imp { use super::*; fn sm(what: &'static str) -> impl Fn(solidcraft_smlib::Error) -> KernelError { - move |e| failed(format!("SMLib {what}: {e}")) + move |e| KernelError::smlib(format!("SMLib {what}"), e) } pub(super) fn refuse(what: &str) -> KernelError { diff --git a/crates/smlib/src/core.rs b/crates/smlib/src/core.rs index c672ac6fd..d31a7cde6 100644 --- a/crates/smlib/src/core.rs +++ b/crates/smlib/src/core.rs @@ -422,6 +422,17 @@ pub(crate) fn run(call: &'static str, f: impl FnOnce(&mut Kerne run_on(call, &[], f) } +thread_local! { + /// How many solidcore calls this thread is inside: a panic now is caught ([`run_on`]). + static IN_CALL: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Is this thread inside a solidcore call, whose panic [`run_on`] catches? (Crash reports mark such +/// a panic recovered.) +pub(crate) fn in_call() -> bool { + IN_CALL.with(std::cell::Cell::get) > 0 +} + /// [`run`] for a call that reads the bodies `inputs`: should it fail while a dump folder is set, /// they are left there ([`dump::failed`]). pub(crate) fn run_on( @@ -434,7 +445,17 @@ pub(crate) fn run_on( // A profiler span per call: where the kernel's time goes. let _span = solidcraft_profile::span("solidcore", call); dump::set_current(Some(call)); - let r = match catch_unwind(AssertUnwindSafe(|| f(k))) { + struct Depth; + impl Drop for Depth { + fn drop(&mut self) { + IN_CALL.with(|d| d.set(d.get().saturating_sub(1))); + } + } + IN_CALL.with(|d| d.set(d.get() + 1)); + let depth = Depth; + let caught = catch_unwind(AssertUnwindSafe(|| f(k))); + drop(depth); + let r = match caught { Ok(Ok(v)) => Ok(v), Ok(Err(e)) => Err(Error::Solidcore(format!("{call}: {e}"))), Err(p) => { diff --git a/crates/smlib/src/lib.rs b/crates/smlib/src/lib.rs index 4da013bc5..df250565d 100644 --- a/crates/smlib/src/lib.rs +++ b/crates/smlib/src/lib.rs @@ -231,6 +231,22 @@ pub fn current_call() -> Option { core::dump::current() } +/// Is this thread inside a solidcore call? A panic there is caught and becomes +/// [`Error::Internal`]; crash reports mark it recovered. +pub fn in_call() -> bool { + core::in_call() +} + +/// A panic inside a solidcore call, which the call catches as it catches any +/// ([`Error::Internal`], the kernel replaced by a fresh one): the crash-report check +/// (`diagnostics.crash_test`'s kernel mode). The crate's one deliberate panic. +#[allow(clippy::panic)] +pub fn crash_test() -> Result<()> { + core::run("crash test", |_| -> std::result::Result<(), solidcore::SolidError> { + std::panic::panic_any(String::from("crash test: an internal error in the kernel")) + }) +} + /// A B-rep. Immutable: operations return new bodies. pub struct Brep { body: core::Body, diff --git a/crates/smlib/src/tests.rs b/crates/smlib/src/tests.rs index 28f2c5513..54e272d8c 100644 --- a/crates/smlib/src/tests.rs +++ b/crates/smlib/src/tests.rs @@ -79,7 +79,7 @@ fn calls_from_many_threads_are_serialised() { static DUMP_DIR_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// Entry points that ask no kernel, so have nothing to say here. -const NO_KERNEL: [&str; 12] = [ +const NO_KERNEL: [&str; 13] = [ "inertia_tensor", "is_valid", "failed_tests", @@ -92,11 +92,13 @@ const NO_KERNEL: [&str; 12] = [ "blends", "word", "words", + "in_call", ]; -const ANSWERING: [&str; 62] = [ +const ANSWERING: [&str; 63] = [ "set_dump_dir", "current_call", + "crash_test", "make_box", "read", "write",