Skip to main content

dive_eval/
error.rs

1//! Evaluation errors with TLC's error classes and message texts.
2//!
3//! An [`EvalError`] is a value, never a panic. It carries:
4//! - its [`ErrorClass`]: an evaluation error TLC also raises, an explicit
5//!   refusal of a feature dive does not implement exactly, a resource limit,
6//!   or an internal bug;
7//! - for evaluation errors, TLC's error code ([`Ec`]) and TLC's message text,
8//!   byte for byte. Messages that TLC builds from a semantic node's
9//!   `toString()` contain the node's location string, as TLC prints it;
10//! - the IR node it was raised at, when known.
11//!
12//! TLC reports an error in one of two shapes (`util.Assert`, `tlc2.output.MP`):
13//! a `GENERAL` (1000) error is printed as its bare message; any other code is
14//! printed as a nested `-tool` message with its code. [`EvalError::tool_text`]
15//! renders both, so the harness can compare dive's report with TLC's
16//! transcript.
17
18use std::fmt;
19
20use dive_ir::ExprId;
21use dive_value::{ErrorKind, ValueError};
22
23/// A TLC error code (`tlc2.output.EC`) that evaluation can raise.
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
25#[non_exhaustive]
26pub enum Ec {
27    /// `GENERAL` (1000): `Assert.fail` with a plain message.
28    General,
29    /// `TLC_EXPECTED_VALUE` (2215).
30    ExpectedValue,
31    /// `TLC_MODULE_APPLY_EMPTY_SEQ` (2184).
32    ApplyEmptySeq,
33    /// `TLC_MODULE_ONE_ARGUMENT_ERROR` (2283).
34    OneArgumentError,
35    /// `TLC_MODULE_ARGUMENT_ERROR` (2169).
36    ArgumentError,
37    /// `TLC_MODULE_ARGUMENT_ERROR_AN` (2266).
38    ArgumentErrorAn,
39    /// `TLC_MODULE_EVALUATING` (2182).
40    ModuleEvaluating,
41    /// `TLC_MODULE_ARGUMENT_NOT_IN_DOMAIN` (2183).
42    ArgumentNotInDomain,
43    /// `TLC_MODULE_COMPUTING_CARDINALITY` (2181).
44    ComputingCardinality,
45    /// `TLC_VALUE_ASSERT_FAILED` (2132).
46    AssertFailed,
47    /// `TLC_CONFIG_UNDEFINED_OR_NO_OPERATOR` (2280).
48    UndefinedOrNoOperator,
49    /// `TLC_ENCOUNTERED_FORMULA_IN_PREDICATE` (2261).
50    FormulaInPredicate,
51    /// `TLC_MODULE_DIVISION_BY_ZERO` (2179).
52    DivisionByZero,
53    /// `TLC_MODULE_OVERFLOW` (2178).
54    Overflow,
55    /// `TLC_MODULE_NULL_POWER_NULL` (2180).
56    NullPowerNull,
57    /// `TLC_INTEGER_TOO_BIG` (2265).
58    IntegerTooBig,
59    /// `TLC_MODULE_CHECK_MEMBER_OF` (2158).
60    CheckMemberOf,
61    /// `TLC_MODULE_COMPARE_VALUE` (2155).
62    CompareValue,
63    /// `TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE` (2154).
64    JavaMethodOverride,
65    /// `TLC_CANT_HANDLE_REAL_NUMBERS` (2244).
66    CantHandleReal,
67    /// `TLC_STATE_NOT_COMPLETELY_SPECIFIED_LIVE` (2148).
68    NotCompletelySpecifiedLive,
69    /// `TLC_ARGUMENT_MISMATCH` (2170).
70    ArgumentMismatch,
71    /// `TLC_MODULE_APPLYING_TO_WRONG_VALUE` (2176).
72    ApplyingToWrongValue,
73    /// `TLC_EXPECTED_EXPRESSION_IN_COMPUTING` (2247): the successor
74    /// generator met a non-boolean where it expected a predicate.
75    ExpectedExpressionInComputing,
76    /// `TLC_EXPECTED_EXPRESSION_IN_COMPUTING2` (2248): the same for a
77    /// function application.
78    ExpectedExpressionInComputing2,
79    /// `TLC_ENABLED_WRONG_FORMULA` (2260).
80    EnabledWrongFormula,
81    /// `TLC_MODULE_TLCGET_UNDEFINED` (2145).
82    TlcGetUndefined,
83    /// `TLC_MODULE_BAG_UNION1` (2177).
84    BagUnion1,
85}
86
87impl Ec {
88    /// The numeric code.
89    #[must_use]
90    pub const fn code(self) -> u32 {
91        match self {
92            Self::General => 1000,
93            Self::ExpectedValue => 2215,
94            Self::ApplyEmptySeq => 2184,
95            Self::OneArgumentError => 2283,
96            Self::ArgumentError => 2169,
97            Self::ArgumentErrorAn => 2266,
98            Self::ModuleEvaluating => 2182,
99            Self::ArgumentNotInDomain => 2183,
100            Self::ComputingCardinality => 2181,
101            Self::AssertFailed => 2132,
102            Self::UndefinedOrNoOperator => 2280,
103            Self::FormulaInPredicate => 2261,
104            Self::DivisionByZero => 2179,
105            Self::Overflow => 2178,
106            Self::NullPowerNull => 2180,
107            Self::IntegerTooBig => 2265,
108            Self::CheckMemberOf => 2158,
109            Self::CompareValue => 2155,
110            Self::JavaMethodOverride => 2154,
111            Self::CantHandleReal => 2244,
112            Self::NotCompletelySpecifiedLive => 2148,
113            Self::ArgumentMismatch => 2170,
114            Self::ApplyingToWrongValue => 2176,
115            Self::ExpectedExpressionInComputing => 2247,
116            Self::ExpectedExpressionInComputing2 => 2248,
117            Self::EnabledWrongFormula => 2260,
118            Self::TlcGetUndefined => 2145,
119            Self::BagUnion1 => 2177,
120        }
121    }
122
123    /// The `EC` constant's name.
124    #[must_use]
125    pub const fn name(self) -> &'static str {
126        match self {
127            Self::General => "GENERAL",
128            Self::ExpectedValue => "TLC_EXPECTED_VALUE",
129            Self::ApplyEmptySeq => "TLC_MODULE_APPLY_EMPTY_SEQ",
130            Self::OneArgumentError => "TLC_MODULE_ONE_ARGUMENT_ERROR",
131            Self::ArgumentError => "TLC_MODULE_ARGUMENT_ERROR",
132            Self::ArgumentErrorAn => "TLC_MODULE_ARGUMENT_ERROR_AN",
133            Self::ModuleEvaluating => "TLC_MODULE_EVALUATING",
134            Self::ArgumentNotInDomain => "TLC_MODULE_ARGUMENT_NOT_IN_DOMAIN",
135            Self::ComputingCardinality => "TLC_MODULE_COMPUTING_CARDINALITY",
136            Self::AssertFailed => "TLC_VALUE_ASSERT_FAILED",
137            Self::UndefinedOrNoOperator => "TLC_CONFIG_UNDEFINED_OR_NO_OPERATOR",
138            Self::FormulaInPredicate => "TLC_ENCOUNTERED_FORMULA_IN_PREDICATE",
139            Self::DivisionByZero => "TLC_MODULE_DIVISION_BY_ZERO",
140            Self::Overflow => "TLC_MODULE_OVERFLOW",
141            Self::NullPowerNull => "TLC_MODULE_NULL_POWER_NULL",
142            Self::IntegerTooBig => "TLC_INTEGER_TOO_BIG",
143            Self::CheckMemberOf => "TLC_MODULE_CHECK_MEMBER_OF",
144            Self::CompareValue => "TLC_MODULE_COMPARE_VALUE",
145            Self::JavaMethodOverride => "TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE",
146            Self::CantHandleReal => "TLC_CANT_HANDLE_REAL_NUMBERS",
147            Self::NotCompletelySpecifiedLive => "TLC_STATE_NOT_COMPLETELY_SPECIFIED_LIVE",
148            Self::ArgumentMismatch => "TLC_ARGUMENT_MISMATCH",
149            Self::ApplyingToWrongValue => "TLC_MODULE_APPLYING_TO_WRONG_VALUE",
150            Self::ExpectedExpressionInComputing => "TLC_EXPECTED_EXPRESSION_IN_COMPUTING",
151            Self::ExpectedExpressionInComputing2 => "TLC_EXPECTED_EXPRESSION_IN_COMPUTING2",
152            Self::EnabledWrongFormula => "TLC_ENABLED_WRONG_FORMULA",
153            Self::TlcGetUndefined => "TLC_MODULE_TLCGET_UNDEFINED",
154            Self::BagUnion1 => "TLC_MODULE_BAG_UNION1",
155        }
156    }
157
158    fn from_code(code: u32) -> Self {
159        match code {
160            2215 => Self::ExpectedValue,
161            2184 => Self::ApplyEmptySeq,
162            2283 => Self::OneArgumentError,
163            2169 => Self::ArgumentError,
164            2266 => Self::ArgumentErrorAn,
165            2182 => Self::ModuleEvaluating,
166            2183 => Self::ArgumentNotInDomain,
167            2181 => Self::ComputingCardinality,
168            2132 => Self::AssertFailed,
169            2280 => Self::UndefinedOrNoOperator,
170            2261 => Self::FormulaInPredicate,
171            2179 => Self::DivisionByZero,
172            2178 => Self::Overflow,
173            2180 => Self::NullPowerNull,
174            2265 => Self::IntegerTooBig,
175            2158 => Self::CheckMemberOf,
176            2155 => Self::CompareValue,
177            2154 => Self::JavaMethodOverride,
178            2244 => Self::CantHandleReal,
179            2148 => Self::NotCompletelySpecifiedLive,
180            2170 => Self::ArgumentMismatch,
181            2176 => Self::ApplyingToWrongValue,
182            2247 => Self::ExpectedExpressionInComputing,
183            2248 => Self::ExpectedExpressionInComputing2,
184            2260 => Self::EnabledWrongFormula,
185            2145 => Self::TlcGetUndefined,
186            2177 => Self::BagUnion1,
187            _ => Self::General,
188        }
189    }
190
191    /// The code for a numeric TLC code (`GENERAL` for one evaluation does
192    /// not raise).
193    pub(crate) fn from_tlc_code(code: u32) -> Self {
194        Self::from_code(code)
195    }
196}
197
198/// What kind of failure an [`EvalError`] is.
199#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
200pub enum ErrorClass {
201    /// A cooperative host interruption, classified by the driver, never a
202    /// specification failure or an arbitrary resource refusal.
203    Interrupted,
204    /// An evaluation error that TLC raises in the same situation, with TLC's
205    /// code and message.
206    Eval,
207    /// dive does not implement the construct exactly and refuses it. The
208    /// message names the feature (charter soundness rule: never approximate).
209    Unsupported,
210    /// A resource limit: evaluation depth, value nesting, or a dive-only size
211    /// limit. TLC's counterpart is a JVM `StackOverflowError` or
212    /// `OutOfMemoryError`, which the harness never treats as an oracle fact.
213    ResourceLimit,
214    /// An internal invariant was violated: a bug in dive.
215    Bug,
216}
217
218/// Actual evaluator exception constructor, retained across typed value transport.
219/// This is not evidence that diagnostic replay executed or reached this error.
220#[derive(Clone, Copy, Debug, PartialEq, Eq)]
221pub enum ExceptionKind {
222    /// A module's explicit TLC `EvalException`.
223    EvalException,
224    /// The evaluator's explicit tool/runtime exception.
225    ToolRuntime,
226}
227
228/// The value method that actually caught an evaluation failure.
229#[derive(Clone, Copy, Debug, PartialEq, Eq)]
230pub enum ValueMethod {
231    /// `FcnLambdaValue.toFcnRcd`, while computing the function's body.
232    FunctionMaterialize,
233    /// An actual `TupleValue.equals` catch.
234    TupleEquals,
235    /// An actual `RecordValue.equals` catch.
236    RecordEquals,
237}
238
239/// Receiver construction provenance retained by a value-method catch.
240/// Its fields can only be supplied by the evaluator's actual receiver.
241#[derive(Clone, Copy, Debug, PartialEq, Eq)]
242pub struct ValueMethodFailure {
243    method: ValueMethod,
244    constructor: ExprId,
245    source: Option<ExprId>,
246}
247
248impl ValueMethodFailure {
249    /// The method that caught the error.
250    #[must_use]
251    pub fn method(self) -> ValueMethod {
252        self.method
253    }
254
255    /// The receiver's constructor in this evaluator's IR.
256    #[must_use]
257    pub fn constructor(self) -> ExprId {
258        self.constructor
259    }
260
261    /// The source attached when the diagnostic tool constructed the receiver.
262    #[must_use]
263    pub fn source(self) -> Option<ExprId> {
264        self.source
265    }
266}
267
268#[derive(Clone, Debug, PartialEq, Eq)]
269struct Inner {
270    class: ErrorClass,
271    ec: Ec,
272    message: String,
273    origin: Option<ExprId>,
274    /// Whether TLC raises this as an `EvalException` (not wrapped by a Java
275    /// override) rather than as a `TLCRuntimeException`.
276    eval_exception: bool,
277    exception_kind: Option<ExceptionKind>,
278    /// Static-analysis binders are not runtime values. Keep this typed so an
279    /// unrelated refusal with the same text can never authorize lazy retry.
280    analysis_only: bool,
281    interruption: Option<crate::host::Interrupted>,
282    /// Original typed cause of a built-in Java-override wrapper. Rendered
283    /// message text, including apparent tool frames, grants no provenance.
284    override_cause: Option<(dive_ir::StdOp, Ec)>,
285    value_method: Option<ValueMethodFailure>,
286    receiver: Option<dive_value::ReceiverFailure>,
287}
288
289const ANALYSIS_ONLY: &str = "analysis-only binder has no runtime value";
290
291/// An evaluation error: its class, TLC's code and message, and the node it was
292/// raised at.
293#[derive(Clone, Debug, PartialEq, Eq)]
294pub struct EvalError(Box<Inner>);
295
296impl EvalError {
297    fn make(class: ErrorClass, ec: Ec, message: String, eval_exception: bool) -> Self {
298        Self(Box::new(Inner {
299            class,
300            ec,
301            message,
302            origin: None,
303            eval_exception,
304            exception_kind: None,
305            analysis_only: false,
306            interruption: None,
307            override_cause: None,
308            value_method: None,
309            receiver: None,
310        }))
311    }
312
313    /// A `GENERAL` evaluation error with TLC's message, as `Assert.fail(msg)`
314    /// raises it.
315    #[must_use]
316    pub fn general(message: impl Into<String>) -> Self {
317        let mut error = Self::make(ErrorClass::Eval, Ec::General, message.into(), false);
318        error.0.exception_kind = Some(ExceptionKind::ToolRuntime);
319        error
320    }
321
322    /// An evaluation error with a specific code, as `Assert.fail(EC, params)`
323    /// raises it (a `TLCRuntimeException`).
324    #[must_use]
325    pub fn coded(ec: Ec, message: impl Into<String>) -> Self {
326        let mut error = Self::make(ErrorClass::Eval, ec, message.into(), false);
327        error.0.exception_kind = Some(ExceptionKind::ToolRuntime);
328        error
329    }
330
331    /// An evaluation error raised by a module as an `EvalException`: a Java
332    /// override passes it through unwrapped.
333    #[must_use]
334    pub fn eval_exception(ec: Ec, message: impl Into<String>) -> Self {
335        let mut error = Self::make(ErrorClass::Eval, ec, message.into(), true);
336        error.0.exception_kind = Some(ExceptionKind::EvalException);
337        error
338    }
339
340    /// Observed constructor provenance. Unclassified value-method errors have
341    /// no such authority, even if their code or message resembles a tool error.
342    #[must_use]
343    pub fn exception_kind(&self) -> Option<ExceptionKind> {
344        self.0.exception_kind
345    }
346
347    /// The actual value-method catch, independent of numeric codes or text.
348    #[must_use]
349    pub fn value_method(&self) -> Option<ValueMethodFailure> {
350        self.0.value_method
351    }
352
353    pub(crate) fn qualify_receiver(mut self, owner: Option<&dive_value::ReceiverDomain>) -> Self {
354        let Some(failure) = self.0.receiver.take() else {
355            return self;
356        };
357        let Some((node, diagnostic)) = owner.and_then(|owner| owner.recover(failure)) else {
358            return self;
359        };
360        let method = match failure.method() {
361            dive_value::ReceiverMethod::TupleEquals => ValueMethod::TupleEquals,
362            dive_value::ReceiverMethod::RecordEquals => ValueMethod::RecordEquals,
363        };
364        self.in_value_method(method, ExprId(node), diagnostic.then_some(ExprId(node)))
365    }
366
367    pub(crate) fn in_value_method(
368        mut self,
369        method: ValueMethod,
370        constructor: ExprId,
371        source: Option<ExprId>,
372    ) -> Self {
373        // Unsupported operations, host stops and internal errors are never
374        // promoted to a TLC exception by a receiver's source location.
375        if self.is_eval()
376            && self
377                .0
378                .value_method
379                .is_none_or(|failure| failure.source.is_none())
380        {
381            self.0.value_method = Some(ValueMethodFailure {
382                method,
383                constructor,
384                source,
385            });
386        }
387        self
388    }
389
390    /// Constructs the actual native wrapper without recovering its cause from
391    /// presentation text. Only the evaluator's native dispatch uses this path.
392    pub(crate) fn wrapped_override(
393        operator: dive_ir::StdOp,
394        message: String,
395        cause: &Self,
396    ) -> Self {
397        let mut error = Self::coded(Ec::JavaMethodOverride, message);
398        error.0.override_cause = Some((operator, cause.ec()));
399        error
400    }
401
402    /// The original operator and error code retained by native wrapping.
403    ///
404    /// An error made with [`Self::coded`] has no such provenance, even when
405    /// its message contains the same method text and nested tool frames.
406    ///
407    /// ```
408    /// use dive_eval::{Ec, EvalError};
409    /// let error = EvalError::coded(Ec::JavaMethodOverride, "nested tool text");
410    /// assert_eq!(error.override_cause(), None);
411    /// ```
412    #[must_use]
413    pub fn override_cause(&self) -> Option<(dive_ir::StdOp, Ec)> {
414        self.0.override_cause
415    }
416
417    /// An explicit refusal: dive does not implement `feature` exactly.
418    #[must_use]
419    pub fn unsupported(feature: impl Into<String>) -> Self {
420        let feature = feature.into();
421        Self::make(ErrorClass::Unsupported, Ec::General, feature, false)
422    }
423
424    /// The refusal raised when evaluation forces a static-analysis binder,
425    /// which has no runtime value. See [`Self::is_analysis_only`].
426    #[must_use]
427    pub fn analysis_only() -> Self {
428        let mut error = Self::unsupported(ANALYSIS_ONLY);
429        error.0.analysis_only = true;
430        error
431    }
432
433    /// Whether this is the [`Self::analysis_only`] refusal: the evaluated
434    /// expression depends on a static-analysis binder. Planners use it to
435    /// keep such an argument lazy instead of freezing a value.
436    #[must_use]
437    pub fn is_analysis_only(&self) -> bool {
438        self.0.analysis_only
439    }
440
441    /// Cooperative host control flow. The driver retains the stop evidence.
442    #[must_use]
443    pub fn interrupted(interruption: crate::host::Interrupted) -> Self {
444        let mut error = Self::make(
445            ErrorClass::Interrupted,
446            Ec::General,
447            "host interrupted evaluation".into(),
448            false,
449        );
450        error.0.interruption = Some(interruption);
451        error
452    }
453
454    /// The typed host interruption, including its opaque driver identity.
455    #[must_use]
456    pub fn interruption(&self) -> Option<crate::host::Interrupted> {
457        self.0.interruption
458    }
459
460    /// A resource limit.
461    #[must_use]
462    pub fn resource_limit(message: impl Into<String>) -> Self {
463        Self::make(
464            ErrorClass::ResourceLimit,
465            Ec::General,
466            message.into(),
467            false,
468        )
469    }
470
471    /// An internal error (a bug in dive), with enough context to reproduce it.
472    #[must_use]
473    pub fn bug(message: impl Into<String>) -> Self {
474        Self::make(ErrorClass::Bug, Ec::General, message.into(), false)
475    }
476
477    /// Attaches the node the error was raised at, unless one is already set.
478    #[must_use]
479    pub fn at(mut self, origin: ExprId) -> Self {
480        if self.0.origin.is_none() {
481            self.0.origin = Some(origin);
482        }
483        self
484    }
485
486    /// The class.
487    #[must_use]
488    pub fn class(&self) -> ErrorClass {
489        self.0.class
490    }
491
492    /// TLC's error code (meaningful for [`ErrorClass::Eval`]).
493    #[must_use]
494    pub fn ec(&self) -> Ec {
495        self.0.ec
496    }
497
498    /// The message: TLC's text for an evaluation error, the feature for a
499    /// refusal.
500    #[must_use]
501    pub fn message(&self) -> &str {
502        &self.0.message
503    }
504
505    /// The node the error was raised at.
506    #[must_use]
507    pub fn origin(&self) -> Option<ExprId> {
508        self.0.origin
509    }
510
511    /// Whether this is an evaluation error TLC also raises.
512    #[must_use]
513    pub fn is_eval(&self) -> bool {
514        self.0.class == ErrorClass::Eval
515    }
516
517    /// Whether TLC raises this error as an `EvalException` rather than as a
518    /// `TLCRuntimeException` (`Assert.fail`). Some of TLC's messages depend
519    /// on it (`SpecProcessor.processConstantDefns`).
520    #[must_use]
521    pub fn is_eval_exception(&self) -> bool {
522        self.0.eval_exception
523    }
524
525    /// Whether a Java override would pass the error through unchanged
526    /// (TLC's `EvalException`), rather than wrapping it in
527    /// `TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE`.
528    #[must_use]
529    pub(crate) fn passes_override(&self) -> bool {
530        self.0.eval_exception || self.0.class != ErrorClass::Eval
531    }
532
533    /// The error as TLC prints it nested in another `-tool` message: the bare
534    /// message for `GENERAL`, or the message wrapped in its own
535    /// `@!@!@STARTMSG code:0 @!@!@` block.
536    #[must_use]
537    pub fn tool_text(&self) -> String {
538        match self.0.ec {
539            Ec::General => self.0.message.clone(),
540            ec => format!(
541                "@!@!@STARTMSG {}:0 @!@!@\n{}\n@!@!@ENDMSG {} @!@!@",
542                ec.code(),
543                self.0.message,
544                ec.code()
545            ),
546        }
547    }
548}
549
550impl fmt::Display for EvalError {
551    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
552        match self.0.class {
553            ErrorClass::Eval => write!(
554                f,
555                "{} ({}): {}",
556                self.0.ec.name(),
557                self.0.ec.code(),
558                self.0.message
559            ),
560            ErrorClass::Interrupted => write!(f, "evaluation interrupted by its host"),
561            ErrorClass::Unsupported => write!(f, "unsupported: {}", self.0.message),
562            ErrorClass::ResourceLimit => write!(f, "resource limit: {}", self.0.message),
563            ErrorClass::Bug => write!(f, "internal error: {}", self.0.message),
564        }
565    }
566}
567
568impl std::error::Error for EvalError {}
569
570#[derive(Debug)]
571struct Stashed {
572    receipt: Option<u32>,
573    error: EvalError,
574}
575
576thread_local! {
577    /// A deferred provider's error, recovered only by the matching transport.
578    static STASH: std::cell::RefCell<Option<Stashed>> = const { std::cell::RefCell::new(None) };
579}
580
581// Process uniqueness is necessary: a ValueError can cross a worker boundary.
582// Zero marks exhausted identity space, never a receipt. Interruption and actual
583// evaluator exceptions take this cold path; successful evaluation does not.
584static NEXT_RECEIPT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
585
586fn receipt(counter: &std::sync::atomic::AtomicU32) -> Option<u32> {
587    use std::sync::atomic::Ordering;
588    counter
589        .try_update(Ordering::Relaxed, Ordering::Relaxed, |next| {
590            (next != 0).then(|| next.checked_add(1).unwrap_or(0))
591        })
592        .ok()
593}
594
595/// Passes an evaluation error through `dive-value` (which only knows
596/// [`ValueError`]), so that [`EvalError::from`] can recover it intact.
597pub(crate) fn stash(error: EvalError) -> ValueError {
598    stash_with_counter(error, &NEXT_RECEIPT)
599}
600
601fn stash_with_counter(error: EvalError, counter: &std::sync::atomic::AtomicU32) -> ValueError {
602    let (error, receipt) = if matches!(error.class(), ErrorClass::Interrupted | ErrorClass::Eval) {
603        match receipt(counter) {
604            Some(receipt) => (error, Some(receipt)),
605            None => (
606                EvalError::bug("deferred evaluator receipt identity space exhausted"),
607                None,
608            ),
609        }
610    } else {
611        (error, None)
612    };
613    let kind = match (error.class(), error.ec(), receipt) {
614        (ErrorClass::Interrupted, _, Some(receipt)) => ErrorKind::Interrupted { receipt },
615        (_, _, Some(receipt)) => ErrorKind::DeferredError { receipt },
616        (ErrorClass::Eval, Ec::General, _) => ErrorKind::NotEnumerable,
617        (ErrorClass::Eval, _, _) => ErrorKind::Argument,
618        _ => ErrorKind::DiveLimit,
619    };
620    let value_error = ValueError::new(kind, error.message().to_owned());
621    STASH.with(|stash| *stash.borrow_mut() = Some(Stashed { receipt, error }));
622    value_error
623}
624
625impl From<ValueError> for EvalError {
626    fn from(error: ValueError) -> Self {
627        let receiver = error.receiver_failure();
628        let mut raised = Self::from_value_error(&error);
629        raised.0.receiver = receiver;
630        raised
631    }
632}
633
634impl EvalError {
635    fn from_value_error(error: &ValueError) -> Self {
636        if error.kind() == ErrorKind::Unsupported {
637            return Self::unsupported(error.message().to_owned());
638        }
639        if let ErrorKind::Interrupted { receipt } | ErrorKind::DeferredError { receipt } =
640            error.kind()
641        {
642            let interruption = matches!(error.kind(), ErrorKind::Interrupted { .. });
643            return STASH
644                .with(|stash| {
645                    let mut stash = stash.borrow_mut();
646                    if stash.as_ref().is_some_and(|pending| {
647                        pending.receipt == Some(receipt)
648                            && if interruption {
649                                pending.error.class() == ErrorClass::Interrupted
650                            } else {
651                                pending.error.class() == ErrorClass::Eval
652                            }
653                    }) {
654                        stash.take().map(|pending| pending.error)
655                    } else {
656                        None
657                    }
658                })
659                .unwrap_or_else(|| {
660                    Self::bug("value-layer error has no matching typed evaluator receipt")
661                });
662        }
663        let recovered = STASH.with(|stash| {
664            let mut stash = stash.borrow_mut();
665            // An ordinary value error cannot consume a pending interruption,
666            // even when its text happens to equal the provider's message.
667            if stash
668                .as_ref()
669                .is_some_and(|pending| pending.receipt.is_some())
670            {
671                return None;
672            }
673            stash.take().map(|pending| pending.error)
674        });
675        if let Some(stashed) = recovered
676            && stashed.message() == error.message()
677        {
678            return stashed;
679        }
680        match error.kind() {
681            ErrorKind::DiveLimit => Self::resource_limit(error.message().to_owned()),
682            kind => {
683                let ec = Ec::from_code(kind.tlc_code());
684                // Preserve the existing TLC module/override wrapping contract.
685                let eval_exception = ec != Ec::General
686                    && !error
687                        .message()
688                        .starts_with("Overflow when computing the number of elements");
689                let mut raised = Self::make(
690                    ErrorClass::Eval,
691                    ec,
692                    error.message().to_owned(),
693                    eval_exception,
694                );
695                // This typed integer operation is Naturals/Integers.Divide's
696                // actual EvalException, not a code/message-based projection
697                // of an arbitrary value method's replay behavior.
698                if kind == ErrorKind::DivisionByZero {
699                    raised.0.exception_kind = Some(ExceptionKind::EvalException);
700                }
701                raised
702            }
703        }
704    }
705}
706
707/// Result alias for evaluation.
708pub type Result<T, E = EvalError> = std::result::Result<T, E>;
709
710#[cfg(test)]
711#[allow(clippy::expect_used, reason = "typed interruption transport controls")]
712mod interruption_transport {
713    use super::*;
714    use crate::Interrupted;
715
716    #[test]
717    fn generic_exception_provenance_requires_typed_transport_not_message_resemblance() {
718        let actual = EvalError::general("same presentation");
719        assert_eq!(actual.exception_kind(), Some(ExceptionKind::ToolRuntime));
720        let transported = stash(actual.clone());
721        let ordinary = ValueError::new(ErrorKind::NotEnumerable, actual.message());
722        assert_eq!(EvalError::from(ordinary).exception_kind(), None);
723        assert_eq!(EvalError::from(transported), actual);
724        let module = EvalError::eval_exception(Ec::AssertFailed, "actual assertion");
725        assert_eq!(
726            EvalError::from(stash(module)).exception_kind(),
727            Some(ExceptionKind::EvalException)
728        );
729    }
730
731    #[test]
732    fn stale_receipts_and_ordinary_errors_do_not_consume_another_interruption() {
733        let stale = stash(EvalError::interrupted(Interrupted::new(10)));
734        let current = stash(EvalError::interrupted(Interrupted::new(20)));
735        assert_ne!(stale.kind(), current.kind());
736        assert_eq!(EvalError::from(stale).class(), ErrorClass::Bug);
737        let ordinary = ValueError::new(ErrorKind::Argument, "host interrupted evaluation");
738        assert_eq!(EvalError::from(ordinary).class(), ErrorClass::Eval);
739        let duplicate = current.clone();
740        let recovered = EvalError::from(current);
741        assert_eq!(recovered.interruption(), Some(Interrupted::new(20)));
742        assert_eq!(EvalError::from(duplicate).class(), ErrorClass::Bug);
743    }
744
745    #[test]
746    fn transport_to_another_thread_fails_closed_without_consuming_either_owner() {
747        let original = stash(EvalError::interrupted(Interrupted::new(10)));
748        let moved = original.clone();
749        std::thread::spawn(move || {
750            let local = stash(EvalError::interrupted(Interrupted::new(20)));
751            assert_ne!(moved.kind(), local.kind());
752            assert_eq!(EvalError::from(moved).class(), ErrorClass::Bug);
753            assert_eq!(
754                EvalError::from(local).interruption(),
755                Some(Interrupted::new(20))
756            );
757        })
758        .join()
759        .expect("worker");
760        assert_eq!(
761            EvalError::from(original).interruption(),
762            Some(Interrupted::new(10))
763        );
764    }
765
766    #[test]
767    fn receipt_ids_never_wrap_or_reuse_and_transport_layout_stays_small() {
768        let counter = std::sync::atomic::AtomicU32::new(u32::MAX - 1);
769        assert_eq!(receipt(&counter), Some(u32::MAX - 1));
770        assert_eq!(receipt(&counter), Some(u32::MAX));
771        assert_eq!(receipt(&counter), None);
772        assert_eq!(receipt(&counter), None);
773        let exhausted = stash_with_counter(EvalError::interrupted(Interrupted::new(10)), &counter);
774        assert_eq!(EvalError::from(exhausted).class(), ErrorClass::Bug);
775        #[cfg(target_pointer_width = "64")]
776        {
777            // Receiver diagnostics live in the rare boxed error payload;
778            // successful Result slots shrink rather than carrying those facts.
779            assert_eq!(std::mem::size_of::<ValueError>(), 16);
780            assert_eq!(std::mem::size_of::<ErrorKind>(), 8);
781        }
782    }
783}
784
785#[cfg(test)]
786mod native_cause_transport {
787    use super::*;
788    use dive_ir::StdOp;
789
790    fn wrapped() -> EvalError {
791        EvalError::wrapped_override(
792            StdOp::FiniteSetsCardinality,
793            "original wrapper text".to_owned(),
794            &EvalError::coded(Ec::Overflow, "original size overflow"),
795        )
796    }
797
798    #[test]
799    fn native_origin_survives_clone_and_real_receipt_but_not_rendered_forgery() {
800        let original = wrapped().at(ExprId(7));
801        assert_eq!(
802            original.clone().override_cause(),
803            Some((StdOp::FiniteSetsCardinality, Ec::Overflow))
804        );
805        let forged = EvalError::coded(Ec::JavaMethodOverride, original.message());
806        assert_eq!(forged.override_cause(), None);
807        let transported = stash(original.clone());
808        assert!(matches!(
809            transported.kind(),
810            ErrorKind::DeferredError { .. }
811        ));
812        let text_forgery = ValueError::new(ErrorKind::Argument, original.message());
813        assert_eq!(EvalError::from(text_forgery).override_cause(), None);
814        let duplicate = transported.clone();
815        assert_eq!(EvalError::from(transported), original);
816        assert_eq!(EvalError::from(duplicate).class(), ErrorClass::Bug);
817    }
818
819    #[test]
820    fn native_receipts_do_not_cross_threads_or_exhaust_into_a_verdict()
821    -> Result<(), Box<dyn std::error::Error>> {
822        let value = stash(wrapped());
823        let moved = value.clone();
824        std::thread::spawn(move || {
825            assert_eq!(EvalError::from(moved).class(), ErrorClass::Bug);
826        })
827        .join()
828        .map_err(|_| "worker failed")?;
829        assert!(EvalError::from(value).override_cause().is_some());
830        let exhausted = std::sync::atomic::AtomicU32::new(0);
831        assert_eq!(
832            EvalError::from(stash_with_counter(wrapped(), &exhausted)).class(),
833            ErrorClass::Bug
834        );
835        Ok(())
836    }
837}