Map: core / diagnostics

How every user-visible message — parse errors, type errors, runtime errors, exit-code hints — is located in source and rendered to the terminal.

Source locations — core/src/source.rs

A source position is a Span — a half-open byte range [start, end) tagged with a FileId, an opaque per-file handle. Line and column are not carried on IR or AST nodes; they are recovered at render time by handing the source text directly to ariadne. Where no narrower position is available, the position is Option<Span> = None uniformly across the AST, IR, and typechecker. Span::join merges two spans; Span::range yields the std::ops::Range<usize> ariadne expects. Carrying only byte offsets keeps the IR free of presentation state.

The error value — core/src/error.rs

One type is every runtime failure. An Error is the record, reason: Reason and prov: Option<Prov>, together with the report of one unwinding: stored hints (boxed, innermost site first), a witness span, an optional rejection, a context prefix and the Unwound facts (abandoned_tail, a saturating discarded byte count). Its optional parts are boxed because an Error rides in every Settled, and a compile-time assertion keeps it under clippy’s result_large_err threshold. Error::new(reason: Reason) -> Error accepts no implicit string conversion. with_hint appends, with_context prepends, and Display is the context chain followed by Reason::describe. Rendering lives in shell/runtime/error.rs, below.

Operational reasons are facts; Raised(Claim) is authored text. fact/error.rs declares the shared Reason; fact/error/ owns its closed payload families and their Datum definitions (ErrorRecord alone is Typed). Reason::describe and Reason::advice read those facts, not rendered messages. Error::io(operation: IoOperation, subject: IoSubject, error: &io::Error) borrows the native error and projects its cause through io::failure, retaining custom path/owned-I/O facts. Fixed not-found and permission-denied wording is derived centrally; opaque OS/library detail remains beneath a typed foreign cause, not a general message fallback. Native I/O subjects, path-error operands, non-Unicode refusals and environment-key subjects use text::quote_native before losing native units. Their portable strings include escaped quotes; renderers insert them once, without path normalization or re-quoting.

A block the checker refuses at install is one fact. A handler, catch-all, hook that the runtime vets and the checker refuses becomes InvalidCause::IllTyped { role: BlockRole, diagnostics } (fact/error/invalid.rs): each TypeDiagnostic is the stable code and rendered message of one checker error, projected by TypeError::diagnostic and gathered by ill_typed (shell/runtime/coerce.rs). The checker’s runtime entry points return every close error, not the first. IllTyped::new and its Datum decoder reject an empty diagnostic list; callers read it through diagnostics().

A failure carries one provenance: the failing frame’s name and site. prov is None until claimed. Break::locate(name, span, shell) (shell/runtime/flow.rs) claims an unlocated error or stop only when its span lies in a session source. Prov::Live { name: FrameName, span } draws a caret; Prov::Resolved holds a name and CallSite, drawing coordinates without a caret, and is what Prov::leaving makes of a live span the parent registry does not hold. Error::leaving also drops report-only witness spans outside the inherited registry prefix. A witness from another source is qualified by script, line and column; an equal display name alone does not establish source identity. An initial _ does not hide a frame; the baked prelude is invisible because its spans are outside session sources. See the error record.

Runtime source identity — SourceDb

Every registered Source carries its SourceOrigin (source.rs): a File by the native path it was read from, or a Virtual label — <stdin>, -c, a hook, an embedded profile — for text no file holds. That path is a SourceFile, UTF-8 by construction: an origin travels serialized (on a Run, a linked Module, the SourceDb) and serde holds a path only as text, so SourceFile::new — the one door, through path::utf8 — refuses a path that is not UTF-8, naming it, before the file is read, rather than letting serialization fail late. Every loader (batch script, startup file, plugin, use, capability profile, exarch’s config and network policy) surfaces that refusal as its own error. The origin is the source’s identity: the check-time load chain’s cycle key, the directory a script-relative path resolves beside, and, for a file, what $SCRIPT bakes. The display name a diagnostic draws and a CallSite carries is derived from it once, at registration: a file’s path path::shown, a virtual source’s label as given. A host names a run’s root source by the origin on its Run.

