Skip to main content

dive_value/
error.rs

1//! Value-layer errors with TLC's error classes and message texts.
2
3use std::fmt;
4
5/// The class of a value-layer error.
6///
7/// Specification error classes map to TLC's error codes (`tlc2.output.EC`), see
8/// [`ErrorKind::tlc_code`]. [`ErrorKind::Interrupted`] is instead typed host
9/// control flow; its numeric code accessor is not a TLC-error certificate.
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
11#[non_exhaustive]
12pub enum ErrorKind {
13    /// A mathematical operation whose exact semantics are not implemented.
14    /// The numeric code accessor is not a TLC error certificate for this kind.
15    Unsupported,
16    /// Typed cooperative host interruption transported through a deferred
17    /// evaluator provider. This is not a TLC error or a resource refusal.
18    Interrupted {
19        /// Process-unique, nonreused identity of the evaluator's pending
20        /// deferred-provider receipt. It is not a TLC error code.
21        receipt: u32,
22    },
23    /// An evaluator error with sealed native-cause provenance. Only its
24    /// original evaluator can recover the error; message text is insufficient.
25    DeferredError {
26        /// Process-unique, nonreused pending evaluator receipt.
27        receipt: u32,
28    },
29    /// Two values that TLC refuses to compare or to test for equality
30    /// (`Assert.fail` in a `compareTo`/`equals` method, `EC.GENERAL`).
31    Incomparable,
32    /// A membership test that TLC refuses (`member` methods, `EC.GENERAL`).
33    Membership,
34    /// A membership test in an infinite built-in set refused by its module
35    /// (`EC.TLC_MODULE_CHECK_MEMBER_OF`).
36    ModuleMembership,
37    /// A comparison refused by a built-in infinite set (`EC.TLC_MODULE_COMPARE_VALUE`).
38    ModuleCompare,
39    /// 32-bit integer overflow (`EC.TLC_MODULE_OVERFLOW`).
40    Overflow,
41    /// An integer literal above 2^31 - 1 (`EC.TLC_INTEGER_TOO_BIG`).
42    IntegerTooBig,
43    /// `\div` by zero (`EC.TLC_MODULE_DIVISION_BY_ZERO`).
44    DivisionByZero,
45    /// `0^0` (`EC.TLC_MODULE_NULL_POWER_NULL`).
46    NullPowerNull,
47    /// An argument of the wrong kind or range (`EC.TLC_MODULE_ARGUMENT_ERROR`).
48    Argument,
49    /// A set too large to be represented or enumerated (`EC.GENERAL`).
50    TooLarge,
51    /// A set that cannot be enumerated because it is infinite or symbolic (`EC.GENERAL`).
52    NotEnumerable,
53    /// A duplicate in a function domain or a record's fields (`EC.GENERAL`).
54    Duplicate,
55    /// A value that cannot be fingerprinted, such as `Nat` (`EC.GENERAL`).
56    NotFingerprintable,
57    /// A value that cannot be converted to TLC's JSON form.
58    Json,
59    /// Bytes that are not a valid value encoding ([`crate::codec`]). This is an
60    /// internal error, never a property of the spec: dive only decodes what it encoded.
61    Codec,
62    /// A dive-only limit, such as a big-integer result too large to allocate.
63    /// TLC has no counterpart (it would have overflowed long before).
64    DiveLimit,
65}
66
67impl ErrorKind {
68    /// The TLC `EC` code number TLC reports for this class.
69    #[must_use]
70    pub const fn tlc_code(self) -> u32 {
71        match self {
72            Self::ModuleMembership => 2158,
73            Self::ModuleCompare => 2155,
74            Self::Overflow => 2178,
75            Self::IntegerTooBig => 2265,
76            Self::DivisionByZero => 2179,
77            Self::NullPowerNull => 2180,
78            Self::Argument => 2169,
79            Self::Interrupted { .. }
80            | Self::Unsupported
81            | Self::DeferredError { .. }
82            | Self::Incomparable
83            | Self::Membership
84            | Self::TooLarge
85            | Self::NotEnumerable
86            | Self::Duplicate
87            | Self::NotFingerprintable
88            | Self::Json
89            | Self::Codec
90            | Self::DiveLimit => 1000,
91        }
92    }
93
94    /// The TLC `EC` constant name for [`ErrorKind::tlc_code`].
95    #[must_use]
96    pub const fn tlc_name(self) -> &'static str {
97        match self {
98            Self::ModuleMembership => "TLC_MODULE_CHECK_MEMBER_OF",
99            Self::ModuleCompare => "TLC_MODULE_COMPARE_VALUE",
100            Self::Overflow => "TLC_MODULE_OVERFLOW",
101            Self::IntegerTooBig => "TLC_INTEGER_TOO_BIG",
102            Self::DivisionByZero => "TLC_MODULE_DIVISION_BY_ZERO",
103            Self::NullPowerNull => "TLC_MODULE_NULL_POWER_NULL",
104            Self::Argument => "TLC_MODULE_ARGUMENT_ERROR",
105            _ => "GENERAL",
106        }
107    }
108
109    /// The stable dive error code (`DIVE-Vnnnn`) for this class.
110    #[must_use]
111    pub const fn dive_code(self) -> &'static str {
112        match self {
113            Self::Interrupted { .. } => "DIVE-V0031",
114            Self::DeferredError { .. } => "DIVE-V0032",
115            Self::Unsupported => "DIVE-V0033",
116            Self::Incomparable => "DIVE-V0001",
117            Self::Membership => "DIVE-V0002",
118            Self::ModuleMembership => "DIVE-V0003",
119            Self::ModuleCompare => "DIVE-V0004",
120            Self::Overflow => "DIVE-V0010",
121            Self::IntegerTooBig => "DIVE-V0011",
122            Self::DivisionByZero => "DIVE-V0012",
123            Self::NullPowerNull => "DIVE-V0013",
124            Self::Argument => "DIVE-V0014",
125            Self::TooLarge => "DIVE-V0020",
126            Self::NotEnumerable => "DIVE-V0021",
127            Self::Duplicate => "DIVE-V0022",
128            Self::NotFingerprintable => "DIVE-V0023",
129            Self::Json => "DIVE-V0024",
130            Self::DiveLimit => "DIVE-V0030",
131            Self::Codec => "DIVE-V0040",
132        }
133    }
134}
135
136/// A value-layer error: a class plus the exact message TLC prints for it.
137///
138/// The message is the text TLC puts in the error report body. For example, comparing
139/// `1` with `"a"` while normalizing a set gives
140/// `Attempted to compare integer 1 with non-integer:\n"a"`.
141#[derive(Clone, Debug, PartialEq, Eq)]
142pub struct ValueError {
143    kind: ErrorKind,
144    // Keep ordinary Result slots small. This allocation occurs only when an
145    // actual error is created, never for a successful value or comparison.
146    details: Box<Details>,
147}
148
149#[derive(Clone, Debug, PartialEq, Eq)]
150struct Details {
151    message: String,
152    receiver: Option<crate::ReceiverFailure>,
153}
154
155impl ValueError {
156    /// Creates an error of the given class with the given message.
157    #[must_use]
158    pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
159        Self {
160            kind,
161            details: Box::new(Details {
162                message: message.into(),
163                receiver: None,
164            }),
165        }
166    }
167
168    /// Actual receiver-method provenance; arbitrary messages carry none.
169    #[must_use]
170    pub fn receiver_failure(&self) -> Option<crate::ReceiverFailure> {
171        self.details.receiver
172    }
173
174    pub(crate) fn caught_by(mut self, function: &crate::Fcn) -> Self {
175        if !matches!(
176            self.kind,
177            ErrorKind::Interrupted { .. } | ErrorKind::DiveLimit | ErrorKind::Codec
178        ) && self
179            .details
180            .receiver
181            .is_none_or(|failure| !failure.sourced())
182            && let Some(failure) = crate::ReceiverFailure::equals(function)
183        {
184            self.details.receiver = Some(failure);
185        }
186        self
187    }
188
189    /// The error class.
190    #[must_use]
191    pub const fn kind(&self) -> ErrorKind {
192        self.kind
193    }
194
195    /// The TLC-format message.
196    #[must_use]
197    pub fn message(&self) -> &str {
198        &self.details.message
199    }
200}
201
202impl fmt::Display for ValueError {
203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204        write!(f, "{}: {}", self.kind.dive_code(), self.details.message)
205    }
206}
207
208impl std::error::Error for ValueError {}
209
210/// Result alias for value-layer operations.
211pub type Result<T, E = ValueError> = std::result::Result<T, E>;