diff --git a/crates/smlib/src/core/blend.rs b/crates/smlib/src/core/blend.rs index 75b816a2e78..476d4315edc 100644 --- a/crates/smlib/src/core/blend.rs +++ b/crates/smlib/src/core/blend.rs @@ -86,6 +86,7 @@ pub(super) fn status(e: SolidError) -> Error { e if is_topology_failure(&e) => Error::Status(e.sm_status().unwrap_or(solidcore::error::SM_ERR)), e if is_curve_failure(&e) => Error::Status(e.sm_status().unwrap_or(solidcore::error::SM_ERR)), e if is_surface_failure(&e) => Error::Status(e.sm_status().unwrap_or(solidcore::error::SM_ERR)), + e if is_offset_failure(&e) => Error::Status(e.sm_status().unwrap_or(solidcore::error::SM_ERR)), SolidError::InvalidInput { .. } => Error::Status(INVALID_INPUT), SolidError::Unsupported { reason, .. } if reason == MIXED_CORNER_RAILS_CROSS => Error::Unported(MIXED_CORNER_UNSUPPORTED), e if is_boolean_failure(&e) => boolean_status(e), @@ -172,6 +173,13 @@ fn is_surface_failure(e: &SolidError) -> bool { e.surface_failure().is_some() } +/// An offset routine's failure (solidcore's `OffsetFailure`) that replaced a status the routine +/// returned (`Upstream` before solidcore described it): it passes on as that status. An offset's +/// refusals replaced none and pass on as before. +fn is_offset_failure(e: &SolidError) -> bool { + e.offset_failure().is_some_and(|o| o.replaces_upstream_status()) +} + /// `size_ok`. fn size_ok(x: f64) -> bool { x.is_finite() && x > 0.0 && x <= 1e6 @@ -1606,4 +1614,24 @@ mod tests { assert!(matches!(status(surface(SurfaceFailure::OutsideDomain("the point is outside the sweep"))), Error::Status(1020))); assert!(matches!(status(surface(SurfaceFailure::OffSurface("the point is off the surface"))), Error::Status(1021))); } + + /// An offset routine's failure passes on as the status it replaced, as the `Upstream` it + /// replaced did, whether or not it names a face; an offset's refusal does not pass on as a + /// status. + #[test] + fn offset_failures_pass_on_as_their_status() { + use solidcore::error::Failure; + use solidcore::error::offset::OffsetFailure; + let offset = |o| Failure::new("offset::offset_executive::crossing_loops", o).into_error(); + assert!(matches!(status(offset(OffsetFailure::Failed("x"))), Error::Status(1001))); + assert!(matches!(status(offset(OffsetFailure::Missing("the face's surface"))), Error::Status(1006))); + assert!(matches!(status(offset(OffsetFailure::InvalidValue("x"))), Error::Status(1007))); + assert!(matches!(status(offset(OffsetFailure::Inconsistent("x"))), Error::Status(1005))); + let at = Failure::new("offset::draft", OffsetFailure::InvalidValue("the face has no surface or no outer face use")) + .at(solidcore::EntityRef::Face(solidcore::topology::FaceId::from_index(2))) + .into_error(); + assert!(matches!(status(at), Error::Status(1007))); + let folds = offset(OffsetFailure::Folds { face: solidcore::topology::FaceId::from_index(1), distance: 2.0, largest: 1.0 }); + assert!(!matches!(status(folds), Error::Status(_))); + } } diff --git a/solidcore/crates/goldens/src/units/blend_fillet_standard_solver_p2.rs b/solidcore/crates/goldens/src/units/blend_fillet_standard_solver_p2.rs index 0207958b365..246fcf077d0 100644 --- a/solidcore/crates/goldens/src/units/blend_fillet_standard_solver_p2.rs +++ b/solidcore/crates/goldens/src/units/blend_fillet_standard_solver_p2.rs @@ -591,7 +591,9 @@ fn rust_cr_eu_body( Ok(fs) => fs, Err(e) if e.is_unported() => return Err(e), // the tangent-surface exits (SM_ERR only signalled upstream) - Err(SolidError::Upstream { code, .. }) => return Ok(vec![f64::from(code)]), + Err(e) if solidcore::error::upstream_status(&e).is_some() => { + return Ok(vec![f64::from(solidcore::error::upstream_status(&e).unwrap_or(-1))]); + } Err(e) => return Err(e), }; fs.solver.surface_extension_factor = ext; @@ -817,8 +819,7 @@ fn surface_of(s: &SrfIn) -> Result { fn status(e: &SolidError) -> f64 { match e { SolidError::InvalidInput { .. } | SolidError::PortInvariant { .. } => 1007.0, - SolidError::Upstream { code, .. } => f64::from(*code), - _ => -1.0, + e => solidcore::error::upstream_status(e).map_or(-1.0, f64::from), } } diff --git a/solidcore/crates/goldens/src/units/intersect_surface_intersector_p4.rs b/solidcore/crates/goldens/src/units/intersect_surface_intersector_p4.rs index 5a9ca3e8acf..158ed980436 100644 --- a/solidcore/crates/goldens/src/units/intersect_surface_intersector_p4.rs +++ b/solidcore/crates/goldens/src/units/intersect_surface_intersector_p4.rs @@ -241,8 +241,7 @@ impl From for Fail { fn status(e: &SolidError) -> f64 { match e { SolidError::InvalidInput { .. } | SolidError::PortInvariant { .. } => 1007.0, - SolidError::Upstream { code, .. } => f64::from(*code), - _ => -1.0, + e => solidcore::error::upstream_status(e).map_or(-1.0, f64::from), } } diff --git a/solidcore/crates/goldens/src/units/intersect_topology_solver_p2.rs b/solidcore/crates/goldens/src/units/intersect_topology_solver_p2.rs index 156b62c25fa..5bfc751fe1d 100644 --- a/solidcore/crates/goldens/src/units/intersect_topology_solver_p2.rs +++ b/solidcore/crates/goldens/src/units/intersect_topology_solver_p2.rs @@ -823,7 +823,9 @@ fn static_rust(case: &Case) -> Result { } let status = match e { SolidError::InvalidInput { .. } | SolidError::PortInvariant { .. } => 1007.0, - SolidError::Upstream { code, .. } => f64::from(code), + ref e if solidcore::error::upstream_status(e).is_some() => { + f64::from(solidcore::error::upstream_status(e).unwrap_or(-1)) + } // a typed refusal (no upstream status): recorded, not a harness failure SolidError::Unsupported { .. } => return Ok(Output::err(e.to_string())), _ => return Err(HarnessError::new(e.to_string())), diff --git a/solidcore/crates/solidcore/src/error.rs b/solidcore/crates/solidcore/src/error.rs index 21071c9eb3d..7cd488366a0 100644 --- a/solidcore/crates/solidcore/src/error.rs +++ b/solidcore/crates/solidcore/src/error.rs @@ -641,8 +641,12 @@ impl core::fmt::Display for Failure { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{}: {}", self.operation, self.reason)?; // a reason that names no entity of its own is followed by the failure's - if let (Reason::Failed(_) | Reason::Topology(_), Some(entity)) = (&self.reason, self.entity) - { + let names_none = match &self.reason { + Reason::Failed(_) | Reason::Topology(_) => true, + Reason::Offset(o) => o.replaces_upstream_status(), + _ => false, + }; + if let (true, Some(entity)) = (names_none, self.entity) { write!(f, " ({entity})")?; } if let Some(cause) = &self.cause { @@ -1095,9 +1099,11 @@ impl SolidError { /// an `Upstream` site ([`nurbs::BSplineFailure`], [`intersect::IntersectFailure`], /// [`primitive::PrimitiveFailure`], [`mass::MassFailure`], [`heal::HealFailure`], /// [`geom::GeomFailure`], [`query::QueryFailure`], [`topology::TopologyFailure`], - /// [`surface::SurfaceFailure`], a [`sweep::SweepFailure`] or [`curve::CurveFailure`] that - /// replaced one ([`sweep::SweepFailure::replaces_upstream_status`], - /// [`curve::CurveFailure::replaces_upstream_status`])). The callers that branch on an + /// [`surface::SurfaceFailure`], a [`sweep::SweepFailure`], [`curve::CurveFailure`] or + /// [`offset::OffsetFailure`] that replaced one + /// ([`sweep::SweepFailure::replaces_upstream_status`], + /// [`curve::CurveFailure::replaces_upstream_status`], + /// [`offset::OffsetFailure::replaces_upstream_status`])). The callers that branch on an /// upstream status use it so that they treat both alike; it goes with `Upstream` in /// the last PR of the typed-errors work. #[must_use] @@ -1116,6 +1122,7 @@ impl SolidError { | Reason::Surface(_) => Some(f.status), Reason::Sweep(w) if w.replaces_upstream_status() => Some(f.status), Reason::Curve(c) if c.replaces_upstream_status() => Some(f.status), + Reason::Offset(o) if o.replaces_upstream_status() => Some(f.status), _ => None, }, _ => None, @@ -1337,9 +1344,11 @@ impl SolidError { /// ([`nurbs::BSplineFailure`], [`intersect::IntersectFailure`], /// [`primitive::PrimitiveFailure`], [`mass::MassFailure`], [`heal::HealFailure`], /// [`geom::GeomFailure`], [`query::QueryFailure`], [`topology::TopologyFailure`], -/// [`surface::SurfaceFailure`], a [`sweep::SweepFailure`] or [`curve::CurveFailure`] that -/// replaced one ([`sweep::SweepFailure::replaces_upstream_status`], -/// [`curve::CurveFailure::replaces_upstream_status`])). +/// [`surface::SurfaceFailure`], a [`sweep::SweepFailure`], [`curve::CurveFailure`] or +/// [`offset::OffsetFailure`] that replaced one +/// ([`sweep::SweepFailure::replaces_upstream_status`], +/// [`curve::CurveFailure::replaces_upstream_status`], +/// [`offset::OffsetFailure::replaces_upstream_status`])). /// /// For difftest's comparison only: it is removed with `Upstream` and `sm_status` in the /// last PR of the typed-errors work. Callers match [`SolidError::kind`] and the @@ -2336,16 +2345,17 @@ mod tests { pub(crate) mod replaced_upstream_samples { use super::SolidError; - /// The typed failures of three areas that replaced an `Upstream` with `code` (#13790): - /// an intersection's, a geometry utility's and a topology routine's, at `entity` when one is given. + /// The typed failures of four areas that replaced an `Upstream` with `code` (#13790): + /// an intersection's, a geometry utility's, a topology routine's and an offset routine's, + /// at `entity` when one is given. pub(crate) fn replaced_upstream( operation: &'static str, code: i32, entity: Option, - ) -> [SolidError; 3] { + ) -> [SolidError; 4] { use crate::error::{ - geom::GeomFailure, intersect::IntersectFailure, topology::TopologyFailure, Failure, - Reason, + geom::GeomFailure, intersect::IntersectFailure, offset::OffsetFailure, + topology::TopologyFailure, Failure, Reason, }; let typed = |reason: Reason| { let f = Failure::new(operation, reason).with_status(code); @@ -2365,6 +2375,9 @@ pub(crate) mod replaced_upstream_samples { typed(Reason::Topology(TopologyFailure::Failed( "replaced an upstream status", ))), + typed(Reason::Offset(OffsetFailure::Failed( + "replaced an upstream status", + ))), ] } diff --git a/solidcore/crates/solidcore/src/error/intersect.rs b/solidcore/crates/solidcore/src/error/intersect.rs index 1586c6184a6..2f7b6aba6bd 100644 --- a/solidcore/crates/solidcore/src/error/intersect.rs +++ b/solidcore/crates/solidcore/src/error/intersect.rs @@ -18,8 +18,8 @@ //! `operation` path says which routine. The handles these routines work on are the //! classification's or intersector's own, not ids of the caller's B-rep, so no failure //! names an entity. The failures that are checks of a caller's handles stay -//! [`crate::SolidError::InvalidInput`]. `surface_intersector` and `topology_solver` do -//! not use these yet. +//! [`crate::SolidError::InvalidInput`]. `surface_intersector/p1` and `p5`, which have +//! open work elsewhere, do not use these yet. use super::{ ErrorKind, Failure, Reason, SM_ERR, SM_ERR_ASSERT_FAILURE, SM_ERR_NULL_POINTER, @@ -112,7 +112,7 @@ impl crate::SolidError { } #[cfg(test)] -mod tests { +pub(super) mod tests { use super::*; use crate::SolidError; @@ -153,38 +153,141 @@ mod tests { ); } - /// The intersection routines that describe their failures build no bare `Upstream` - /// status in their library code. + /// A sample of the second set of converted files (`surface_intersector/p2` to `p4`, + /// `topology_solver/p1` and `p2`): each keeps the operation, status, kind and entity of + /// its `Upstream`. #[test] - fn the_described_intersect_routines_build_no_bare_statuses() { - let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/intersect"); - let mut files = vec![ - "point_class.rs".to_owned(), - "ray_tracer.rs".to_owned(), - "surface_drop_curve.rs".to_owned(), - "surface_drop_lib/p1.rs".to_owned(), - "surface_drop_lib/p2.rs".to_owned(), - "surface_drop_lib/p3.rs".to_owned(), - "adv_surface_intersector.rs".to_owned(), - "api_intersectors.rs".to_owned(), - "surface_silhouette.rs".to_owned(), - "surface_tracer.rs".to_owned(), + fn the_surface_intersector_and_topology_solver_samples_keep_their_upstream_answers() { + let samples = [ + ( + "intersect::surface_intersector::p2::SurfaceIntersector::compute_point_values", + IntersectFailure::Failed("the surface point has no normal"), + SM_ERR, + ), + ( + "intersect::surface_intersector::p3::SurfaceIntersector::find_boundary_start_points", + IntersectFailure::Missing("the surface's cache"), + SM_ERR_NULL_POINTER, + ), + ( + "intersect::surface_intersector::p4::SurfaceIntersector::do_law_intersection", + IntersectFailure::Missing("the first surface's offset surface"), + SM_ERR_NULL_POINTER, + ), + ( + "intersect::topology_solver::p1::LocalSolver::solve_it", + IntersectFailure::Failed("the base, point and curve local solvers solve nothing"), + SM_ERR, + ), + ( + "intersect::topology_solver::p2::LocalSolver::solve_face_face", + IntersectFailure::Missing("the first surface to solve against"), + SM_ERR_NULL_POINTER, + ), + ]; + for (operation, failure, code) in samples { + let typed = SolidError::intersect(operation, failure); + let before = SolidError::Upstream { + operation, + code, + entity: None, + }; + assert_eq!(typed.sm_status(), before.sm_status(), "{typed:?}"); + assert_eq!(typed.upstream_status(), Some(code), "{typed:?}"); + assert_eq!(super::super::upstream_status(&typed), Some(code)); + assert_eq!(typed.kind(), before.kind(), "{typed:?}"); + assert_eq!(typed.operation(), before.operation(), "{typed:?}"); + assert_eq!(typed.entity(), None, "{typed:?}"); + assert_eq!(typed.is_port_failure(), before.is_port_failure()); + assert_eq!(typed.is_status_answer(), before.is_status_answer()); + assert_eq!( + typed.is_unported_or_cancelled(), + before.is_unported_or_cancelled() + ); + } + } + + /// The intersection routines describe their failures: their library code builds no + /// bare `Upstream` status, except the files listed (with the bare sites each may still + /// hold) whose conversion waits on other open work. + #[test] + fn the_intersect_routines_build_no_bare_statuses() { + const WAITING: [(&str, usize); 2] = [ + ("intersect/surface_intersector/p1.rs", 6), + ("intersect/surface_intersector/p5.rs", 6), ]; - files.extend((1..=9).map(|i| format!("curve_class/p{i}.rs"))); - for rel in files { - let text = std::fs::read_to_string(src.join(&rel)) + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + assert_eq!(bare_statuses_under(&root, "intersect", 40), WAITING); + } + + /// The files under `src/` (and `src/.rs`) whose library code builds bare + /// statuses, with the number each builds, in path order; at least `least` files are read. + pub(in crate::error) fn bare_statuses_under( + root: &std::path::Path, + area: &str, + least: usize, + ) -> Vec<(&'static str, usize)> { + let mut files = vec![root.join(format!("{area}.rs"))]; + let mut dirs = vec![root.join(area)]; + while let Some(dir) = dirs.pop() { + for entry in std::fs::read_dir(dir).expect("read dir") { + let path = entry.expect("entry").path(); + if path.is_dir() { + dirs.push(path); + } else if path.extension().is_some_and(|x| x == "rs") { + files.push(path); + } + } + } + files.sort(); + assert!(files.len() >= least, "{files:?}"); + let mut found = Vec::new(); + for path in files { + let relative = path + .strip_prefix(root) + .expect("under src") + .to_string_lossy() + .replace('\\', "/"); + if relative.ends_with("/tests.rs") || relative.ends_with("_tests.rs") { + continue; + } + let text = std::fs::read_to_string(&path) .expect("read") .replace("\r\n", "\n"); + // The library part ends at the test module: `#[cfg(test)]`, then any attributes + // (such as an `#[allow(..)]` for the tests' unwraps), then `mod` with any + // visibility. let library = text - .find("#[cfg(test)]\nmod tests") - .map_or(text.as_str(), |at| &text[..at]); - for needle in [ + .match_indices("\n#[cfg(test)]\n") + .find(|(at, _)| { + let mut rest = text[at + "\n#[cfg(test)]\n".len()..].lines(); + rest.find(|line| { + let line = line.trim_start(); + !(line.starts_with("#[") || line.starts_with("clippy::") || line == ")]") + }) + .is_some_and(|line| { + let line = line + .strip_prefix("pub(crate) ") + .or_else(|| line.strip_prefix("pub(super) ")) + .or_else(|| line.strip_prefix("pub ")) + .unwrap_or(line); + line.starts_with("mod ") + }) + }) + .map_or(text.as_str(), |(at, _)| &text[..at]); + let bare: usize = [ "SolidError::sm_err(", "SolidError::null_pointer(", "SolidError::Upstream {", - ] { - assert!(!library.contains(needle), "{needle} in {rel}"); + "SolidError::nl_ser(", + ] + .iter() + .map(|needle| library.matches(needle).count()) + .sum(); + if bare > 0 { + found.push((&*relative.leak(), bare)); } } + found } } diff --git a/solidcore/crates/solidcore/src/error/offset.rs b/solidcore/crates/solidcore/src/error/offset.rs index 1c40377b4fc..e9db0bffb15 100644 --- a/solidcore/crates/solidcore/src/error/offset.rs +++ b/solidcore/crates/solidcore/src/error/offset.rs @@ -20,12 +20,22 @@ //! | [`OffsetFailure::ReachUncertified`] | `SM_ERR` (solidcore-native) | //! | [`OffsetFailure::LoopGapUncertified`] | `SM_ERR` (solidcore-native) | //! | [`OffsetFailure::Unsound`] | `SM_ERR` (solidcore-native) | +//! | [`OffsetFailure::Failed`] | `SM_ERR` | +//! | [`OffsetFailure::Missing`] | `SM_ERR_NULL_POINTER` | +//! | [`OffsetFailure::InvalidValue`] | `SM_ERR_INVALID_INPUT` | +//! | [`OffsetFailure::Inconsistent`] | `SM_ERR_ASSERT_FAILURE` | //! -//! Deviations: not upstream. Entity ids are those of the operation's input B-rep. +//! Deviations: not upstream. Entity ids are those of the operation's input B-rep. The +//! last four describe, in a phrase, the failures of offset routines that returned a bare +//! status ([`OffsetFailure::replaces_upstream_status`]); the failure's `operation` path +//! says which routine and its entity, where the site named one, which face. The files +//! with open work elsewhere (`offset_executive/{p1,p2,step_gaps,reach}`, +//! `offset_faces`, `offset_geometry_creation`) do not use them yet. use super::{ - EntityRef, ErrorKind, SM_ERR, SM_ERR_BAD_INTERSECTIONS, SM_ERR_INVALID_INPUT, - SM_ERR_OFFSET_EDGE_VANISHES, SM_ERR_OFFSET_WALLS_TOUCH, + EntityRef, ErrorKind, Failure, Reason, SM_ERR, SM_ERR_ASSERT_FAILURE, SM_ERR_BAD_INTERSECTIONS, + SM_ERR_INVALID_INPUT, SM_ERR_NULL_POINTER, SM_ERR_OFFSET_EDGE_VANISHES, + SM_ERR_OFFSET_WALLS_TOUCH, }; use crate::topology::{EdgeId, FaceId}; @@ -160,6 +170,17 @@ pub enum OffsetFailure { /// What the built body fails. what: Unsoundness, }, + /// An offset routine could not continue, as the phrase says (for example "the face + /// has no surface"). + Failed(&'static str), + /// Something an offset routine needs is missing, as the phrase says (for example "the + /// offset B-rep"). + Missing(&'static str), + /// A value an offset routine was given is not one it can use, as the phrase says. + InvalidValue(&'static str), + /// A consistency check of an offset routine's own data did not hold, as the phrase + /// says. + Inconsistent(&'static str), } /// What a local operation's or a solid offset's built body fails ([`OffsetFailure::Unsound`]). @@ -248,10 +269,26 @@ impl OffsetFailure { Self::ExactCurveUncut | Self::Unsound { .. } | Self::DistanceUnresolved { .. } - | Self::ToleranceUnresolved { .. } => None, + | Self::ToleranceUnresolved { .. } + | Self::Failed(_) + | Self::Missing(_) + | Self::InvalidValue(_) + | Self::Inconsistent(_) => None, } } + /// True for a failure that replaced a bare status an offset routine returned + /// ([`OffsetFailure::Failed`], [`OffsetFailure::Missing`], + /// [`OffsetFailure::InvalidValue`], [`OffsetFailure::Inconsistent`]): it answers with + /// that status as the `Upstream` it replaced did. The refusals replaced none. + #[must_use] + pub const fn replaces_upstream_status(&self) -> bool { + matches!( + self, + Self::Failed(_) | Self::Missing(_) | Self::InvalidValue(_) | Self::Inconsistent(_) + ) + } + /// The status the C++ reports for the refusal (difftest's comparison detail). pub(crate) const fn comparison_status(&self) -> i32 { match self { @@ -263,7 +300,11 @@ impl OffsetFailure { | Self::ReachUncertified { .. } | Self::ExactCurveUncut | Self::LoopGapUncertified { .. } - | Self::Unsound { .. } => SM_ERR, + | Self::Unsound { .. } + | Self::Failed(_) => SM_ERR, + Self::Missing(_) => SM_ERR_NULL_POINTER, + Self::InvalidValue(_) => SM_ERR_INVALID_INPUT, + Self::Inconsistent(_) => SM_ERR_ASSERT_FAILURE, Self::WallsTouch { .. } => SM_ERR_OFFSET_WALLS_TOUCH, Self::LoopsCross { .. } => SM_ERR_BAD_INTERSECTIONS, Self::EdgeVanishes { .. } => SM_ERR_OFFSET_EDGE_VANISHES, @@ -291,6 +332,9 @@ impl OffsetFailure { Self::DistanceUnresolved { .. } | Self::ToleranceUnresolved { .. } => { ErrorKind::InvalidInput } + Self::Failed(_) | Self::Missing(_) | Self::InvalidValue(_) | Self::Inconsistent(_) => { + ErrorKind::of_status(self.comparison_status()) + } } } @@ -486,6 +530,152 @@ impl core::fmt::Display for OffsetFailure { "invalid input: offset tolerance {tolerance:e} is nonzero but at or below the \ effective zero (1e-12): no B-rep can hold a tolerance that small" ), + Self::Failed(what) => f.write_str(what), + Self::Missing(what) => write!(f, "{what} is missing"), + Self::InvalidValue(what) => write!(f, "invalid input: {what}"), + Self::Inconsistent(what) => write!(f, "a consistency check failed: {what}"), + } + } +} + +impl crate::SolidError { + /// [`crate::SolidError::Failed`] for an offset routine that fails with `failure`. + #[must_use] + pub(crate) fn offset(operation: &'static str, failure: OffsetFailure) -> Self { + Failure::new(operation, failure).into_error() + } + + /// [`crate::SolidError::Failed`] for something an offset routine needs that is not + /// there, as the phrase says, with status [`SM_ERR_NULL_POINTER`] (upstream `NER(ptr)` + /// on a `NULL` pointer). + #[must_use] + pub(crate) fn offset_missing(operation: &'static str, what: &'static str) -> Self { + Self::offset(operation, OffsetFailure::Missing(what)) + } + + /// The offset failure behind this error, for a [`crate::SolidError::Failed`] with a + /// [`Reason::Offset`]. + #[must_use] + pub fn offset_failure(&self) -> Option<&OffsetFailure> { + match self { + Self::Failed(f) => match &f.reason { + Reason::Offset(o) => Some(o), + _ => None, + }, + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::SolidError; + + /// The offset failures that replaced a bare status keep the status, kind, operation + /// and entity of the `Upstream` they replace; a sample of each converted file + /// (`offset_executive/crossing_loops`, `offset_executive/cavity`, `draft`). + #[test] + fn offset_failures_keep_the_status_and_kind_of_the_upstream_they_replace() { + let face = Some(EntityRef::Face(FaceId::from_index(3))); + let samples = [ + ( + "offset::offset_executive::crossing_loops", + OffsetFailure::Inconsistent( + "an edge use's UV trim curve does not span its edge's interval", + ), + SM_ERR_ASSERT_FAILURE, + None, + ), + ( + "offset::offset_executive::crossing_loops", + OffsetFailure::Missing("an entity or curve of the offset face"), + SM_ERR_NULL_POINTER, + None, + ), + ( + "offset::offset_executive::cavity::is_cavity_region", + OffsetFailure::Missing("the face's surface"), + SM_ERR_NULL_POINTER, + None, + ), + ( + "offset::draft", + OffsetFailure::InvalidValue("the face has no surface or no outer face use"), + SM_ERR_INVALID_INPUT, + face, + ), + ("offset::op", OffsetFailure::Failed("x"), SM_ERR, None), + ]; + for (operation, failure, code, entity) in samples { + assert!(failure.replaces_upstream_status()); + let typed = match entity { + Some(e) => Failure::new(operation, failure).at(e).into_error(), + None => SolidError::offset(operation, failure), + }; + let before = SolidError::Upstream { + operation, + code, + entity, + }; + assert_eq!(typed.sm_status(), before.sm_status(), "{typed:?}"); + assert_eq!(typed.upstream_status(), Some(code), "{typed:?}"); + assert_eq!(super::super::upstream_status(&typed), Some(code)); + assert_eq!(typed.kind(), before.kind(), "{typed:?}"); + assert_eq!(typed.operation(), before.operation(), "{typed:?}"); + assert_eq!(typed.entity(), before.entity(), "{typed:?}"); + assert_eq!(typed.is_port_failure(), before.is_port_failure()); + assert_eq!(typed.is_status_answer(), before.is_status_answer()); + assert_eq!( + typed.is_unported_or_cancelled(), + before.is_unported_or_cancelled() + ); + assert_eq!(typed.offset_failure(), Some(&failure)); } + assert_eq!( + Failure::new( + "offset::draft", + OffsetFailure::InvalidValue("the face has no surface or no outer face use"), + ) + .at(EntityRef::Face(FaceId::from_index(3))) + .into_error() + .to_string(), + "offset::draft: invalid input: the face has no surface or no outer face use (face 3)" + ); + assert_eq!( + SolidError::offset_missing("offset::op", "the face's surface").to_string(), + "offset::op: the face's surface is missing" + ); + // a refusal replaced no status and does not answer as one + let folds = SolidError::offset( + "offset::op", + OffsetFailure::Folds { + face: FaceId::from_index(1), + distance: 2.0, + largest: 1.0, + }, + ); + assert_eq!(folds.upstream_status(), None); + assert_eq!(SolidError::sm_err("offset::op").offset_failure(), None); + } + + /// The offset routines describe their failures: their library code builds no bare + /// `Upstream` status, except the files listed (with the bare sites each may still + /// hold) whose conversion waits on other open work. + #[test] + fn the_offset_routines_build_no_bare_statuses() { + const WAITING: [(&str, usize); 6] = [ + ("offset/offset_executive/p1.rs", 9), + ("offset/offset_executive/p2.rs", 9), + ("offset/offset_executive/reach.rs", 1), + ("offset/offset_executive/step_gaps.rs", 1), + ("offset/offset_faces.rs", 4), + ("offset/offset_geometry_creation.rs", 17), + ]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + assert_eq!( + super::super::intersect::tests::bare_statuses_under(&root, "offset", 20), + WAITING + ); } } diff --git a/solidcore/crates/solidcore/src/intersect/surface_intersector/p2.rs b/solidcore/crates/solidcore/src/intersect/surface_intersector/p2.rs index 2f163e0a416..1226d109b95 100644 --- a/solidcore/crates/solidcore/src/intersect/surface_intersector/p2.rs +++ b/solidcore/crates/solidcore/src/intersect/surface_intersector/p2.rs @@ -532,7 +532,10 @@ impl SurfaceIntersector<'_> { // error case - surface point has no normal if norm.length_squared() < EFF_ZERO_SQ { - return Err(SolidError::sm_err(OP_CPV)); + return Err(SolidError::intersect_failed( + OP_CPV, + "the surface point has no normal", + )); } } @@ -638,7 +641,12 @@ impl SurfaceIntersector<'_> { ) { Ok(()) => {} Err(e) if e.is_unported_or_cancelled() => return Err(e), - Err(_) => return Err(SolidError::sm_err(OP_SING)), + Err(_) => { + return Err(SolidError::intersect_failed( + OP_SING, + "the advanced intersector could not place the singular point", + )) + } } } else { compute_singularity_point_base(uv_values, point, previous)?; @@ -851,7 +859,11 @@ impl SurfaceIntersector<'_> { // for every point to flush let n = pnts.len(); - let at = |i: usize| pnts.get(i).ok_or_else(|| SolidError::sm_err(OP_FLUSH)); + let at = |i: usize| { + pnts.get(i).ok_or_else(|| { + SolidError::intersect_failed(OP_FLUSH, "the curve has no point at that index") + }) + }; let mut i = 1; while i < n { let prev = at(i - 1)?; @@ -1171,7 +1183,10 @@ impl SurfaceIntersector<'_> { let mut ii = 1usize; loop { if ii > MAX_GAP_SAMPLES { - return Err(SolidError::sm_err(OP_CLASSIFY)); + return Err(SolidError::intersect_failed( + OP_CLASSIFY, + "the boundary start point is not classified within the sample limit", + )); } // the sample array index: 1, then 2 (the last sample moves to 1) let tgt = if ii > 1 { 2 } else { 1 }; @@ -1418,7 +1433,10 @@ fn compute_singularity_point_base( _point: &mut TsectPnt, _previous: Option<&TsectPnt>, ) -> Result<()> { - Err(SolidError::sm_err(OP_SING)) + Err(SolidError::intersect_failed( + OP_SING, + "the basic intersector does not handle singular or tangent points", + )) } /// True when `point` is farther than `tol_3d` from every start point's curve point @@ -1649,7 +1667,10 @@ pub fn compute_law_point_values_with<'s, V: IntersectorVirtuals<'s> + ?Sized>( // `SER( Inversion(dParameter, ..) )`: SM_ERR outside the interval or for a // zero-length one if pass && !inv.is_success() { - return Err(SolidError::sm_err(OP_LAW)); + return Err(SolidError::intersect_failed( + OP_LAW, + "the law curve's normal could not be inverted", + )); } let t = inv.parameter.unwrap_or(UNDEF_DOUBLE); pv[1] = n0 * (1.0 - t) + n1 * t; @@ -1657,7 +1678,10 @@ pub fn compute_law_point_values_with<'s, V: IntersectorVirtuals<'s> + ?Sized>( // the step may end just past the interval, where the unclamped parameter // is set and extrapolates as wanted: only an undefined one is passed on if pass && inv.parameter.is_none() { - return Err(SolidError::sm_err(OP_LAW)); + return Err(SolidError::intersect_failed( + OP_LAW, + "the law curve's normal inversion gave no parameter", + )); } let t = inv.parameter.unwrap_or(UNDEF_DOUBLE); pv_delta[1] = n0 * (1.0 - t) + n1 * t; @@ -1722,7 +1746,10 @@ pub fn compute_law_point_values_with<'s, V: IntersectorVirtuals<'s> + ?Sized>( // next iteration with a bigger delta step delta_step *= 10.0; } - Err(SolidError::sm_err(OP_LAW)) + Err(SolidError::intersect_failed( + OP_LAW, + "no delta step gives the law point's values", + )) } #[cfg(test)] diff --git a/solidcore/crates/solidcore/src/intersect/surface_intersector/p3.rs b/solidcore/crates/solidcore/src/intersect/surface_intersector/p3.rs index 914546be292..6c4674fa637 100644 --- a/solidcore/crates/solidcore/src/intersect/surface_intersector/p3.rs +++ b/solidcore/crates/solidcore/src/intersect/surface_intersector/p3.rs @@ -78,7 +78,7 @@ use crate::blend::fillet_standard_solver::p1::FilletLaw; use crate::curve::curve::Curve; -use crate::error::{passed_on, Result, SolidError, SM_ERR_NULL_POINTER}; +use crate::error::{passed_on, Result, SolidError}; use crate::geom::extent1d::{Extent1d, ExtentPointType}; use crate::geom::extent2d::Extent2d; use crate::geom::extent3d::Extent3d; @@ -262,11 +262,10 @@ impl SurfaceIntersector<'_> { let get = |i: SrfIndex| match surface_cache::(k, self.surface(i), Some(i)) { Ok(c) => Ok(c), Err(e) if e.is_unported_or_cancelled() => Err(e), - Err(_) => Err(SolidError::Upstream { - operation: OP_FBSP, - code: SM_ERR_NULL_POINTER, - entity: None, - }), + Err(_) => Err(SolidError::intersect_missing( + OP_FBSP, + "the surface's cache", + )), }; let mut caches = vec![get(SrfIndex::First)?]; if !self.doing_self_intersection { @@ -315,11 +314,10 @@ impl SurfaceIntersector<'_> { queries: Option<&dyn FaceQueries>, ) -> Result<()> { if caches.is_empty() { - return Err(SolidError::Upstream { - operation: OP_FBSP, - code: SM_ERR_NULL_POINTER, - entity: None, - }); + return Err(SolidError::intersect_missing( + OP_FBSP, + "the surfaces' caches", + )); } // Turn on boundary curve processing to force LocalSolve to look for drop @@ -369,11 +367,9 @@ impl SurfaceIntersector<'_> { // Get thisSurface->3DBoundaryCurves: [0] min u, [1] min v, [2] max u, // [3] max v let cache_index = l_srf.min(caches.len() - 1); - let cache = caches.get_mut(cache_index).ok_or(SolidError::Upstream { - operation: OP_FBSP, - code: SM_ERR_NULL_POINTER, - entity: None, - })?; + let cache = caches + .get_mut(cache_index) + .ok_or_else(|| SolidError::intersect_missing(OP_FBSP, "the surface's cache"))?; let iso = cache.iso_boundary_curves(k, &domain, self.this_approx_tol_3d / 3.0)?; // add the intervals of the iso curves (statuses ignored, passed on with @@ -422,13 +418,12 @@ impl SurfaceIntersector<'_> { } else { // on OtherSurface's cache: upstream's GlobalCurveIntersect fetches // that same cache (smsurf_GetSurfaceCache) and solves on its tree - let other_cache = caches.get((1 - l_srf).min(caches.len() - 1)).ok_or( - SolidError::Upstream { - operation: OP_FBSP, - code: SM_ERR_NULL_POINTER, - entity: None, - }, - )?; + let other_cache = + caches + .get((1 - l_srf).min(caches.len() - 1)) + .ok_or_else(|| { + SolidError::intersect_missing(OP_FBSP, "the other surface's cache") + })?; surface_global_curve_intersect( k, self.surface(other), @@ -896,7 +891,10 @@ impl SurfaceIntersector<'_> { if !self.uv_domains[0].contains_point(prev_tsp.uv_pos(s0), EFF_ZERO) || !self.uv_domains[1].contains_point(prev_tsp.uv_pos(s1), EFF_ZERO) { - return Err(SolidError::sm_err(OP_NEXT)); + return Err(SolidError::intersect_failed( + OP_NEXT, + "the previous point lies outside a surface's domain", + )); } // if needed: clip stepsize to keep nextTSP in both surfaces diff --git a/solidcore/crates/solidcore/src/intersect/surface_intersector/p4.rs b/solidcore/crates/solidcore/src/intersect/surface_intersector/p4.rs index 3c1970afec9..badcda52e2e 100644 --- a/solidcore/crates/solidcore/src/intersect/surface_intersector/p4.rs +++ b/solidcore/crates/solidcore/src/intersect/surface_intersector/p4.rs @@ -462,10 +462,16 @@ impl SurfaceIntersector<'_> { fn check_in_domains(&self, next: TsectId, uv_tol: [f64; 2]) -> Result<()> { let p = self.point(next)?; if !self.uv_domains[0].contains_point(p.uv_pos(SrfIndex::First), uv_tol[0]) { - return Err(SolidError::sm_err(OP_TRACE)); + return Err(SolidError::intersect_failed( + OP_TRACE, + "the traced point lies outside the first surface's domain", + )); } if !self.uv_domains[1].contains_point(p.uv_pos(SrfIndex::Second), uv_tol[1]) { - return Err(SolidError::sm_err(OP_TRACE)); + return Err(SolidError::intersect_failed( + OP_TRACE, + "the traced point lies outside the second surface's domain", + )); } Ok(()) } @@ -647,7 +653,10 @@ impl SurfaceIntersector<'_> { pub fn find_interior_curves(&mut self, k: &Kernel, out: &mut TsectCurves) -> Result<()> { // The basic intersector does not allow self intersection testing. if self.doing_self_intersection { - return Err(SolidError::sm_err(OP_FIC)); + return Err(SolidError::intersect_failed( + OP_FIC, + "the basic intersector does not test self intersection", + )); } // Find node pairs in the tree (SER: checked; surface::surface::p7, its leaf @@ -698,7 +707,10 @@ impl SurfaceIntersector<'_> { out: &mut TsectCurves, ) -> Result<()> { if self.doing_self_intersection { - return Err(SolidError::sm_err(OP_FIC)); + return Err(SolidError::intersect_failed( + OP_FIC, + "the basic intersector does not test self intersection", + )); } let mut curve_caches: Vec>> = Vec::new(); for pair in pairs { @@ -719,12 +731,14 @@ impl SurfaceIntersector<'_> { None => slot.insert(match make_curve_cache::<()>(k, curve, None) { Ok(c) => c, Err(e) if e.is_unported_or_cancelled() => return Err(e), - Err(_) => return Err(SolidError::null_pointer(OP_FIC)), + Err(_) => { + return Err(SolidError::intersect_missing(OP_FIC, "the curve's cache")) + } }), }; - let tree = cache - .tree() - .ok_or_else(|| SolidError::null_pointer(OP_FIC))?; + let tree = cache.tree().ok_or_else(|| { + SolidError::intersect_missing(OP_FIC, "the curve cache's tree") + })?; if tree.intersects_box(&int_bbox)? { is_near_curve = true; break; @@ -865,7 +879,10 @@ pub fn do_law_intersection_with<'s, V: IntersectorVirtuals<'s> + ?Sized>( law_curve: &mut FilletLaw, ) -> Result { let [first, last] = points else { - return Err(SolidError::sm_err(OP_DLI)); + return Err(SolidError::intersect_failed( + OP_DLI, + "the law intersection needs exactly two points", + )); }; let (first, last) = (*first, *last); @@ -876,10 +893,16 @@ pub fn do_law_intersection_with<'s, V: IntersectorVirtuals<'s> + ?Sized>( // the offset surfaces if !is_offset_surface(v.intersector().surface(SrfIndex::First)) { - return Err(SolidError::null_pointer(OP_DLI)); + return Err(SolidError::intersect_missing( + OP_DLI, + "the first surface's offset surface", + )); } if !is_offset_surface(v.intersector().surface(SrfIndex::Second)) { - return Err(SolidError::null_pointer(OP_DLI)); + return Err(SolidError::intersect_missing( + OP_DLI, + "the second surface's offset surface", + )); } let normals = [ @@ -1401,7 +1424,7 @@ pub fn trace_curve_with<'s, V: IntersectorVirtuals<'s> + ?Sized>( point_count += 1; if point_count == 5000 { // the tolerance is too small or a surface is poorly defined - return Err(SolidError::sm_err(OP_TRACE)); + return Err(SolidError::intersect_failed(OP_TRACE, "the trace reached 5000 points: the tolerance is too small or a surface is poorly defined")); } } Ok(()) @@ -1541,7 +1564,10 @@ fn do_point_intersection_body<'s, V: IntersectorVirtuals<'s> + ?Sized>( // no work - no through points specified if points.is_empty() { - return Err(SolidError::sm_err(OP_DPI)); + return Err(SolidError::intersect_failed( + OP_DPI, + "no through points were given", + )); } // Use supplied tolerances when given @@ -1598,7 +1624,12 @@ fn do_point_intersection_body<'s, V: IntersectorVirtuals<'s> + ?Sized>( match r { Ok(()) => {} Err(e) if e.is_unported_or_cancelled() => return Err(e), - Err(_) => return Err(SolidError::sm_err(OP_DPI)), + Err(_) => { + return Err(SolidError::intersect_failed( + OP_DPI, + "the through point's values could not be computed", + )) + } } // the first points must be on both surfaces @@ -1608,7 +1639,10 @@ fn do_point_intersection_body<'s, V: IntersectorVirtuals<'s> + ?Sized>( tsp.srf_pos(SrfIndex::Second), ) { - return Err(SolidError::sm_err(OP_DPI)); + return Err(SolidError::intersect_failed( + OP_DPI, + "the first through point is not on both surfaces", + )); } if ii == 0 { @@ -1651,7 +1685,7 @@ fn do_point_intersection_body<'s, V: IntersectorVirtuals<'s> + ?Sized>( .intersector_mut() .start_points .pop() - .ok_or_else(|| SolidError::null_pointer(OP_DPI))?; + .ok_or_else(|| SolidError::intersect_missing(OP_DPI, "a start point to trace from"))?; v.intersector_mut().curve_trace_direction = 1.0; // tracing beyond the end: clip the extension @@ -2083,7 +2117,13 @@ mod tests { *p.uv_pos_mut(SrfIndex::Second) = Point2::new(0.5, 0.5); let id = si.alloc_point(p); let r = si.do_point_intersection(&k, &[id], &opts); - assert!(matches!(r, Err(SolidError::Upstream { .. }))); + assert!( + r.as_ref() + .err() + .and_then(SolidError::upstream_status) + .is_some(), + "{r:?}" + ); assert_eq!(si.point(id).unwrap().curve_parameter, -1.0); } @@ -2113,20 +2153,25 @@ mod tests { let p = si.alloc_point(TsectPnt::new()); let q = si.alloc_point(TsectPnt::new()); let mut law = FilletLaw::new(crate::blend::fillet_standard_solver::p1::FilletLawKind::Base); - assert!(matches!( - si.do_law_intersection(k, &[p], &opts, &mut law), - Err(SolidError::Upstream { - code: crate::error::SM_ERR, - .. - }) - )); - assert!(matches!( - si.do_law_intersection(k, &[p, q], &opts, &mut law), - Err(SolidError::Upstream { - code: crate::error::SM_ERR_NULL_POINTER, - .. - }) - )); + let one = si + .do_law_intersection(k, &[p], &opts, &mut law) + .unwrap_err(); + assert_eq!(one.upstream_status(), Some(crate::error::SM_ERR), "{one}"); + assert_eq!( + one.intersect_failure(), + Some(&crate::error::intersect::IntersectFailure::Failed( + "the law intersection needs exactly two points" + )) + ); + let two = si + .do_law_intersection(k, &[p, q], &opts, &mut law) + .unwrap_err(); + assert_eq!( + two.upstream_status(), + Some(crate::error::SM_ERR_NULL_POINTER), + "{two}" + ); + assert_eq!(two.operation(), OP_DLI); assert_eq!(si.this_approx_tol_3d, 0.25); } @@ -2214,7 +2259,7 @@ mod tests { }; assert_eq!( si.find_interior_curves_from_node_pairs(&k, &[pair, far_pair], &mut out), - Err(SolidError::null_pointer(OP_FIC)) + Err(SolidError::intersect_missing(OP_FIC, "the curve's cache")) ); // Pair validation still precedes even the first curve-cache build. @@ -2234,7 +2279,7 @@ mod tests { // No cache from the earlier call may survive replacing its output curve. assert_eq!( si.find_interior_curves_from_node_pairs(&k, &[pair], &mut out), - Err(SolidError::null_pointer(OP_FIC)) + Err(SolidError::intersect_missing(OP_FIC, "the curve's cache")) ); } } diff --git a/solidcore/crates/solidcore/src/intersect/topology_solver/p1.rs b/solidcore/crates/solidcore/src/intersect/topology_solver/p1.rs index 0176c0ffd14..6e052c84e17 100644 --- a/solidcore/crates/solidcore/src/intersect/topology_solver/p1.rs +++ b/solidcore/crates/solidcore/src/intersect/topology_solver/p1.rs @@ -211,9 +211,15 @@ pub trait TopologyObjects { const OP: &str = "intersect::topology_solver::p1::TopologyObjects::brep_trees"; let cache = self.brep_cache(brep)?; Ok(super::p2::TopologyTrees { - vertices: cache.vertex_tree().ok_or(SolidError::null_pointer(OP))?, - curves: cache.curve_tree().ok_or(SolidError::null_pointer(OP))?, - surfaces: cache.surface_tree().ok_or(SolidError::null_pointer(OP))?, + vertices: cache.vertex_tree().ok_or_else(|| { + SolidError::intersect_missing(OP, "the B-rep cache's vertex tree") + })?, + curves: cache + .curve_tree() + .ok_or_else(|| SolidError::intersect_missing(OP, "the B-rep cache's curve tree"))?, + surfaces: cache.surface_tree().ok_or_else(|| { + SolidError::intersect_missing(OP, "the B-rep cache's surface tree") + })?, }) } @@ -234,9 +240,12 @@ pub trait TopologyObjects { let object = self.shape_member_object(member)?; match member { ShapeMember::Vertex(_) => Ok(object), - ShapeMember::Edge(_) => self.edge_curve(object)?.ok_or(SolidError::null_pointer( - "intersect::topology_solver::p2::shape_geometry_object", - )), + ShapeMember::Edge(_) => self.edge_curve(object)?.ok_or_else(|| { + SolidError::intersect_missing( + "intersect::topology_solver::p2::shape_geometry_object", + "the edge's curve", + ) + }), ShapeMember::Face(_) => self.face_surface(object), ShapeMember::Other => Err(SolidError::invalid_input( "intersect::topology_solver::p2::shape_geometry_object", @@ -1060,7 +1069,10 @@ impl<'a, O: SolutionObject> LocalSolver<'a, O> { ) -> Result<()> { match self.kind { LocalSolverKind::Base | LocalSolverKind::Point | LocalSolverKind::Curve => { - Err(SolidError::sm_err(OP_BASE)) + Err(SolidError::intersect_failed( + OP_BASE, + "the base, point and curve local solvers solve nothing", + )) } LocalSolverKind::PointVertex => self.solve_point_vertex(ts, object1, object2), LocalSolverKind::VertexVertex => self.solve_vertex_vertex(ts, object1, object2), @@ -1113,14 +1125,18 @@ impl<'a, O: SolutionObject> LocalSolver<'a, O> { let mut count = 0; let vertex; if self.swap_order { - vertex = object1.ok_or(SolidError::null_pointer(OP_PV))?; + vertex = object1.ok_or_else(|| { + SolidError::intersect_missing(OP_PV, "the vertex to solve against") + })?; push_object(&mut sol.objects, &mut count, Some(vertex)); if self.point_vertex.is_some() { // If the point represents a vertex then save it in list push_object(&mut sol.objects, &mut count, self.point_vertex); } } else { - vertex = object2.ok_or(SolidError::null_pointer(OP_PV))?; + vertex = object2.ok_or_else(|| { + SolidError::intersect_missing(OP_PV, "the vertex to solve against") + })?; if self.point_vertex.is_some() { // If the point represents a vertex then save it in list push_object(&mut sol.objects, &mut count, self.point_vertex); @@ -1518,14 +1534,18 @@ impl<'a, O: SolutionObject> LocalSolver<'a, O> { // we want we can switch the order. let surface; if self.swap_order { - surface = object1.ok_or(SolidError::null_pointer(OP_PF))?; + surface = object1.ok_or_else(|| { + SolidError::intersect_missing(OP_PF, "the surface to solve against") + })?; push_object(&mut sol_objects, &mut count, Some(surface)); if self.point_vertex.is_some() { // If the point represents a vertex then save it in list push_object(&mut sol_objects, &mut count, self.point_vertex); } } else { - surface = object2.ok_or(SolidError::null_pointer(OP_PF))?; + surface = object2.ok_or_else(|| { + SolidError::intersect_missing(OP_PF, "the surface to solve against") + })?; if self.point_vertex.is_some() { // If the point represents a vertex then save it in list push_object(&mut sol_objects, &mut count, self.point_vertex); @@ -1804,7 +1824,8 @@ impl<'a, O: SolutionObject> LocalSolver<'a, O> { ) -> Result<()> { let objects = ts.objects; let handle = if self.swap_order { object1 } else { object2 }; - let handle = handle.ok_or(SolidError::null_pointer(OP_CE))?; + let handle = handle + .ok_or_else(|| SolidError::intersect_missing(OP_CE, "the curve to solve against"))?; // Remove Composites - replaced Edge array with single curve Edge let edge = objects.curve_edge(handle)?; @@ -2202,7 +2223,9 @@ fn face_silhouettes_at_tolerance( .unwrap_or_default() .into_iter() .collect::>>() - .ok_or(SolidError::null_pointer(OP_FACE_SIL))?; + .ok_or_else(|| { + SolidError::intersect_missing(OP_FACE_SIL, "a UV curve of the trimmed silhouettes") + })?; // Register trimmed curves and create copy by getting them again cache.add_curves_to_cache( @@ -2227,7 +2250,10 @@ fn face_silhouettes_at_tolerance( copies.curves_3d.unwrap_or_default(), copies.curves_uv.unwrap_or_default(), )), - None => Err(SolidError::sm_err(OP_FACE_SIL)), + None => Err(SolidError::intersect_failed( + OP_FACE_SIL, + "the trimmed silhouettes are not in the cache", + )), } } @@ -2894,13 +2920,12 @@ pub(crate) mod tests { let mut ls = LocalSolver::new(LocalSolverKind::Curve, false, None); assert!(ls.solve_it(&k, &mut ts, None, None).is_err()); let mut ls = LocalSolver::new(LocalSolverKind::FaceFace, false, None); - assert!(matches!( - ls.solve_it(&k, &mut ts, None, None), - Err(SolidError::Upstream { - code: crate::error::SM_ERR_NULL_POINTER, - .. - }) - )); + let e = ls.solve_it(&k, &mut ts, None, None).unwrap_err(); + assert_eq!( + e.upstream_status(), + Some(crate::error::SM_ERR_NULL_POINTER), + "{e}" + ); } #[test] diff --git a/solidcore/crates/solidcore/src/intersect/topology_solver/p2.rs b/solidcore/crates/solidcore/src/intersect/topology_solver/p2.rs index fdc0014cbd9..4368fdd42c5 100644 --- a/solidcore/crates/solidcore/src/intersect/topology_solver/p2.rs +++ b/solidcore/crates/solidcore/src/intersect/topology_solver/p2.rs @@ -80,16 +80,12 @@ impl<'t, O: SolutionObject + 't> TopologySolver<'t, '_, O> { let tree2 = self.base.tree(1)?; let node1 = self.base.branch_node(branch, 0)?; let node2 = self.base.branch_node(branch, 1)?; - let id1 = branch - .first() - .copied() - .flatten() - .ok_or(SolidError::null_pointer(OP_LOCAL))?; - let id2 = branch - .get(1) - .copied() - .flatten() - .ok_or(SolidError::null_pointer(OP_LOCAL))?; + let id1 = branch.first().copied().flatten().ok_or_else(|| { + SolidError::intersect_missing(OP_LOCAL, "the branch's first tree node") + })?; + let id2 = branch.get(1).copied().flatten().ok_or_else(|| { + SolidError::intersect_missing(OP_LOCAL, "the branch's second tree node") + })?; let first_objects = if node1.aux_type == AuxDataType::ObjectList { tree1.node_object_list(id1)? } else { @@ -113,7 +109,7 @@ impl<'t, O: SolutionObject + 't> TopologySolver<'t, '_, O> { let mut local = self .local_solver .take() - .ok_or(SolidError::null_pointer(OP_LOCAL))?; + .ok_or_else(|| SolidError::intersect_missing(OP_LOCAL, "the local solver"))?; let result = local.solve_it(k, self, object1.object, object2.object); self.local_solver = Some(local); result?; @@ -132,7 +128,7 @@ impl<'a, O: SolutionObject> LocalSolver<'a, O> { object2: Option, ) -> Result<()> { let vertex = if self.swap_order { object2 } else { object1 } - .ok_or(SolidError::null_pointer(OP_VF))?; + .ok_or_else(|| SolidError::intersect_missing(OP_VF, "the vertex to solve against"))?; self.point_vertex = Some(vertex); self.point = ts.objects.vertex_point(vertex)?; self.solve_point_face(k, ts, object1, object2) @@ -152,10 +148,13 @@ impl<'a, O: SolutionObject> LocalSolver<'a, O> { } else { point_curve.interval = self.interval; } - let vertex = object2.ok_or(SolidError::null_pointer(OP_CV))?; + let vertex = object2 + .ok_or_else(|| SolidError::intersect_missing(OP_CV, "the vertex to solve against"))?; point_curve.point_vertex = Some(vertex); point_curve.point = ts.objects.vertex_point(vertex)?; - let curve = self.curve.ok_or(SolidError::null_pointer(OP_CV))?; + let curve = self + .curve + .ok_or_else(|| SolidError::intersect_missing(OP_CV, "the curve to solve against"))?; point_curve.point_curve(k, ts, curve.curve, Some(curve.handle)) } } @@ -170,14 +169,18 @@ fn swap_curve_surface_parameters(solution: &mut Solution) -> Result<()> { .start .parameters .get_mut(..3) - .ok_or(SolidError::sm_err(OP_CF))? + .ok_or_else(|| { + SolidError::intersect_failed(OP_CF, "the solution has fewer than three parameters") + })? .rotate_left(1); if solution.solution_type == SolutionType::RangeOfValues { solution .end .parameters .get_mut(..3) - .ok_or(SolidError::sm_err(OP_CF))? + .ok_or_else(|| { + SolidError::intersect_failed(OP_CF, "the solution has fewer than three parameters") + })? .rotate_left(1); } Ok(()) @@ -324,12 +327,12 @@ impl<'a, O: SolutionObject> LocalSolver<'a, O> { object2: Option, ) -> Result<()> { let vertex = if self.swap_order { object1 } else { object2 } - .ok_or(SolidError::null_pointer(OP_EV))?; + .ok_or_else(|| SolidError::intersect_missing(OP_EV, "the vertex to solve against"))?; // Upstream selects this SAME object as pCurve (SmTopologySolver.cpp:1032): // for a real vertex that cast is invalid. Validate the selected object class // instead of reinterpreting memory or silently correcting the operand. let curve_object = if self.swap_order { object1 } else { object2 } - .ok_or(SolidError::null_pointer(OP_EV))?; + .ok_or_else(|| SolidError::intersect_missing(OP_EV, "the curve to solve against"))?; if curve_object.kind() != crate::geom::solution_array::ObjectKind::Curve { return Err(SolidError::invalid_input( OP_EV, @@ -365,7 +368,7 @@ impl<'a, O: SolutionObject> LocalSolver<'a, O> { object2: Option, ) -> Result<()> { let curve = if self.swap_order { object2 } else { object1 } - .ok_or(SolidError::null_pointer(OP_EF))?; + .ok_or_else(|| SolidError::intersect_missing(OP_EF, "the curve to solve against"))?; let edge = ts.objects.curve_edge(curve)?; if self.in_shape(ts.objects, edge) { let edge = edge.ok_or(SolidError::invalid_input(OP_EF, "curve without an edge"))?; @@ -391,7 +394,7 @@ impl<'a, O: SolutionObject> LocalSolver<'a, O> { object2: Option, ) -> Result<()> { let surface_handle = if self.swap_order { object1 } else { object2 } - .ok_or(SolidError::null_pointer(OP_CF))?; + .ok_or_else(|| SolidError::intersect_missing(OP_CF, "the surface to solve against"))?; let owner = self .curve_edge .or(self.curve_face) @@ -406,7 +409,9 @@ impl<'a, O: SolutionObject> LocalSolver<'a, O> { return Ok(()); } let face = face.ok_or(SolidError::invalid_input(OP_CF, "surface without a face"))?; - let curve = self.curve.ok_or(SolidError::null_pointer(OP_CF))?; + let curve = self + .curve + .ok_or_else(|| SolidError::intersect_missing(OP_CF, "the curve to solve against"))?; if ts.base.projected_operation { let (curves, uv_curves) = p1::face_silhouettes( ts.kernel, @@ -432,7 +437,12 @@ impl<'a, O: SolutionObject> LocalSolver<'a, O> { local.curve_edge2 = None; local.interval2 = other.natural_interval(); local.curve_face2 = Some(face); - local.surface_curve2 = Some(uv_curves.get(i).ok_or(SolidError::sm_err(OP_CF))?); + local.surface_curve2 = Some(uv_curves.get(i).ok_or_else(|| { + SolidError::intersect_failed( + OP_CF, + "the silhouette has no UV curve at that index", + ) + })?); // (the silhouette curve exists only for this solve) local.temporary_curves = true; local.solve_curve_curve(k, ts)?; @@ -590,8 +600,12 @@ impl<'a, O: SolutionObject> LocalSolver<'a, O> { object1: Option, object2: Option, ) -> Result<()> { - let surface1 = object1.ok_or(SolidError::null_pointer(OP_FF))?; - let surface2 = object2.ok_or(SolidError::null_pointer(OP_FF))?; + let surface1 = object1.ok_or_else(|| { + SolidError::intersect_missing(OP_FF, "the first surface to solve against") + })?; + let surface2 = object2.ok_or_else(|| { + SolidError::intersect_missing(OP_FF, "the second surface to solve against") + })?; let face1 = ts.objects.surface_face(surface1)?; let face2 = ts.objects.surface_face(surface2)?; if !self.in_shape(ts.objects, face1) || !self.in_shape(ts.objects, face2) { @@ -624,7 +638,12 @@ impl<'a, O: SolutionObject> LocalSolver<'a, O> { local.curve_face = Some(face1); local.curve_edge = None; local.interval = curve.natural_interval(); - local.surface_curve = Some(uv_curves.get(i).ok_or(SolidError::sm_err(OP_FF))?); + local.surface_curve = Some(uv_curves.get(i).ok_or_else(|| { + SolidError::intersect_failed( + OP_FF, + "the silhouette has no UV curve at that index", + ) + })?); local.solve_curve_face(k, ts, Some(surface2), Some(surface2))?; } } else { @@ -775,10 +794,17 @@ fn curve_tree( true, )? .normal - .ok_or(SolidError::sm_err(OP))?; - let root = tree.top_node().ok_or(SolidError::sm_err(OP))?; + .ok_or_else(|| { + SolidError::intersect_failed(OP, "the curve's bounding box has no normal cone") + })?; + let root = tree + .top_node() + .ok_or_else(|| SolidError::intersect_failed(OP, "the curve tree has no top node"))?; tree.node_mut(root)?.bbox = bbox; - let list = tree.node(root)?.list_head().ok_or(SolidError::sm_err(OP))?; + let list = tree + .node(root)? + .list_head() + .ok_or_else(|| SolidError::intersect_failed(OP, "the curve tree's top node has no list"))?; let item = tree.list_mut(list)?; item.bbox = bbox; item.object = Some(curve.handle); @@ -853,7 +879,8 @@ impl<'t, O: SolutionObject + 't> TopologySolver<'t, '_, O> { if !valid_point_operation(options.operation) { return Err(SolidError::invalid_input(OP, "unsupported operation")); } - let brep = brep.ok_or(SolidError::null_pointer(OP))?; + let brep = + brep.ok_or_else(|| SolidError::intersect_missing(OP, "the B-rep to solve against"))?; let mut ts = new_topology_solver(kernel, objects, options); let trees = objects.brep_trees(brep)?; let query = point_tree(point); @@ -932,7 +959,10 @@ impl<'t, O: SolutionObject + 't> TopologySolver<'t, '_, O> { options.operation = SolverOperation::Intersect; } let mut ts = new_topology_solver(kernel, objects, options); - let trees = objects.brep_trees(brep.ok_or(SolidError::null_pointer(OP))?)?; + let trees = + objects.brep_trees(brep.ok_or_else(|| { + SolidError::intersect_missing(OP, "the B-rep to solve against") + })?)?; let query = curve_tree(kernel, curve, interval)?; if options.operation != SolverOperation::Normalize { let mut vertices = LocalSolver::new(LocalSolverKind::CurveVertex, false, None); @@ -1103,8 +1133,12 @@ impl<'t, O: SolutionObject + 't> TopologySolver<'t, '_, O> { return Err(SolidError::invalid_input(OP, "unsupported operation")); } let mut ts = new_topology_solver(kernel, objects, options); - let first = objects.brep_trees(first.ok_or(SolidError::null_pointer(OP))?)?; - let second = objects.brep_trees(second.ok_or(SolidError::null_pointer(OP))?)?; + let first = objects.brep_trees(first.ok_or_else(|| { + SolidError::intersect_missing(OP, "the first B-rep to solve against") + })?)?; + let second = objects.brep_trees(second.ok_or_else(|| { + SolidError::intersect_missing(OP, "the second B-rep to solve against") + })?)?; ts.solve_two_tree_sets(first, second)?; Ok(ts.base.solutions) } diff --git a/solidcore/crates/solidcore/src/offset/draft.rs b/solidcore/crates/solidcore/src/offset/draft.rs index 6186c573e0a..c7dc5dd1cde 100644 --- a/solidcore/crates/solidcore/src/offset/draft.rs +++ b/solidcore/crates/solidcore/src/offset/draft.rs @@ -54,7 +54,7 @@ use crate::blend::fillet_section::interval::Ivl; use crate::blend::fillet_section::station::as_b_spline; -use crate::error::SM_ERR_INVALID_INPUT; +use crate::error::{offset::OffsetFailure, Failure}; use crate::geom::axis2_placement::Axis2Placement; use crate::geom::certified::{above, distance, unit, unit_error}; use crate::geom::tol::are_same; @@ -767,12 +767,13 @@ impl DraftDefinition { /// `SM_ERR_INVALID_INPUT` for face `f` (the capi's status for a face without a surface or /// an outer faceuse). -const fn invalid(f: FaceId) -> SolidError { - SolidError::Upstream { - operation: OP, - code: SM_ERR_INVALID_INPUT, - entity: Some(EntityRef::Face(f)), - } +fn invalid(f: FaceId) -> SolidError { + Failure::new( + OP, + OffsetFailure::InvalidValue("the face has no surface or no outer face use"), + ) + .at(EntityRef::Face(f)) + .into_error() } /// The surface face `f` of a solid takes drafted by `draft`, with its definition diff --git a/solidcore/crates/solidcore/src/offset/offset_executive/cavity.rs b/solidcore/crates/solidcore/src/offset/offset_executive/cavity.rs index b4390e5b005..7c2a8396183 100644 --- a/solidcore/crates/solidcore/src/offset/offset_executive/cavity.rs +++ b/solidcore/crates/solidcore/src/offset/offset_executive/cavity.rs @@ -105,7 +105,7 @@ fn count_behind_ahead( let face_data = result.face(f)?; let Some(surface) = face_data.surface.as_ref() else { // (NER on GetSurface: a face without one is a null pointer) - return Err(SolidError::null_pointer(OP)); + return Err(SolidError::offset_missing(OP, "the face's surface")); }; (surface.clone_for_evaluation()?, face_data.uv_domain) }; diff --git a/solidcore/crates/solidcore/src/offset/offset_executive/crossing_loops.rs b/solidcore/crates/solidcore/src/offset/offset_executive/crossing_loops.rs index e0e69576aac..835e18d9d00 100644 --- a/solidcore/crates/solidcore/src/offset/offset_executive/crossing_loops.rs +++ b/solidcore/crates/solidcore/src/offset/offset_executive/crossing_loops.rs @@ -74,7 +74,6 @@ const OP: &str = "offset::offset_executive::crossing_loops::resolve_crossing_loo use crate::error::offset::{LoopCrossing, OffsetFailure, WallContact}; use crate::error::Failure; // `SM_ERR_ASSERT_FAILURE`. -use crate::error::SM_ERR_ASSERT_FAILURE; /// A stretch of a loop of an offset face between two of its crossings with other loops /// or the ends of its edge use, in the loop's direction (`sm_LoopStretch`). @@ -334,28 +333,35 @@ fn cut_at_crossings_refusing_touch( Ok(num_crossings) } -fn assert_failure() -> SolidError { - SolidError::Upstream { - operation: OP, - code: SM_ERR_ASSERT_FAILURE, - entity: None, - } +/// The UV trim curve of an edge use does not run over its edge's interval +/// (`SM_ERR_ASSERT_FAILURE`). +fn trim_interval_mismatch() -> SolidError { + SolidError::offset( + OP, + OffsetFailure::Inconsistent( + "an edge use's UV trim curve does not span its edge's interval", + ), + ) } +/// `value`, or `SM_ERR_NULL_POINTER` (upstream `NER`) for an entity or curve that is not +/// there. fn required(value: Option) -> Result { - value.ok_or_else(|| SolidError::null_pointer(OP)) + value.ok_or_else(|| SolidError::offset_missing(OP, "an entity or curve of the offset face")) } fn at(v: &[T], i: usize) -> Result<&T> { - v.get(i).ok_or_else(|| SolidError::null_pointer(OP)) + v.get(i) + .ok_or_else(|| SolidError::offset_missing(OP, "an entry of the crossings' own lists")) } fn at_mut(v: &mut [T], i: usize) -> Result<&mut T> { - v.get_mut(i).ok_or_else(|| SolidError::null_pointer(OP)) + v.get_mut(i) + .ok_or_else(|| SolidError::offset_missing(OP, "an entry of the crossings' own lists")) } fn index_i64(i: usize) -> Result { - i64::try_from(i).map_err(|_| SolidError::null_pointer(OP)) + i64::try_from(i).map_err(|_| SolidError::offset_missing(OP, "a node number for the edge use")) } /// The vertex node of edge use `k`: `-1 - k`. @@ -436,6 +442,11 @@ impl OffsetExecutive { let crate::error::Reason::Offset(refusal) = failure.reason else { return SolidError::Failed(failure); }; + // a failed routine's status (not a refusal) is returned as it is, as it was before + // the routine described it + if refusal.replaces_upstream_status() { + return SolidError::Failed(failure); + } let input_face = match self.faceuse_to_faces.firsts(f).as_slice() { [fu] => eu::faceuse_face(original, *fu).ok().flatten(), _ => None, @@ -513,7 +524,7 @@ impl OffsetExecutive { let uv = required(eu::uv_trim_curve(b, edgeuse)?.0.cloned())?; let e = edge_of(b, edgeuse)?; if !uv.natural_interval().are_equal(&b.edge(e)?.interval, 0.0) { - return Err(assert_failure()); + return Err(trim_interval_mismatch()); } loop_of.push(ll); edgeuses.push(edgeuse); diff --git a/solidcore/crates/solidcore/src/offset/offset_executive/p1.rs b/solidcore/crates/solidcore/src/offset/offset_executive/p1.rs index efdc29d0d0c..26fb471fce4 100644 --- a/solidcore/crates/solidcore/src/offset/offset_executive/p1.rs +++ b/solidcore/crates/solidcore/src/offset/offset_executive/p1.rs @@ -4713,14 +4713,13 @@ mod tests { let mut original = Brep::new(); let cache = BrepCache::new(crate::geom::a_object::BREP_TYPE).unwrap(); let keys = OriginalKeys::new(&original).unwrap(); - assert!(matches!( - solve_original_brep_point(&kernel, &mut original, &cache, &keys, Vec3::ZERO), - Err(SolidError::Upstream { - operation: "intersect::topology_solver::p1::TopologyObjects::brep_trees", - code: crate::error::SM_ERR_NULL_POINTER, - .. - }) - )); + let e = solve_original_brep_point(&kernel, &mut original, &cache, &keys, Vec3::ZERO) + .unwrap_err(); + assert_eq!( + e.operation(), + "intersect::topology_solver::p1::TopologyObjects::brep_trees" + ); + assert_eq!(e.upstream_status(), Some(crate::error::SM_ERR_NULL_POINTER)); } #[test]