SourceDb (source.rs) resolves that id at render time. It is the registry of every source the session has loaded, keyed by FileId, living on SessionState::sources: append-only for the session’s whole life, so a nested run can never re-mint a FileId an outer run’s live spans still name. compile_run registers the root before compiling, once, so a nested module registration cannot take its FileId. Failed roots stay registered, as do loaded modules. IoLoan installs the root span with SessionState::root_file (None between runs). Hosts read the db after a run returns to render.

This is the structural fix for the cross-source caret: a runtime error raised inside a used module carries the module’s FileId, so the renderer resolves the module’s text and draws the caret into the module’s bytes — not the top-level script’s. An id the renderer cannot resolve (the placeholder FileId::DUMMY, or an unregistered source) renders messageless rather than indexing an unrelated text. (structural-bug-prevention class 9.)

CallSite (source.rs, resolved by SourceDb::site) is the audit-and-wire shape a span resolves to: script name and 1-indexed (line, col). Audit holds one total, private Prov register for the innermost visible frame; enter_site displaces it for a DisplacedSite token that only restore_site consumes, and visible calls bracket it so, with adjacent tail-call restorations coalesced. Shell::at_site(name, span, body) brackets synchronous operations. Every source run installs its root span; hooks install their origin at 1:1; workers inherit the parent’s register at spawn. Observation.site and Shell::call_site() are total CallSites. Minting an error record reads its own provenance, else that register, so an unclaimed failure names the run’s start. A worker completes provenance before publishing, making done, poll and await agree.

A compile failure carries its own text: Rejection (diagnostic.rs) pairs the failure’s Reports with their Source and the status a run that failed so exits on (2 parse, 1 type). Root and module text register before compilation. compile::CompileError includes Parse, Types and Use { at, refusal: UseRefusal }. A load refusal names the one written path, or carries a nested module rejection, cycle chain or depth refusal. The importer’s report points at use, then renders a rejected module against its own text. An unreadable module is never read and has no source report.

A run refused before evaluation carries StaticDiagnostics (shell/run.rs): Compile(Rejection) or spanless Host (an unknown hook, a non-ground argument). Its render reaches every host through Report::Static (engine-protocol). Module resolution, read, compile and undecided-export failures are static failures of the importer; try cannot catch them. A host-file compile failure reaches its host loading operation as an Error carrying Rejection; CompileError itself has no runtime dependency.

Static refusals retain their trail. RunReport::Static carries Vec<Observation>; wire Report::Static carries their encoded data. Successful check-only dispatches return RunReport::Checked / Report::Checked, also with a trail and no evaluated value. A check-time module read runs shell.locate under Prov::Live { name: "use", span: at }; its denial is recorded in the dispatch’s trail even when checking refuses evaluation. There is no compile-time mooring or surface event. The host prints the static diagnostic; ral --audit emits the trail envelope, and exarch consumes the same observations in its shell-eval report. Successful reads add no observation.

Rendering — core/src/diagnostic.rs

Each error draws itself; one drawer draws all. diagnostic is the report algebra: a Report (code, message, primary Label, optional secondary, hint) and Rejection. Report::render(&Source) is the single ariadne call, with byte indexing (IndexType::Byte) so a Span is the label’s own coordinate; caret widens an empty span to one whole char and anchors end of input on the last char, so every label is drawable. With no primary label, Report::plain is the compact one-liner. The builders sit with their errors: ParseError::report in syntax/report.rs (the L000x messages come from LexErrorKind::headline alone; a plain P0001 carries its own help, the message saying what is wrong and the help what to write), TypeError::report in typecheck/explain.rs, and Error::render / Error::compact (shell/runtime/error.rs, resolving live provenance against a SourceDb and borrowing the session’s ExitHints). UseRefusal::report in compile.rs uses U0001–U0005 for read, nested-check, cycle, depth and unavailable-loader refusals. Read refusals retain their structured Error and its hints; each refusal labels what failed, not every path failure as a failed typecheck. Rendering tests live inline with each owner: generic renderer tests in diagnostic.rs, parse and lexer reports in syntax/report.rs, type reports in typecheck/explain.rs, and runtime source selection in shell/runtime/error.rs.

