Skip to main content

elly_core/eval/
error.rs

1//! Errors at run time: [`Raised`], a value unwinding through the evaluator's
2//! single error channel, and what a raised error leaves behind as it unwinds.
3//!
4//! ## Unwinding
5//!
6//! A raised error leaves behind the calls it unwound through, and for a
7//! refutation, what refuted and the value it refuted.
8//!
9//! The evaluator recurses in Rust, so the calls are recorded on the way out,
10//! on the error path alone, in the realm rather than in [`Raised`], which
11//! keeps its size. What refuted which value is recorded only once a
12//! refutation escapes the parameter, binding, case or `__match` that refuted:
13//! one refuted on the way to an arm that matches records nothing. A host
14//! takes both with [`Ctx::take_trace`]. They hold ids; names and spans are
15//! found when the trace is taken, and the source text when it is reported. See `docs/done/2026-10-11_elly-ctx-chunks.md`, step 4c.
16
17use core::cell::{Cell, RefCell};
18
19use alloc::borrow::Cow;
20use alloc::boxed::Box;
21use alloc::collections::VecDeque;
22use alloc::format;
23use alloc::string::String;
24use alloc::vec::Vec;
25
26use crate::code::{ChunkId, Node, NodeId, PatId, StaticChunk};
27use crate::source::{report, CtxSpan, DocSource, Location};
28use crate::sym::Sym;
29use crate::{Ctx, Text, Value};
30
31// ---------------------------------------------------------------------------
32// Raised errors
33// ---------------------------------------------------------------------------
34
35/// Value unwinding through the single error channel (see `docs/elly-spec.md`).
36///
37/// - `Error(v)`: Genuine failure (host abort or `__Err.raise v`). Propagates
38///   past `__match`.
39/// - `NoMatch(v)`: Pattern refutation from `match_pattern`. Only `__match` catches
40///   this, falling through to its fallback. Other boundaries treat it as `Error(v)`,
41///   surfacing the original error `v`.
42///
43/// - `Signal(s)`: An iterator loop's control flow (`it.__break`, …), caught by
44///   the loop that issued `it`. Every other boundary passes it on, `__Err.catch`
45///   included; one that escapes every loop reads as `.not_in_loop`.
46///
47/// Kinds are distinguished by construction; user code can only raise `Error`,
48/// preventing forged `NoMatch` signals.
49#[derive(Debug, Clone)]
50pub enum Raised {
51    /// A genuine error, propagated by `__match`.
52    Error(Value),
53    /// A pattern refutation carrying the original error it decays to when uncaught.
54    NoMatch(Value),
55    /// A step's outcome, unwinding to its loop (see `eval/iter.rs`).
56    Signal(Signal),
57}
58
59/// A loop's control flow, raised by a signal method on a step's cursor and
60/// caught by the loop of `loop_id`, the identity that cursor carries. The two
61/// carrying a value box it, so a signal does not widen [`Raised`].
62#[derive(Debug, Clone)]
63pub enum Signal {
64    /// `it.__continue`: the step produces nothing.
65    Continue(u64),
66    /// `it.__break`: the step produces nothing and the loop ends.
67    Break(u64),
68    /// `it.__return v`: the step ends with `v`.
69    Return(Box<(u64, Value)>),
70    /// `it.__yield xs`: the step produces each element of `xs`, an iterator.
71    Yield(Box<(u64, Value)>),
72}
73
74impl Signal {
75    /// The identity of the loop this signal is for.
76    pub(crate) fn loop_id(&self) -> u64 {
77        match self {
78            Signal::Continue(id) | Signal::Break(id) => *id,
79            Signal::Return(b) | Signal::Yield(b) => b.0,
80        }
81    }
82}
83
84impl Raised {
85    /// A refutation carrying `tag` (stored without its dot) as the *original* error it stands for.
86    /// `__match` catches it and falls through; uncaught, it decays to `.tag`.
87    pub(crate) fn no_match(tag: Sym) -> Raised {
88        Raised::NoMatch(Value::Symbol(tag))
89    }
90
91    /// Raise one of the host-failure symbol tags (stored without its leading dot) as
92    /// a genuine `Error`. The tag is one of the fixed symbols every realm shares.
93    pub(crate) fn symbol(tag: Sym) -> Raised {
94        Raised::Error(Value::Symbol(tag))
95    }
96
97    /// Returns the carried payload regardless of the `Raised` kind. A signal
98    /// reads as `.not_in_loop`: this is where one that escaped every loop ends.
99    pub fn value(&self) -> Cow<'_, Value> {
100        match self {
101            Raised::Error(v) | Raised::NoMatch(v) => Cow::Borrowed(v),
102            Raised::Signal(_) => Cow::Owned(Value::Symbol(Sym::NOT_IN_LOOP)),
103        }
104    }
105
106    /// Consumes the `Raised` value into its payload, as [`value`](Self::value)
107    /// reads it.
108    pub fn into_value(self) -> Value {
109        match self {
110            Raised::Error(v) | Raised::NoMatch(v) => v,
111            Raised::Signal(_) => Value::Symbol(Sym::NOT_IN_LOOP),
112        }
113    }
114}
115
116// ---------------------------------------------------------------------------
117// Unwinding
118// ---------------------------------------------------------------------------
119
120/// How many frames a trace keeps: half from the failing end, half from the
121/// outermost. The frames between are counted.
122const FRAMES_CAP: usize = 128;
123
124/// The realm's unwinding record, empty outside an unwinding error.
125#[derive(Default)]
126pub(crate) struct Unwind {
127    /// Whether `state` holds anything.
128    dirty: Cell<bool>,
129    state: RefCell<State>,
130}
131
132#[derive(Default)]
133struct State {
134    frames: Frames,
135    /// What refuted which value, once a refutation escaped the pattern, case
136    /// or `__match` that refuted.
137    refuted: Option<Refuted>,
138}
139
140/// The calls unwound through, the failing one first; repeats of a call are
141/// counted in its frame.
142#[derive(Default)]
143struct Frames {
144    head: Vec<Frame>,
145    tail: VecDeque<Frame>,
146    /// How many frames were dropped between `head` and `tail`.
147    omitted: u32,
148}
149
150/// An application node an error unwound through, and how many more times
151/// in a row.
152#[derive(Clone, Copy)]
153struct Frame {
154    chunk: ChunkId,
155    call: NodeId,
156    repeat: u32,
157}
158
159/// What refuted a value, in chunk `chunk`, and the value.
160struct Refuted {
161    chunk: ChunkId,
162    site: Site,
163    value: Value,
164}
165
166/// What refuted: the outermost pattern a refutation escaped, a case none of
167/// whose arms matched, by its subject, or a `__match` none of whose clauses
168/// did.
169#[derive(Clone, Copy)]
170enum Site {
171    Pat(PatId),
172    Case(NodeId),
173    Match,
174}
175
176impl Frames {
177    fn push(&mut self, chunk: ChunkId, call: NodeId) {
178        let prev = match self.tail.back_mut() {
179            Some(prev) => Some(prev),
180            None => self.head.last_mut(),
181        };
182        if let Some(prev) = prev {
183            if prev.chunk == chunk && prev.call == call {
184                prev.repeat += 1;
185                return;
186            }
187        }
188        let frame = Frame {
189            chunk,
190            call,
191            repeat: 0,
192        };
193        if self.head.len() < FRAMES_CAP / 2 {
194            self.head.push(frame);
195            return;
196        }
197        if self.tail.len() == FRAMES_CAP / 2 {
198            let dropped = self.tail.pop_front().expect("the tail is full");
199            self.omitted = self
200                .omitted
201                .saturating_add(dropped.repeat.saturating_add(1));
202        }
203        self.tail.push_back(frame);
204    }
205
206    fn clear(&mut self) {
207        if !self.head.is_empty() {
208            self.head.clear();
209            self.tail.clear();
210            self.omitted = 0;
211        }
212    }
213}
214
215// ---------------------------------------------------------------------------
216// Recording, from the evaluator
217// ---------------------------------------------------------------------------
218
219impl Ctx {
220    /// `raised` is unwinding through application node `call` of chunk `at`,
221    /// unless `call` is [`NodeId::NONE`]. A signal records nothing: a loop's
222    /// `__break` is a normal exit, not a failure to explain.
223    #[cold]
224    #[inline(never)]
225    pub(crate) fn unwound(&self, raised: &Raised, at: ChunkId, call: NodeId) {
226        if call == NodeId::NONE || matches!(raised, Raised::Signal(_)) {
227            return;
228        }
229        self.unwind.dirty.set(true);
230        self.unwind.state.borrow_mut().frames.push(at, call);
231    }
232
233    /// `raised` escaped pattern `pat` of chunk `at`, which it refuted
234    /// matching `value`: if it is a refutation, and none escaped deeper, it
235    /// is what refuted.
236    #[cold]
237    #[inline(never)]
238    pub(crate) fn escaped(&self, raised: Raised, at: ChunkId, pat: PatId, value: &Value) -> Raised {
239        if let Raised::NoMatch(_) = raised {
240            let mut state = self.unwind.state.borrow_mut();
241            if state.refuted.is_none() {
242                state.refuted = Some(Refuted {
243                    chunk: at,
244                    site: Site::Pat(pat),
245                    value: value.clone(),
246                });
247                self.unwind.dirty.set(true);
248            }
249        }
250        raised
251    }
252
253    /// No arm of the case with subject node `subject` of chunk `at` matched
254    /// `value`.
255    #[cold]
256    #[inline(never)]
257    pub(crate) fn no_arm_matched(&self, at: ChunkId, subject: NodeId, value: &Value) -> Raised {
258        self.refuted(at, Site::Case(subject), value)
259    }
260
261    /// No clause of a `__match` matched `value`.
262    #[cold]
263    #[inline(never)]
264    pub(crate) fn no_clause_matched(&self, value: &Value) -> Raised {
265        self.refuted(ChunkId::NONE, Site::Match, value)
266    }
267
268    fn refuted(&self, chunk: ChunkId, site: Site, value: &Value) -> Raised {
269        self.unwind.state.borrow_mut().refuted = Some(Refuted {
270            chunk,
271            site,
272            value: value.clone(),
273        });
274        self.unwind.dirty.set(true);
275        Raised::no_match(Sym::NO_MATCH)
276    }
277
278    /// An error was caught, by a catch or by a case arm, `__match` clause or
279    /// or-pattern branch that refuted: what it left is dropped.
280    #[inline(never)]
281    pub(crate) fn caught(&self) {
282        if self.unwind.dirty.get() {
283            self.clear_state();
284        }
285    }
286
287    #[cold]
288    #[inline(never)]
289    fn clear_state(&self) {
290        self.unwind.dirty.set(false);
291        let mut state = self.unwind.state.borrow_mut();
292        state.frames.clear();
293        state.refuted = None;
294    }
295
296    /// Forgets what an error left, as an evaluation starts.
297    pub(crate) fn clear_unwind(&self) {
298        self.caught();
299    }
300}
301
302// ---------------------------------------------------------------------------
303// The trace, for a host
304// ---------------------------------------------------------------------------
305
306/// What an error unwound through on its way to the top: see
307/// [`Ctx::take_trace`].
308#[derive(Debug, Clone, Default, PartialEq)]
309pub struct Trace {
310    /// The calls it unwound through, the failing call first.
311    pub frames: Vec<TraceFrame>,
312    /// How many frames were dropped, and where among `frames` they were, if
313    /// the trace was too long to keep.
314    pub omitted: Option<(usize, u32)>,
315    /// For a `.no_match`, what refuted which value.
316    pub refuted: Option<Refutation>,
317}
318
319/// A call an error unwound through.
320#[derive(Debug, Clone, PartialEq, Eq)]
321pub struct TraceFrame {
322    /// The call's span.
323    pub call: Option<CtxSpan>,
324    /// How many more times in a row the same call was unwound through.
325    pub repeat: u32,
326    /// The function the call is in.
327    pub within: FrameName,
328}
329
330/// The function a call is in.
331#[derive(Debug, Clone, PartialEq, Eq)]
332pub enum FrameName {
333    /// A member, a function or a value of a module or a `recur` group.
334    Member(Text),
335    /// A module's `__main`, or the function it is.
336    Main,
337    /// A lambda that no member names, with its span.
338    Closure(Option<CtxSpan>),
339    /// An expression evaluated on its own.
340    Top,
341}
342
343/// How [`Ctx::report_raised`] shows each place in a trace.
344#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
345pub enum ReportStyle {
346    /// At its line, with the span marked, as [`report`](crate::source::report)
347    /// shows it.
348    #[default]
349    Snippets,
350    /// On one line, `name:line:column: message`, indented by two spaces.
351    Lines,
352}
353
354/// A document as a host shows it: its name, and its text if the host has
355/// it (see [`Ctx::report_raised`]).
356pub type DocText = (String, Option<String>);
357
358/// What refuted a value: the parameter or binding pattern a refutation
359/// escaped, with its whole value, however deep inside it the refuting
360/// pattern was; or a case or a `__match` none of whose arms matched.
361#[derive(Debug, Clone, PartialEq)]
362pub struct Refutation {
363    pub by: RefutedBy,
364    /// The pattern's span, or the case's subject's. A `__match` has none:
365    /// it is the call the trace starts at.
366    pub at: Option<CtxSpan>,
367    /// The value refuted.
368    pub value: Value,
369}
370
371/// What a [`Refutation`] is by.
372#[derive(Debug, Clone, Copy, PartialEq, Eq)]
373pub enum RefutedBy {
374    Pattern,
375    Case,
376    Match,
377}
378
379impl Ctx {
380    /// The trace of `raised`, which reached the top of an evaluation of this
381    /// realm, taken out of the realm, and for a `.no_match`, what refuted
382    /// which value.
383    pub fn take_trace(&self, raised: &Raised) -> Trace {
384        self.unwind.dirty.set(false);
385        let State { frames, refuted } = core::mem::take(&mut *self.unwind.state.borrow_mut());
386        let frame = |f: &Frame| TraceFrame {
387            call: self.node_span(f.chunk, f.call),
388            repeat: f.repeat,
389            within: self.frame_name(f.chunk, f.call),
390        };
391        let mut trace = Trace {
392            frames: frames.head.iter().map(frame).collect(),
393            ..Trace::default()
394        };
395        if frames.omitted > 0 {
396            trace.omitted = Some((trace.frames.len(), frames.omitted));
397        }
398        trace.frames.extend(frames.tail.iter().map(frame));
399        if let (Raised::NoMatch(_), Some(r)) = (raised, refuted) {
400            let (by, at) = match r.site {
401                Site::Pat(pat) => (RefutedBy::Pattern, self.pat_span(r.chunk, pat)),
402                Site::Case(subject) => (RefutedBy::Case, self.node_span(r.chunk, subject)),
403                Site::Match => (RefutedBy::Match, None),
404            };
405            trace.refuted = Some(Refutation {
406                by,
407                at,
408                value: r.value,
409            });
410        }
411        trace
412    }
413
414    /// The function that application node `call` of chunk `at` is in: the
415    /// innermost lambda around it, named by the member it is the body of, or
416    /// else the innermost member, a `__main` or a top-level expression.
417    fn frame_name(&self, at: ChunkId, call: NodeId) -> FrameName {
418        let code = self.chunk(at);
419        let chunk: &StaticChunk = &code;
420        let Some(span) = chunk.node_span(call) else {
421            return FrameName::Top;
422        };
423        // An expression's chunk has a made name, and its body is no `__main`.
424        let expression = chunk.name().as_str().starts_with("__eval_");
425        // The innermost lambda around the call.
426        let lambda = chunk
427            .lambda_ids()
428            .filter_map(|l| Some((l, chunk.lambda_span(l)?)))
429            .filter(|(_, s)| s.contains(span))
430            .min_by_key(|(_, s)| s.1);
431        let members = chunk.module_ids().flat_map(|m| {
432            (0..chunk.member_len(m)).filter_map(move |i| Some((m, i, chunk.member(m, i)?)))
433        });
434        if let Some((l, lspan)) = lambda {
435            let named = members
436                .clone()
437                .find(|(_, _, member)| {
438                    member.node.get().is_some() && chunk.node(member.node) == Node::Abs(l)
439                })
440                .map(|(_, _, member)| member.name);
441            let main = || {
442                let body = chunk.module(chunk.top()).body;
443                body.get().is_some() && chunk.node(body) == Node::Abs(l) && !expression
444            };
445            return match named {
446                Some(name) => FrameName::Member(self.text(name)),
447                None if main() => FrameName::Main,
448                None => FrameName::Closure(self.ctx_span(at, lspan)),
449            };
450        }
451        let member = members
452            .filter_map(|(m, i, member)| Some((member, chunk.member_span(m, i)?)))
453            .filter(|(_, s)| s.contains(span))
454            .min_by_key(|(_, s)| s.1);
455        match member {
456            Some((member, _)) => FrameName::Member(self.text(member.name)),
457            None if expression => FrameName::Top,
458            None => FrameName::Main,
459        }
460    }
461
462    /// Reports `raised`, which reached the top with `trace`: an `uncaught`
463    /// line, then what refuted which value and the calls it unwound through,
464    /// each shown in `style`. `doc` gives the name and, if it has it, the
465    /// text of a document, by its source and the name of its chunk; an
466    /// anonymous document is known by the chunk's.
467    pub fn report_raised(
468        &self,
469        raised: &Raised,
470        trace: &Trace,
471        doc: &dyn Fn(&DocSource, &str) -> DocText,
472        style: ReportStyle,
473    ) -> String {
474        let indent = match style {
475            ReportStyle::Snippets => "",
476            ReportStyle::Lines => "  ",
477        };
478        let mut docs: Vec<(ChunkId, u32, String, Option<String>)> = Vec::new();
479        let mut at = |span: Option<CtxSpan>, message: &str| -> String {
480            let Some((location, span)) = span.and_then(|s| Some((self.locate(s.0)?, s))) else {
481                return format!("{indent}<unknown>: {message}");
482            };
483            let known = docs
484                .iter()
485                .position(|d| (d.0, d.1) == (location.chunk, location.doc));
486            let i = match known {
487                Some(i) => i,
488                None => {
489                    let chunk = self.chunk(location.chunk);
490                    let source = chunk.documents()[location.doc as usize].source();
491                    let (name, text) = doc(source, chunk.name().as_str());
492                    docs.push((location.chunk, location.doc, name, text));
493                    docs.len() - 1
494                }
495            };
496            let (_, _, name, text) = &docs[i];
497            match style {
498                ReportStyle::Snippets => shown(name, text.as_deref(), &location, span, message),
499                ReportStyle::Lines => {
500                    let line = location.line_num;
501                    match text.as_deref().and_then(|t| location.column(t)) {
502                        Some(column) => format!("{indent}{name}:{line}:{column}: {message}"),
503                        None => format!("{indent}{name}:{line}: {message}"),
504                    }
505                }
506            }
507        };
508        let mut out = format!("uncaught {}", raised.value().to_display(self));
509        if let Some(r) = &trace.refuted {
510            let what = match r.by {
511                RefutedBy::Pattern => "refuted",
512                RefutedBy::Case => "no arm matched",
513                RefutedBy::Match => "no clause matched",
514            };
515            let span = r.at.or_else(|| trace.frames.first()?.call);
516            out.push('\n');
517            out.push_str(&at(span, &format!("{what} {}", r.value.to_display(self))));
518        }
519        for (i, frame) in trace.frames.iter().enumerate() {
520            if let Some((j, n)) = trace.omitted {
521                if i == j {
522                    out.push_str(&format!("\n{indent}[{n} frames omitted]"));
523                }
524            }
525            let message = match &frame.within {
526                FrameName::Member(name) => format!("in {name}"),
527                FrameName::Main => String::from("in __main"),
528                FrameName::Closure(span) => match span.and_then(|s| self.locate(s.0)) {
529                    Some(l) => format!("in the closure at line {}", l.line_num),
530                    None => String::from("in a closure"),
531                },
532                FrameName::Top => String::from("in the expression"),
533            };
534            out.push('\n');
535            out.push_str(&at(frame.call, &message));
536            if frame.repeat > 0 {
537                out.push_str(&format!(
538                    "\n{indent}[the call above repeated {} more times]",
539                    frame.repeat
540                ));
541            }
542        }
543        out
544    }
545}
546
547/// `message` at `span`, which is at `location` of the document `name`: with
548/// the line and the span marked if the text is known, or else the line alone.
549fn shown(
550    name: &str,
551    text: Option<&str>,
552    location: &Location,
553    span: CtxSpan,
554    message: &str,
555) -> String {
556    match text {
557        Some(text) => report(
558            name,
559            text,
560            muon::Span {
561                offset: location.pos,
562                length: span.1,
563            },
564            message,
565        ),
566        None => format!("{name}:{}: {message}", location.line_num),
567    }
568}