Skip to main content

hpr/
error.rs

1//! The facade's error type.
2
3use hpr_aero::AeroError;
4use hpr_atmos::AtmosError;
5use hpr_core::CoreError;
6use hpr_design::checks::Severity;
7use hpr_design::{DesignError, Finding};
8use hpr_motor::MotorError;
9use hpr_sim::SimError;
10use thiserror::Error;
11
12/// Anything the builder API can refuse: its own checks, and every error of the crates it calls.
13#[derive(Debug, Error)]
14#[non_exhaustive]
15pub enum Error {
16    /// A number outside its domain, such as a negative length or a NaN, found as it was given.
17    #[error("{what} is {value}, but it must be {allowed}")]
18    Domain {
19        /// What the number is.
20        what: &'static str,
21        /// The number.
22        value: f64,
23        /// What it must be, as the message says it: `"finite and above 0"`.
24        allowed: &'static str,
25    },
26    /// Parts added in an order the rocket can't be built in, such as fins before any body tube.
27    #[error(transparent)]
28    Order(Order),
29    /// A material id that isn't built in; [`hpr_design::materials`] lists them.
30    #[error("no built-in material `{0}` (`hpr_design::materials` lists them)")]
31    UnknownMaterial(String),
32    /// No motor in the bundled catalog matches the name.
33    #[error("no motor in the bundled catalog matches `{0}`")]
34    NoSuchMotor(String),
35    /// The one motor the name matches is in the bundled catalog with no curve file that reads,
36    /// so it can't fly ([ADR-302][adr-302] ยง3); give a `.eng` or `.rse` file of it instead.
37    ///
38    /// [adr-302]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0302-every-motor-by-name.md
39    #[error("{0} is in the bundled catalog, but no curve file of it is bundled")]
40    NoCurve(String),
41    /// Several different motors match the name, with or without a curve. Each is listed by a
42    /// name that finds it alone: its designation, or its maker's short name and its designation
43    /// where makers share it (`Estes C6`).
44    #[error("`{name}` matches several motors: {}", candidates.join(", "))]
45    AmbiguousMotor {
46        /// The name asked for.
47        name: String,
48        /// The motors it matches.
49        candidates: Vec<String>,
50    },
51    /// A motor with an empty designation, which the design would take as a duplicate id.
52    #[error("a motor needs a designation")]
53    EmptyDesignation,
54    /// A motor file holds no motor, or more than one where one was expected.
55    #[error("the motor file holds {0} motors, not one")]
56    MotorCount(usize),
57    /// A flight of a rocket with no motor: give it one with [`crate::Rocket::set_motor`].
58    #[error("the rocket has no motor; give it one with `Rocket::set_motor`")]
59    NoMotor,
60    /// A configuration id the design doesn't hold.
61    #[error("the design has no configuration `{0}`")]
62    NoSuchConfiguration(String),
63    /// The design's checks ([`hpr_design::checks`]) found errors: every finding, errors and
64    /// warnings, in the checks' order.
65    #[error(
66        "the design's checks found {} finding(s), errors among them; the first error is {}",
67        .0.len(),
68        first_error(.0)
69    )]
70    DesignChecks(Vec<Finding>),
71    /// A catalog part the builder can't make into the part asked for.
72    #[error("catalog part {part}: {problem}")]
73    Catalog {
74        /// The part: its maker and part number, and its file.
75        part: String,
76        /// What is wrong with it.
77        problem: CatalogProblem,
78    },
79    /// From the design: its tree, parts and mass properties.
80    #[error(transparent)]
81    Design(#[from] DesignError),
82    /// From the motor models and motor files.
83    #[error(transparent)]
84    Motor(#[from] MotorError),
85    /// From the flight simulation.
86    #[error(transparent)]
87    Sim(#[from] SimError),
88    /// From the aerodynamic model.
89    #[error(transparent)]
90    Aero(#[from] AeroError),
91    /// From the atmosphere and wind models.
92    #[error(transparent)]
93    Atmos(#[from] AtmosError),
94    /// From the geodesy: a launch site that isn't on the Earth.
95    #[error(transparent)]
96    Core(#[from] CoreError),
97}
98
99/// What is out of order when a part can't go where it was added.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
101#[non_exhaustive]
102pub enum Order {
103    /// A nose added after another body part: the nose goes first.
104    #[error("the nose goes first, before any other body part")]
105    NoseNotFirst,
106    /// A transition with no body part before it to start from.
107    #[error("a transition needs a body part before it")]
108    NothingBeforeTransition,
109    /// Fins, a motor tube or a mass with no body tube to go on.
110    #[error("fins, a motor tube and masses go on a body tube: add one first")]
111    NoTube,
112    /// A second motor tube: a built rocket has one.
113    #[error("the rocket has a motor tube already")]
114    SecondMotorTube,
115    /// A motor with no motor tube to go in.
116    #[error("a motor needs a motor tube to go in")]
117    NoMotorTube,
118    /// A fitting holding a part that isn't one (one read from a file): a fitting is a coupler,
119    /// a centering ring, a bulkhead, a launch lug, a parachute or a streamer.
120    #[error("a fitting is a coupler, centering ring, bulkhead, launch lug, parachute or streamer")]
121    NotAFitting,
122    /// A part added to a rocket read from a design, which the builder doesn't change.
123    #[error("parts can't be added to a rocket read from a design")]
124    ReadFromDesign,
125}
126
127/// Why a catalog part ([`hpr_io::orc::Part`]) can't be made into a builder part.
128#[derive(Debug, Clone, PartialEq, Eq, Error)]
129#[non_exhaustive]
130pub enum CatalogProblem {
131    /// A part of a kind the builder's part isn't, such as a body tube given to
132    /// `Nose::from_catalog`.
133    #[error("it is a {found}, which `{builder}` doesn't make")]
134    Kind {
135        /// The part's kind.
136        found: &'static str,
137        /// The function it was given to.
138        builder: &'static str,
139    },
140    /// A material its file names but doesn't define, so it has no density.
141    #[error("its file doesn't define its material `{0}`")]
142    UndefinedMaterial(String),
143    /// A nose cone or transition neither filled nor given a wall thickness.
144    #[error("it is neither filled nor given a wall thickness")]
145    NoWall,
146    /// A nose cone's or transition's shape the builder doesn't know.
147    #[error("its shape is one the builder doesn't know")]
148    Shape,
149    /// A part that states its mass but whose sizes give it no volume to hold it, so no density
150    /// gives it that mass.
151    #[error("it states a mass, but its sizes give it no volume to hold it")]
152    NoVolume,
153}
154
155/// `value` if it is finite and positive, [`Error::Domain`] otherwise.
156pub(crate) fn positive(what: &'static str, value: f64) -> Result<f64, Error> {
157    if value.is_finite() && value > 0.0 {
158        Ok(value)
159    } else {
160        Err(Error::Domain {
161            what,
162            value,
163            allowed: "finite and above 0",
164        })
165    }
166}
167
168/// `value` if it is finite and not negative, [`Error::Domain`] otherwise.
169pub(crate) fn non_negative(what: &'static str, value: f64) -> Result<f64, Error> {
170    if value.is_finite() && value >= 0.0 {
171        Ok(value)
172    } else {
173        Err(Error::Domain {
174            what,
175            value,
176            allowed: "finite and not negative",
177        })
178    }
179}
180
181/// `value` if it is finite, [`Error::Domain`] otherwise.
182pub(crate) fn finite(what: &'static str, value: f64) -> Result<f64, Error> {
183    if value.is_finite() {
184        Ok(value)
185    } else {
186        Err(Error::Domain {
187            what,
188            value,
189            allowed: "finite",
190        })
191    }
192}
193
194/// The first finding that is an error, for [`Error::DesignChecks`]'s message.
195fn first_error(findings: &[Finding]) -> String {
196    findings
197        .iter()
198        .find(|finding| finding.severity() == Severity::Error)
199        .map_or_else(|| "missing".to_owned(), |finding| format!("{finding:?}"))
200}