End::render draws an ending through one private Diagnosis and one render function in shell/runtime/error.rs. Error::diagnosis supplies the described reason and report-only facts; Stop::diagnosis supplies its cause and provenance. Reason::describe(&self) is the one wording, reading the reason alone; Error::describe and ErrorFact::describe delegate, and the record’s message is its value. Reason::advice derives ordered intrinsic notes; runtime advice appends the session’s exit-hints entry for exited, keyed by program basename and status. A denial’s intrinsic remedy precedes stored hints. Other reasons show stored hints, then context_advice for the report’s operation context, then intrinsic and exit-table advice. All are shown, composed under SPEC §13.1; stored hints retain attachment order. Context prefixes never change the reason. Intrinsic advice is recomputed from the reason at each render, and a record carries no reason, so a raise of one has none; report-context advice does not survive without that context. The renderer then adds the saturating counted discard and, when no note is present and the failure is not a spawn refusal, an abandoned-tail note. A panic is spanless run panicked: …; values, exits and reader-gone stops render nothing. Error::render, compact and render_spanless use that same renderer; Error::plain is its words alone, uncoloured and unlaid (message line, then notes), for a host’s log or a command line’s last word where no session renders: Severed’s Display, exarch’s startup refusals. Hosts print the supplied rendered verbatim.

The renderer dispatches on where the error came from, not what the input looked like: a carried rejection draws its own report, so a broken plugin, module, rc or profile prints, at every door, the report its own run as a script would. Otherwise it takes compact_root: Option<FileId> — Some(root) when the input compiled to a single command, carrying that input’s own id — and renders compact only when the error’s span is absent or names root. A single command that dispatches into an rc handler, a used function or a lambda from an earlier run faults in text the user cannot see, so it gets the caret.

The shell’s own stderr lines sit below the renderer, in terminal/stderr.rs: cmd_error, shell_warning, and the macros outln! / err! / errln!, exported for the front ends’ own output too. Unlike println! and eprintln! they drop a failed write rather than panic, since once the terminal hangs up every write fails with EIO; clippy.toml bans the std pair.

The raw ingredients of a span underline are exposed so an external renderer can draw one in its own coordinate system. text::byte_to_char (core/src/text.rs, byte offset → character offset, the unit ariadne and a TextArea cursor both count in) and TypeErrorKind::render_label (typecheck/explain.rs, a kind → its under-caret label phrase) are pub. The structural frontend reuses them to paint an in-place type-error underline whose label and caret agree word-for-word and column-for-column with the post-Enter ariadne report — the inline rendering belongs to that page, not here. text.rs is also the single home of the nucleo fuzzy matcher (rank, and rank_by for an item that is not its own haystack), which serves exarch’s pickers and command popup. Type-error prose generally lives beside the checker: provenance is data on the error (Reason, typecheck/error.rs) and every user-facing sentence is a pure function of it in typecheck/explain.rs (typecheck).

Styling and the colour gate — core/src/io/ansi.rs, core/src/io/terminal.rs

ansi is vocabulary only: escape constants, the OSC helpers (osc_set_title, osc8_link), escape_seq_len, strip, visible, when. One colour decision, made once: a front end probes a TerminalState and seats it (TerminalState::seat, first wins); terminal::stderr_color and terminal::ui_color read that seat. A wire engine seats its EngineSpec.terminal, the front end’s, never a probe of its own null stdio. Before any seat, stderr_color answers from one memoised Auto probe, so early-startup errors still colour, and ui_color is false: only a front end has a UI. The $TERMINAL map is impl From<&TerminalState> for ValClos (ir/value.rs). TerminalState stores base facts only: hyperlinks, clipboard_write (both modern_osc) and bracketed_paste (supports_ansi) are methods, so no two fields can disagree, and the $TERMINAL keys of those names are derived. Value-output styling (the REPL’s => prefix) lives instead in the ral crate’s repl::theme.

Exit-code hints — core/src/shell/runtime/exit_hints.rs

ExitHints is a pure (program basename, exit-status) → explanation lookup table (two maps, * the wildcard), populated via from_text and installed into the Shell; lookup is consulted when an external command fails. Loading the table is the caller’s concern.

Debug tracing — dbg_trace!

dbg_trace!(tag, …) is the single developer-facing trace primitive: a tagged stderr line in debug builds (red only where the terminal::stderr_color gate allows, and through errln!, so never a panic), nothing in release, no environment switch for the trace itself (one-debug-path). Its call sites are permanent instrumentation.