Skip to main content

ridl_core/
diag.rs

1//! The coded diagnostic model every compiler pass emits (docs/ROADMAP.md epic
2//! E1.10, ADR-0004 §5, ADR-0007 decision 2).
3//!
4//! A [`Diagnostic`] is a first-class homegrown value — a stable [`DiagCode`], a
5//! [`Severity`], a message, a primary source [`Span`], secondary [`Label`]s, and
6//! optional [`FixIt`]s — held as the single source of truth and accumulated in a
7//! `Vec`, never modeled as an error return (ADR-0004 §5). The struct maps two
8//! ways: to a terminal renderer for the CLI ([`render`](render::render), over
9//! `codespan-reporting`) and, in a later epic, to LSP `Diagnostic` for editors.
10//!
11//! # Namespaces (ADR-0007 decision 2)
12//!
13//! Codes are grouped by hundreds and never renumbered or reused; a code
14//! retired from a catalogue is listed in [`RETIRED_RIDL_CODES`], and a guard
15//! keeps it out. Five namespaces are in play across the family, one catalogue
16//! each:
17//!
18//! - `FORM-…` — the shared family grammar: lexical `0xx`, parse `1xx`, and the
19//!   general form §4.3 attribute rules. Named after the general form's own
20//!   "shared form namespace". [`FORM_CATALOG`].
21//! - `TYPL-…` — typl semantic rules, defined by the typl reference §16.
22//!   [`TYPL_CATALOG`].
23//! - `RIDL-…` — ridl interaction rules, defined by the ridl reference §16.
24//!   [`RIDL_CATALOG`].
25//! - `RSDL-…` — rsdl system rules, defined by the rsdl reference §16.
26//!   [`RSDL_CATALOG`].
27//! - `MANI-…` — manifest, lockfile, cache, and fetch: the manifest `0xx` codes
28//!   (E1.5) and the distribution `1xx` codes (E1.6). [`MANI_CATALOG`].
29//!
30//! This module is the SSOT the error index (E4.2) reads. Every code is declared
31//! once, by [`diag_codes!`], which expands one entry into both the `DiagCode`
32//! constant and its catalogue row — a code with no entry cannot be written
33//! (ADR-0008 decision 21). A catalogue lists a code even when no pass emits it
34//! yet.
35//!
36//! # The [`FileId`] bridge
37//!
38//! A [`Span`] locates its range inside a file identified by an interned
39//! [`FileId`]. [`SourceMap`] issues those ids: a pass that holds a file's path
40//! and text calls [`SourceMap::file_id`] to obtain the id it stamps into its
41//! spans. The [`SourceMap`] is the only bridge between a diagnostic and the
42//! source text the renderer needs.
43
44use rowan::{TextRange, TextSize};
45use serde::{Serialize, Serializer};
46
47pub mod render;
48
49pub use render::render;
50
51/// A stable diagnostic code, e.g. `"FORM-101"` or `"TYPL-108"` (ADR-0007
52/// decision 2). The empty string means "no code yet" — a diagnostic that has
53/// not been assigned a catalogue code renders as a plain message.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
55#[serde(transparent)]
56pub struct DiagCode(pub &'static str);
57
58impl DiagCode {
59    /// The code string.
60    pub fn as_str(&self) -> &'static str {
61        self.0
62    }
63
64    /// Whether this is the sentinel "no code yet" value.
65    pub fn is_empty(&self) -> bool {
66        self.0.is_empty()
67    }
68
69    /// The sentinel for a diagnostic that carries no catalogue code yet, such
70    /// as the checker's "expected a type, but `X` names a constant / an
71    /// interface" errors (typl §16 defines no code for either) or the Rust
72    /// backend's codegen error. A diagnostic carrying it renders with no code
73    /// after its severity word (`error:`, `warning:`), and the book harness
74    /// can never allow one.
75    pub const NONE: DiagCode = DiagCode("");
76}
77
78/// Declares every diagnostic code exactly once (ADR-0008 decision 21).
79///
80/// One entry expands to both the `DiagCode` constant and the [`CatalogEntry`]
81/// that names it, so a code with no catalogue entry cannot be written: there is
82/// no second list to forget.
83///
84/// The macro also generates [`ALL_CATALOGS`], which the guards read to find
85/// every catalogue. That makes it invocable only once **per module** — a second
86/// invocation beside this one redefines the constant and the crate stops
87/// compiling. It does **not** make it invocable once per crate: a second
88/// invocation inside a child module of `diag` compiles, and its catalogue is
89/// invisible to `ALL_CATALOGS` here. What covers that case is
90/// `codes_written_as_string_literals_are_all_catalogued`, and it covers it for a
91/// structural reason rather than by luck — `$code:literal` guarantees every code
92/// the macro declares is spelled as a literal in a `.rs` file, so a catalogue
93/// the guards cannot see still puts its codes where the scan can.
94///
95/// This replaces the pair of hand-maintained arrays `FORM_CATALOG` and
96/// `MANI_CATALOG` carried until E2 close-out, each guarded by a test that
97/// compared it against a *second hand-written list inside the test*. That pair
98/// checked that two lists agreed; it never checked either against the codes
99/// actually declared, so a constant added to neither compiled and turned nothing
100/// red. `RIDL` and `TYPL` had no catalogue at all.
101///
102/// The remedy available in `crates/ridl-diff` — make the guard an exhaustive `match`
103/// and let the compiler enforce totality — does not exist here: `DiagCode` is a
104/// newtype over `&'static str`, not an enum, so there is no variant set to match
105/// on. Declaring the constant and its entry from one line is the shape that
106/// works for a newtype.
107macro_rules! diag_codes {
108    (
109        $(
110            $(#[$catalog_doc:meta])*
111            $catalog:ident {
112                $(
113                    $(#[$code_doc:meta])*
114                    $konst:ident = $code:literal, $severity:ident,
115                        $summary:literal;
116                )+
117            }
118        )+
119    ) => {
120        impl DiagCode {
121            $($(
122                $(#[$code_doc])*
123                pub const $konst: DiagCode = DiagCode($code);
124            )+)+
125        }
126
127        $(
128            $(#[$catalog_doc])*
129            pub const $catalog: &[CatalogEntry] = &[
130                $(CatalogEntry {
131                    code: DiagCode::$konst,
132                    severity: Severity::$severity,
133                    summary: $summary,
134                },)+
135            ];
136        )+
137
138        /// Every catalogue this module declares, each paired with its constant's
139        /// name. The error index (E4.2) reads this rather than naming the
140        /// catalogues one at a time, and so do the guards below.
141        pub const ALL_CATALOGS: &[(&str, &[CatalogEntry])] = &[
142            $((stringify!($catalog), $catalog),)+
143        ];
144
145        /// Each constant's name paired with the code string it expands to, so a
146        /// guard can check the two agree. Generated rather than written down —
147        /// a hand-written copy would be the shadow this macro exists to remove.
148        #[cfg(test)]
149        const CODE_CONSTANT_NAMES: &[(&str, &str)] = &[
150            $($((stringify!($konst), $code),)+)+
151        ];
152    };
153}
154
155/// The `RIDL-` codes retired by the interface lock (lock design §9). A code is
156/// never renumbered or reused (ADR-0008 decision 13): RIDL-146 to RIDL-148
157/// guarded the slot model of a service's list — a shape re-declared under a
158/// service-level `reserved` name, one interface name on two shapes, and a
159/// nameless service-level tombstone — and left the catalogue with that model
160/// on 2026-09-15. Held as integers rather than `"RIDL-146"` literals, because
161/// a string literal of a code that is in no catalogue fails
162/// `codes_written_as_string_literals_are_all_catalogued`; the guard
163/// `retired_ridl_codes_are_never_redeclared` keeps the numbers out of
164/// [`RIDL_CATALOG`].
165pub const RETIRED_RIDL_CODES: &[u16] = &[146, 147, 148];
166
167diag_codes! {
168    /// The FORM catalogue (ADR-0007 decision 2): lexical `0xx`, parse `1xx`, and
169    /// the attribute-semantics codes 106-108 the checker emits for the general
170    /// form §4.3 allow-list (E2 task 5). Every FORM code is listed even when no
171    /// pass emits it yet, so the error index has one authoritative source. FORM
172    /// diagnostics are all errors.
173    FORM_CATALOG {
174        /// Invalid character.
175        FORM_001 = "FORM-001", Error,
176            "invalid character";
177
178        /// Unterminated string literal.
179        FORM_002 = "FORM-002", Error,
180            "unterminated string literal";
181
182        /// Unterminated regex literal.
183        FORM_003 = "FORM-003", Error,
184            "unterminated regex literal";
185
186        /// Unterminated block comment.
187        FORM_004 = "FORM-004", Error,
188            "unterminated block comment";
189
190        /// Leading zeros in an integer literal.
191        FORM_005 = "FORM-005", Error,
192            "leading zeros in integer literal";
193
194        /// Expected a specific token, or a construct the grammar admits here.
195        /// Most call sites name a token (`` expected `]` ``); the interaction
196        /// positions name the shapes instead — a return type is one of four,
197        /// and saying which is the point of the message.
198        FORM_101 = "FORM-101", Error,
199            "expected a specific token, or a construct the grammar admits here";
200
201        /// Unexpected token — also the code for nesting past the depth the
202        /// parser follows (`MAX_TYPE_DEPTH` in `ridl-syntax`): a type, an
203        /// attribute value, a parenthesised group, or an expression tree,
204        /// whose height each binary operator, member access, group and
205        /// prefix raises by one level.
206        FORM_102 = "FORM-102", Error,
207            "unexpected token";
208
209        /// Unclosed delimiter.
210        FORM_103 = "FORM-103", Error,
211            "unclosed delimiter";
212
213        /// Missing `package` declaration.
214        FORM_104 = "FORM-104", Error,
215            "missing `package` declaration";
216
217        /// Reserved word used as an identifier.
218        FORM_105 = "FORM-105", Error,
219            "reserved word used as an identifier";
220
221        /// Unknown attribute key — not a key the general form §4.3 table defines.
222        FORM_106 = "FORM-106", Error,
223            "unknown attribute key";
224
225        /// Attribute key not allowed on this declaration kind (general form §4.3).
226        FORM_107 = "FORM-107", Error,
227            "attribute key not allowed on this declaration kind";
228
229        /// Duplicate attribute key in one `[ ]` block (general form §4.3).
230        FORM_108 = "FORM-108", Error,
231            "duplicate attribute key in one block";
232    }
233
234    /// The typl catalogue (ADR-0008 decision 21): every `TYPL-` code declared in
235    /// this module, with the severity the typl reference §16 tables classify it
236    /// at. Six codes the reference documents are absent because no constant
237    /// declares them and no pass emits them — TYPL-107, TYPL-112, TYPL-205, and
238    /// the three `@labels` assurance codes TYPL-401 to TYPL-403. That inventory
239    /// is recorded in issue #172; closing it means minting the constants, which
240    /// is a change to what the compiler declares, not a catalogue edit.
241    TYPL_CATALOG {
242        /// More than one `package` declaration in a single file (typl §16.1).
243        /// Emitted by the package loader (E1.3).
244        TYPL_001 = "TYPL-001", Error,
245            "more than one `package` declaration in a file";
246
247        /// Package name does not mirror the directory path relative to the
248        /// manifest root (typl §16.1, ADR-0002 §1). Emitted by the package loader
249        /// (E1.3); single-file mode is exempt.
250        TYPL_002 = "TYPL-002", Error,
251            "package name does not mirror the directory path";
252
253        /// Wildcard, relative, or re-exporting import (typl §16.1, ADR-0002 §2).
254        /// Emitted by the resolver (E1.4).
255        TYPL_003 = "TYPL-003", Error,
256            "wildcard, relative, or re-exporting import";
257
258        /// Circular package imports (typl §16.1, ADR-0002 §6). Emitted by the
259        /// resolver (E1.4) from a depth-first walk over package import edges.
260        TYPL_004 = "TYPL-004", Error,
261            "circular package imports";
262
263        /// A public declaration exposes an `internal` type in its fields, arms,
264        /// backing, or a range-bound constant (typl §3.3, §16.1). Emitted by the
265        /// checker (E1.7b) over every top-level declaration, the ridl `interface`
266        /// and `service` included: an interaction payload, parameter, return arm,
267        /// or stream element is an exposure position exactly as a struct field is.
268        /// A `service` naming an `internal` interface is RIDL-143 instead.
269        TYPL_005 = "TYPL-005", Error,
270            "a public declaration exposes an `internal` type";
271
272        /// Conflicting imports without an alias (typl §16.1, ADR-0002 §2).
273        /// Emitted by the resolver (E1.4).
274        TYPL_006 = "TYPL-006", Error,
275            "conflicting imports without an alias";
276
277        /// Unused import (typl §16.1). Emitted by the resolver (E1.4) as a warning.
278        TYPL_007 = "TYPL-007", Warning,
279            "unused import";
280
281        /// Import alias without an actual collision (typl §16.1, ADR-0002 §2).
282        /// Emitted by the resolver (E1.4) as a warning.
283        TYPL_008 = "TYPL-008", Warning,
284            "import alias without an actual collision";
285
286        /// Duplicate definition of the same name in a package (typl §16.1).
287        TYPL_009 = "TYPL-009", Error,
288            "duplicate definition of the same name in a package";
289
290        /// A package declaring a name the compiler provides itself (typl
291        /// §3.1, §16.1). Error, and not a warning, because such a package can
292        /// never work: `ridl.std` is implicitly imported by every package
293        /// (typl §3.2) rather than resolved through an import, so a user copy
294        /// is unreachable by its own name. In package and workspace mode the
295        /// generated artifact is overwritten by the standard package's too,
296        /// because the output base is the package name; in single-file mode
297        /// the base is the file stem, so that second consequence follows only
298        /// when the stem is itself `ridl.std`, whatever the extension.
299        /// Reported on the `package` declaration, in a workspace member and
300        /// in single-file mode alike.
301        TYPL_010 = "TYPL-010", Error,
302            "package name is reserved for a package the compiler provides";
303
304        /// A type reference names no visible declaration (typl §3.2, §3.3,
305        /// §16.1): the path resolves neither in the package's own scope, nor
306        /// in `ridl.std`, nor through an import, nor as a qualified
307        /// `pkg.Name` — a qualified reference to another package's `internal`
308        /// declaration included. Emitted by the checker on the written path,
309        /// in every position that takes a type reference — for example a
310        /// field, a parameter, a query return, a stream element, a payload,
311        /// a union arm, a map key or a constant's type. A reference that resolves to a declaration of the
312        /// wrong kind (a constant, an interface) is a different error and
313        /// still carries no code (driftsys/ridl#543).
314        TYPL_011 = "TYPL-011", Error,
315            "type reference names no visible declaration";
316
317        /// `integer` without a range constraint (typl §16.2). Warning.
318        TYPL_101 = "TYPL-101", Warning,
319            "`integer` without a range constraint";
320
321        /// `float` without both a range and a `step` (typl §16.2). Warning.
322        TYPL_102 = "TYPL-102", Warning,
323            "`float` without both a range and a `step`";
324
325        /// `string`/`bytes` without explicit bounds — the default `[0..256]` is
326        /// applied (typl §4.4–§4.5, §16.2). Warning.
327        TYPL_103 = "TYPL-103", Warning,
328            "`string`/`bytes` without explicit bounds";
329
330        /// Range `min > max` (typl §16.2).
331        TYPL_104 = "TYPL-104", Error,
332            "range `min > max`";
333
334        /// `step` type mismatch, non-positive, or larger than the range
335        /// (typl §16.2). Also borrowed by the checker (E1.7b) for a range bound
336        /// that references a non-numeric constant, a malformed bound const for
337        /// which §16.2 defines no dedicated code.
338        TYPL_105 = "TYPL-105", Error,
339            "`step` type mismatch, non-positive, or larger than the range";
340
341        /// Invalid regex syntax in a `match` constraint or a regex `const`
342        /// (typl §16.2). Validated with the `regress` ECMA-262 engine (ADR-0007
343        /// decision 10). Emitted by the checker (E1.7b).
344        TYPL_106 = "TYPL-106", Error,
345            "invalid regex syntax in `match` or a regex `const`";
346
347        /// `const` value violates its declared type constraints (typl §16.2).
348        TYPL_108 = "TYPL-108", Error,
349            "`const` value violates its declared type constraints";
350
351        /// Init (`= value`) incompatible with the type/field constraints
352        /// (typl §16.2).
353        TYPL_109 = "TYPL-109", Error,
354            "init `= value` incompatible with the type or field constraints";
355
356        /// Unknown or malformed UCUM unit expression (typl §16.2).
357        TYPL_110 = "TYPL-110", Error,
358            "unknown or malformed UCUM unit expression";
359
360        /// Integer range bound (or enumset bit position) outside the `int64`
361        /// domain (typl §4.2, §16.2).
362        TYPL_111 = "TYPL-111", Error,
363            "integer range bound outside the `int64` domain";
364
365        /// Type has no derivable init value and no declared `= value`
366        /// (typl §5.8, §16.2). Info — escalated to an error only by consumers
367        /// that require an init (e.g. a ridl signal payload).
368        TYPL_115 = "TYPL-115", Info,
369            "type has no derivable init value and no declared `= value`";
370
371        /// Array without explicit bounds (typl §16.3).
372        TYPL_201 = "TYPL-201", Error,
373            "array without explicit bounds";
374
375        /// Map without explicit bounds (typl §16.3).
376        TYPL_202 = "TYPL-202", Error,
377            "map without explicit bounds";
378
379        /// Enum values not unique / not explicitly assigned (typl §16.3).
380        TYPL_203 = "TYPL-203", Error,
381            "enum values not unique or not explicitly assigned";
382
383        /// Union arm with a primitive type (typl §16.3).
384        TYPL_204 = "TYPL-204", Error,
385            "union arm with a primitive type";
386
387        /// Recursive composite reference, direct or transitive (typl §16.3).
388        TYPL_206 = "TYPL-206", Error,
389            "recursive composite reference, direct or transitive";
390
391        /// Enumset bit positions not unique (typl §16.3).
392        TYPL_207 = "TYPL-207", Error,
393            "enumset bit positions not unique";
394
395        /// `string`/`bytes` used directly as a field type (typl §16.3).
396        TYPL_208 = "TYPL-208", Error,
397            "`string`/`bytes` used directly as a field type";
398
399        /// Map key is not a named string type or a primitive (typl §16.3).
400        TYPL_209 = "TYPL-209", Error,
401            "map key is not a named string type or a primitive";
402
403        /// Field, arm, or enum value re-declared under a `reserved` name or value
404        /// (typl §16.3).
405        TYPL_210 = "TYPL-210", Error,
406            "field, arm, or enum value re-declared under a `reserved` entry";
407
408        /// Duplicate `reserved` entry (typl §16.3). Warning. The "dangling"
409        /// half of the §16.3 rule (a name/value never previously used) needs the
410        /// previous IR snapshot and belongs to `ridl-diff` (E2.8).
411        TYPL_211 = "TYPL-211", Warning,
412            "duplicate `reserved` entry";
413
414        /// `error` modifier on a declaration other than `enum`, `struct`, `union`
415        /// (typl §16.3).
416        TYPL_212 = "TYPL-212", Error,
417            "`error` modifier on a declaration other than `enum`, `struct`, `union`";
418
419        /// Union mixing error and non-error arms without the result-union shape
420        /// (typl §16.3).
421        TYPL_213 = "TYPL-213", Error,
422            "union mixes error and non-error arms without the result-union shape";
423
424        /// `error union` containing a non-error-typed arm (typl §16.3).
425        TYPL_214 = "TYPL-214", Error,
426            "`error union` contains a non-error-typed arm";
427
428        /// A field name declared twice in one struct (typl §7, §16.3). Distinct
429        /// from RIDL-149: that code fires when two distinct source names
430        /// collide only after a pinned name transform, and this one fires
431        /// when the two source names are already the same, before any
432        /// transform runs. Both fields still lower — this check reports and
433        /// does not drop.
434        TYPL_215 = "TYPL-215", Error,
435            "field name declared twice in one struct";
436
437        /// An enum value name declared twice in one `enum` (typl §8, §16.3).
438        /// Distinct from RIDL-149: that code fires when two distinct source
439        /// names collide only after a pinned name transform, and this one
440        /// fires when the two source names are already the same, before any
441        /// transform runs. TYPL-203 checks the values' integers, not their
442        /// names, so it does not cover this case.
443        TYPL_216 = "TYPL-216", Error,
444            "enum value name declared twice in one enum";
445
446        /// Stream type `<T>` outside interaction position (typl §16.4, ridl
447        /// §12.3). Emitted by the parser in a `.typl` parse (E2 task 2) and by
448        /// the checker for struct fields and collections in a `.ridl` file
449        /// (E2 task 5).
450        TYPL_301 = "TYPL-301", Error,
451            "stream type `<T>` outside interaction position";
452
453        /// Timing annotation or duration literal in a typl context (typl §16.4).
454        TYPL_302 = "TYPL-302", Error,
455            "timing annotation or duration literal in a typl context";
456
457        /// `require`/`ensure` attribute in a typl context (typl §16.4): the two
458        /// contract attributes at declaration-start position in a `.typl` parse.
459        /// Emitted by the parser (E2 task 2) as a bare string literal rather than
460        /// through this constant — see `codes_written_as_string_literals_are_all
461        /// _catalogued`.
462        TYPL_303 = "TYPL-303", Error,
463            "`require`/`ensure` attribute in a typl context";
464
465        /// Interaction declaration in a typl context (typl §16.4, ADR-0007
466        /// decision 10): one of the nine ridl words at declaration-start position
467        /// in a `.typl` parse. Emitted by the parser (E2 task 2).
468        TYPL_304 = "TYPL-304", Error,
469            "interaction declaration in a typl context";
470
471        /// Blank line between a doc comment and its definition (typl §14, §16.5).
472        /// Warning. Emitted by the checker (E1.7b).
473        TYPL_404 = "TYPL-404", Warning,
474            "blank line between a doc comment and its definition";
475
476        /// `@deprecated` doc tag without a reason string (typl §14.2, §16.5).
477        /// Warning. Emitted by the checker (E1.7b).
478        TYPL_405 = "TYPL-405", Warning,
479            "`@deprecated` doc tag without a reason string";
480    }
481
482    /// The ridl catalogue (ADR-0008 decision 21): every `RIDL-` code declared in
483    /// this module, with the severity the ridl reference §16 tables classify it
484    /// at. RIDL-140, RIDL-141, and RIDL-143 to RIDL-145 sit in the 1xx band
485    /// while the reference lists them under the §16.4 evolution table — a
486    /// documented anomaly kept as written (ADR-0008 decision 6). RIDL-111 and
487    /// RIDL-142 are reserved by ADR-0008 decision 21 and are not declared yet,
488    /// so they are absent here too.
489    ///
490    /// Adding a code here does **not** make it show up in a corpus fixture.
491    /// `RIDL_PROFILE_CODES` in `crates/ridlc/tests/corpus.rs` — the list that
492    /// gives every ridl code a living example — is a list of code *strings*
493    /// with no link to these constants, so a code minted here and omitted there
494    /// is caught by a string-set equality standing beside the declaration
495    /// (`ridl_profile_codes_match_the_catalogue`) rather than by the declaration
496    /// itself. Decision 21 asks the declare-once mechanism to cover that list as
497    /// well, and it does not: the list carries a `Provoked` discriminator this
498    /// catalogue has no equivalent of. Stated here as decision 21 requires; the
499    /// gap is separate work, tracked in issue #172.
500    RIDL_CATALOG {
501        /// `signal` or `event` without a timing annotation — the default
502        /// `[100ms..1000ms]` (or the configured `[defaults].timing`) is applied
503        /// (ridl §9.1, §16.1). Warning. Emitted by the checker (E2 task 9).
504        RIDL_100 = "RIDL-100", Warning,
505            "`signal` or `event` without a timing annotation";
506
507        /// A range annotation `@[X..Y]` whose lower bound exceeds its upper bound
508        /// (ridl §9.2, §16.1). Emitted by the checker (E2 task 9).
509        RIDL_101 = "RIDL-101", Error,
510            "timing range `@[X..Y]` with `X > Y`";
511
512        /// A zero or negative timing duration (ridl §9.2, §16.1). Emitted by the
513        /// checker (E2 task 9).
514        RIDL_102 = "RIDL-102", Error,
515            "zero or negative timing duration";
516
517        /// A strict-periodic `@Xms` annotation on a kind other than `signal` —
518        /// the isochronous mode belongs to state alone (ridl §9.2, §16.1).
519        /// Widened from "on an `event`" by ADR-0015 decision 6 when `command`
520        /// and `query` gained the range form (E9.4): the same rule, stated
521        /// over the three kinds it excludes instead of one. Emitted by the
522        /// checker (E2 task 9).
523        RIDL_103 = "RIDL-103", Error,
524            "strict-periodic `@Xms` on a kind other than `signal`";
525
526        /// Explicit return type on a `command` — a command always returns `()`
527        /// (ridl §6.1, §16.1). Emitted by the checker (E2 task 5).
528        RIDL_104 = "RIDL-104", Error,
529            "explicit return type on a `command`";
530
531        /// `query` returning `()` — use `command` (ridl §7.1, §16.1). Emitted by
532        /// the checker (E2 task 5).
533        RIDL_105 = "RIDL-105", Error,
534            "`query` returning `()`";
535
536        /// A timing annotation on `fixed` — the one kind that carries none —
537        /// or an attribute block on `fixed` (ridl §8, §9, §16.1). Emitted by
538        /// the checker (E2 task 5).
539        ///
540        /// Narrowed by ADR-0015 decision 6 (E9.4): `command` and `query` admit
541        /// the range form now, so the two RPC kinds left this rule and only
542        /// `fixed` remains in both halves. The callables drew FORM-102 until
543        /// the E2 close-out, so one rule sat under two codes and one of them
544        /// was a parse code whose catalogue meaning is "unexpected token" —
545        /// for a token the grammar accepts on purpose, precisely so the
546        /// narrowing can be a semantic rule with a semantic message.
547        RIDL_106 = "RIDL-106", Error,
548            "timing annotation on `fixed`, or attribute block on `fixed`";
549
550        /// Type declaration inside an `interface` or `service` body — typl
551        /// declarations live at package level (ridl §14.1, §16.1).
552        ///
553        /// Emitted by the **parser**, as a bare string literal (`ridl-syntax`
554        /// cannot reference [`DiagCode`]), at the point where it recognises the
555        /// keyword and recovers the declaration into an `ErrorNode`. The
556        /// checker used to code that node a second time, so every RIDL-107
557        /// arrived paired with a contradicting FORM-102 at the same span; the
558        /// parser knows exactly what the construct is, so it is the one that
559        /// names it. RIDL-403 and TYPL-304 are parser-raised for the same
560        /// reason. The constant is kept for the catalogue and for the error
561        /// index.
562        RIDL_107 = "RIDL-107", Error,
563            "type declaration inside an `interface` or `service` body";
564
565        /// A range annotation `@[X..X]` whose bounds are equal — a degenerate
566        /// range, the rate floor equal to its staleness bound, on a `signal` and an
567        /// `event` alike (ridl §9.2, §16.1; ADR-0008 decision 17). Not a spelling
568        /// of the strict-periodic `@Xms`, which is a separate `TimingMode`.
569        /// Warning. Emitted by the checker (E2 task 9).
570        RIDL_108 = "RIDL-108", Warning,
571            "degenerate timing range `@[X..X]`";
572
573        /// Signal payload type has no derivable init value and no `= value`
574        /// override (ridl §4.4, §16.1). Emitted by the checker (E2 task 5).
575        RIDL_109 = "RIDL-109", Error,
576            "signal payload has no derivable init and no `= value` override";
577
578        /// Signal `= value` init override violates the payload type's constraints
579        /// (ridl §4.4, §16.1). Emitted by the checker (E2 task 5).
580        RIDL_110 = "RIDL-110", Error,
581            "signal `= value` init override violates the payload constraints";
582
583        /// A `command` or `query` with no declared response bound — no `@`
584        /// annotation at all, or the half-open `@[min..]` that declares a
585        /// throttle only (ridl §9, §16.1; ADR-0015 decisions 4 and 6). Warning;
586        /// an active profile may escalate it to an error, the same two-step
587        /// §9.1 gives an untimed signal or event. The RPC counterpart of
588        /// RIDL-100, and deliberately not RIDL-100 itself: that text turns on
589        /// a default having been applied, which is exactly what an RPC never
590        /// gets — absent means undeclared in the IR. RIDL-111 is reserved for
591        /// the interface-used-as-a-type error (ADR-0008 decision 21), so 112
592        /// is the first free code in the band. Emitted by the checker (E9.4).
593        RIDL_112 = "RIDL-112", Warning,
594            "`command` or `query` with no declared response bound";
595
596        /// Duplicate `service` name across the whole workspace — the service
597        /// catalog is a flat global namespace (ridl §14.5, §16.4). Emitted
598        /// workspace-wide by `service_catalog` (E2 task 8). The reference numbers
599        /// it in the 1xx band while listing it under the §16.4 evolution/profile
600        /// table — a documented anomaly kept as written (ADR-0008 decision 6).
601        RIDL_140 = "RIDL-140", Error,
602            "duplicate `service` name across the workspace";
603
604        /// A `service` names a type that is not an `interface`, and has no inline
605        /// shape (ridl §14.5, §16.4). Emitted per-package by the checker (E2 task
606        /// 8). Kept in the 1xx band per ADR-0008 decision 6 (see RIDL-140).
607        /// Applies per shape in the service's shape list since ADR-0015
608        /// decision 18 (E9.6): the rule is unchanged, the span reports against
609        /// the offending list element.
610        RIDL_141 = "RIDL-141", Error,
611            "`service` names a type that is not an `interface`";
612
613        /// A `service` publishes an `internal` interface (ridl §14.5, §16.4).
614        /// Emitted per-package by the checker's exposure pass. Distinct from
615        /// TYPL-005: what leaks is an interface rather than a type, and a service
616        /// takes no `internal` modifier, so the TYPL-005 remedy — make the
617        /// exposing declaration internal too — does not exist here. Kept in the
618        /// 1xx band beside RIDL-140/-141 per ADR-0008 decision 6. RIDL-111 and
619        /// RIDL-142 are reserved by decision 21 and not yet implemented, so 143 is
620        /// the next free code; decision 13's allocation ledger needs the ninth
621        /// entry (issue #169). Applies per shape in the service's shape list
622        /// since ADR-0015 decision 18 (E9.6): the rule is unchanged, the span
623        /// reports against the offending list element.
624        RIDL_143 = "RIDL-143", Error,
625            "`service` publishes an `internal` interface";
626
627        /// Duplicate member name across a service's interfaces (ridl §14.5,
628        /// §16.4; ADR-0015 decisions 16 and 18): two composed interfaces both
629        /// declaring `status` would give `service.status` two referents, which
630        /// flat addressing cannot express. Emitted per-package by the checker
631        /// (E9.6). The service codes sit in the 1xx band (see RIDL-140);
632        /// RIDL-112 is minted by ADR-0015 decision 6, so 144 is the first free
633        /// code.
634        RIDL_144 = "RIDL-144", Error,
635            "duplicate member name across a service's interfaces";
636
637        /// The same interface named twice in one service (ridl §14.5, §16.4;
638        /// ADR-0015 decision 18). Its own code rather than a fall-through to
639        /// RIDL-144: listing a shape twice makes every member collide, so
640        /// RIDL-144 alone would emit one diagnostic per member and bury the
641        /// actual mistake. Emitted per-package by the checker (E9.6); lowering
642        /// keeps the first listing only, which holds the slot, and the
643        /// diagnostic's secondary label points at it.
644        RIDL_145 = "RIDL-145", Error,
645            "the same interface named twice in one service";
646
647        /// Two names in one scope that collide after a pinned name transform
648        /// (ridl §11, §16.4; ADR-0016 decision 3). Neither transform is
649        /// injective and no case-folding transform can be, so
650        /// `parseHTTPResponse` and `parseHttpResponse` both project to
651        /// `parse_http_response` and a target whose namespace is snake_case
652        /// would carry one identifier twice — in Rust, one trait with two
653        /// methods of the same name, or one function with two identically
654        /// named arguments. The projection contract's injectivity obligation
655        /// is discharged here, on the package, because it cannot be carried
656        /// by the function. Its own code rather than RIDL-402 — that rule is
657        /// the same name declared twice — because the remedy differs: these
658        /// names are distinct in source and only their projections collide.
659        /// Scoped to the members of one interface, the parameters of one
660        /// interaction (decision 4), the fields of one struct, which joined
661        /// in the commit where E9.8 started projecting them onto proto3, the
662        /// arms of one union, which joined with the ADR-0016 amendment of
663        /// 2026-09-20, and the values of one enum, which joined with the
664        /// amendment of 2026-09-26. The first three namespaces are checked
665        /// under `snake_case` alone; a union's arms are checked under
666        /// `snake_case` and `camel_case` both, because a union arm reaches
667        /// both namespaces and the two collision sets are incomparable; an
668        /// enum's values are checked under `pascal_case` alone, because its
669        /// collision set contains `snake_case`'s. The message names the
670        /// transform that collided. Emitted per-package by the checker (E9.7).
671        RIDL_149 = "RIDL-149", Error,
672            "two names in one scope collide after a pinned name transform";
673
674        /// Stream `<T>` on a `signal` or `event` payload (ridl §12.3, §16.2).
675        /// Emitted by the checker (E2 task 5).
676        RIDL_201 = "RIDL-201", Error,
677            "stream `<T>` on a `signal` or `event` payload";
678
679        /// Stream element type not a named type, `string`, or `bytes` (ridl
680        /// §12.2, §16.2). Emitted by the checker (E2 task 5).
681        RIDL_202 = "RIDL-202", Error,
682            "stream element type not a named type, `string`, or `bytes`";
683
684        /// `require` or `ensure` on `signal`, `event`, or `fixed` (ridl §13,
685        /// §16.3). Emitted by the checker (E2 task 5).
686        RIDL_301 = "RIDL-301", Error,
687            "`require` or `ensure` on `signal`, `event`, or `fixed`";
688
689        /// `ensure` on `command` — a command has no result to observe (ridl §6.1,
690        /// §16.3). Emitted by the checker (E2 task 5).
691        RIDL_302 = "RIDL-302", Error,
692            "`ensure` on `command`";
693
694        /// A fallible query return with no success path (ridl §10.1, §16.3; general
695        /// form §6.1): a bare `error` type in return position, an `error`-typed
696        /// success (left) arm of an inline `T | E`, or a non-error error (right)
697        /// arm. Error. Emitted by the checker (E2 task 10).
698        RIDL_303 = "RIDL-303", Error,
699            "fallible query return with no success path";
700
701        /// An `error`-typed or result-union parameter on a `command` or `query` —
702        /// failure flowing toward a provider (ridl §10.1, §16.3). Warning. Emitted
703        /// by the checker (E2 task 10).
704        RIDL_304 = "RIDL-304", Warning,
705            "`error`-typed or result-union parameter on a `command` or `query`";
706
707        /// An `ensure` clause that never references `result` — well-typed but
708        /// suspicious (ridl §13, §16.3; expr-core specification §8). Warning.
709        /// Emitted by the checker (E2 task 11).
710        RIDL_305 = "RIDL-305", Warning,
711            "`ensure` clause that never references `result`";
712
713        /// A `require`/`ensure` expression outside the guaranteed subset (ridl §13,
714        /// §16.3; expr-core specification §8 — one code for the whole boundary,
715        /// with a message naming the offending form). Error. Emitted by the checker
716        /// (E2 task 11).
717        RIDL_306 = "RIDL-306", Error,
718            "`require`/`ensure` expression outside the guaranteed subset";
719
720        /// An `error` enum declares a Stratum-2 contract-error category name
721        /// (`INVALID_VALUE`, `PRECONDITION_FAILED`, `CONTRACT_BROKEN`,
722        /// `UNKNOWN_INTERACTION`) — reserved vocabulary (ridl §10.2, §16.3).
723        /// Warning. Emitted by the checker (E2 task 10).
724        RIDL_307 = "RIDL-307", Warning,
725            "contract-error category name declared in an `error` enum";
726
727        /// A named result union in query return position — the inline `T | E`
728        /// spelling is canonical there (general form §6.1, ADR-0008 decision 13).
729        /// Warning; the named spelling stays legal typl data, so this is a lint,
730        /// not an error. Emitted by the lint pass (E2 task 19).
731        RIDL_308 = "RIDL-308", Warning,
732            "named result union in query return position";
733
734        /// Interaction re-declared under a `reserved` name (ridl §11, §16.4).
735        /// Emitted by the checker (E2 task 5).
736        RIDL_401 = "RIDL-401", Error,
737            "interaction re-declared under a `reserved` name";
738
739        /// Duplicate interaction name in one interaction body — an `interface`
740        /// or a service's inline shape (ridl §14.1, §16.4). Emitted by the
741        /// checker (E2 task 5); lowering keeps the first declaration only, and
742        /// the diagnostic's secondary label points at it.
743        RIDL_402 = "RIDL-402", Error,
744            "duplicate interaction name in one interaction body";
745
746        /// Behaviour, user-interaction, or architecture declaration in a ridl
747        /// context (ridl §16.4): a reserved word of the uxdl/rmdl/rsdl profiles at
748        /// declaration-start position in a `.ridl` parse. Emitted by the parser
749        /// (E2 task 2).
750        RIDL_403 = "RIDL-403", Error,
751            "behaviour, user-interaction, or architecture declaration in a ridl context";
752
753        /// A query named like a mutation — `set…`, `reset…`, and the rest of the
754        /// mutating verb set (ridl §7.2, §16.4): a state-mutating request belongs
755        /// to `command`. Warning. Emitted by the lint pass (E2 task 19).
756        RIDL_404 = "RIDL-404", Warning,
757            "query named like a mutation";
758
759        /// One `error` type used as the failure arm of queries in three or more
760        /// distinct interfaces — the "shared across unrelated failure domains"
761        /// heuristic (ridl §10.1, §16.4). Info. Emitted by the lint pass (E2 task
762        /// 19); the threshold is three, so two interfaces stay silent.
763        RIDL_405 = "RIDL-405", Info,
764            "one `error` type shared across unrelated failure domains";
765
766        /// A `signal` or `event` payload whose struct re-declares envelope
767        /// metadata — publication time or a frame counter (ridl §3.1, §16.4). Info;
768        /// domain time distinct from transport time is legitimate, so the message
769        /// says so. Emitted by the lint pass (E2 task 19).
770        RIDL_406 = "RIDL-406", Info,
771            "payload struct re-declares envelope metadata";
772
773        /// An interaction's, struct field's or union arm's ordinal (typl §7.4)
774        /// changed against a published baseline snapshot
775        /// (ridl §11, general form §6.3). Warning. Emitted by the `ridl check`
776        /// desk check (E2 task 18), never by the compiler: the comparison
777        /// reads a workspace-local baseline, which is outside `ridlc`'s
778        /// source→IR function (ADR-0008 decisions 9 and 13). A field or arm
779        /// added or removed draws no warning here, and neither does any
780        /// ordinal change in the same edit as an addition or a removal —
781        /// `ridl diff` reports both in CI. A reorder, or a `reserved`
782        /// tombstone added or moved, with the same live fields or arms on both
783        /// sides, does draw it.
784        /// An enum value's or enum-set bit's reorder is not a change (typl
785        /// §8, §9) and does not draw this warning either (driftsys/ridl#335).
786        RIDL_407 = "RIDL-407", Warning,
787            "interaction, struct field, or union arm ordinal changed against the published \
788             baseline";
789
790        /// An interaction of an interface body the baseline being replaced
791        /// declares is not carried forward as the tombstone rule requires
792        /// (ridl §11), in one of four shapes: it is gone from the source with
793        /// no `reserved` tombstone; the source retires it with a tombstone at
794        /// an ordinal other than its own; the baseline already retired it and
795        /// the source dropped the tombstone; or the source declares a live
796        /// interaction under the name a tombstone retires. Error. Emitted by
797        /// `ridl baseline` alone, for the interaction level only — a whole
798        /// interface or service removed, and a named-form service's shape
799        /// list, are outside it. Publication is the last point at which the
800        /// change can still be refused, because the snapshot about to be
801        /// overwritten is the only record that the ordinal was ever taken.
802        /// Distinct from RIDL-407, which is the desk-time warning that an
803        /// ordinal moved and which neither classifies nor gates.
804        RIDL_408 = "RIDL-408", Error,
805            "interaction removed, its tombstone dropped or moved, or its retired name redeclared";
806
807        /// A live entry of the package's `interfaces.lock` names an interface
808        /// the package no longer declares (lock design §4, §8) — the interface
809        /// was renamed or removed, and the lock does not record which. Error.
810        /// Emitted by the checker on the entry's own line of the lock file,
811        /// `ridlc` and `ridl` alike. The fix is `ridl lock <pkg> --retire Old`
812        /// when the interface is gone, or `ridl lock <pkg> --rename Old=New`
813        /// when a declaration without an entry is the same interface under a
814        /// new name; the message names only `--retire` when the package has
815        /// no declaration without an entry. `ridl check` adds a label naming
816        /// the one `--rename` command when the published baseline shows
817        /// exactly one declaration without an entry with the old interface's
818        /// shape.
819        RIDL_409 = "RIDL-409", Error,
820            "live `interfaces.lock` entry with no declaration";
821
822        /// The package's `interfaces.lock` is malformed (lock design §2, §8):
823        /// no `next` line, `next` not greater than every entry's number, one
824        /// number on two entries, one live key on two entries, or a line that
825        /// does not parse — git conflict markers included. Error. Emitted by
826        /// the loader, on the offending line of the lock file itself (or at
827        /// the start of an empty file), so `ridlc` and `ridl` alike stop on
828        /// it; the package then compiles without its lock. The fix is to
829        /// resolve the conflict or restore the file from version control and
830        /// run `ridl lock`.
831        RIDL_410 = "RIDL-410", Error,
832            "`interfaces.lock` is malformed";
833
834        /// An interface in the snapshot `ridl baseline` is about to publish
835        /// carries a provisional number — a declaration with no entry in the
836        /// package's `interfaces.lock` (lock design §3, §8). A provisional
837        /// number is no identity: `ridl diff` never matches on it, so a
838        /// snapshot holding one records nothing a later comparison can hold
839        /// the interface to. Error. Emitted by `ridl baseline` alone, at the
840        /// declaration's name, for a first publication as for a replacement.
841        /// The fix is plain `ridl lock`, which allocates and records the
842        /// number, then publish.
843        RIDL_411 = "RIDL-411", Error,
844            "provisional interface number refused at publication";
845
846        /// An interface number the published baseline holds is absent from
847        /// the fresh snapshot and not among its `interfaces.lock` retired
848        /// entries (lock design §4, §8) — a lock line deleted by hand, since a
849        /// live entry with no declaration already fails the build with
850        /// RIDL-409. Publishing would lose the only record that the number was
851        /// allocated, and `next` could hand it to a later interface. Error.
852        /// Emitted by `ridl baseline` alone, for a published number other
853        /// than 0: a snapshot published before the lock existed carries 0,
854        /// which is never allocated, and is matched by name. The fix is to
855        /// restore the entry's line in `interfaces.lock` from version
856        /// control, with `retired` after the number when the interface is
857        /// gone.
858        RIDL_412 = "RIDL-412", Error,
859            "published interface number dropped without a retired entry";
860
861        /// A parameter name declared twice in one `command` or `query`
862        /// parameter list (ridl §6.1, §7.1, §16.4). Distinct from RIDL-149:
863        /// that code fires when two distinct source names collide only after
864        /// a pinned name transform, and this one fires when the two source
865        /// names are already the same, before any transform runs. Both
866        /// parameters still lower — this check reports and does not drop.
867        RIDL_413 = "RIDL-413", Error,
868            "parameter name declared twice in one parameter list";
869    }
870
871    /// The rsdl catalogue: every `RSDL-` code declared in this module, with the
872    /// severity the rsdl reference §16.1 table classifies it at. A code is
873    /// declared with the pass that raises it. The §16.2 reserved codes and the
874    /// §16.3 retired codes are never declared. `RSDL_PROFILE_CODES` in
875    /// `crates/ridlc/tests/corpus.rs` gives every code here a living example,
876    /// and `rsdl_profile_codes_match_the_catalogue` holds the two lists equal.
877    RSDL_CATALOG {
878        /// `instances` is not a parenthesised list of one or more camelCase
879        /// names — `()`, `instances = solo` (rsdl §5, §7, §16.1). Error. Raised
880        /// by the rsdl attribute check.
881        RSDL_305 = "RSDL-305", Error,
882            "`instances` is not a parenthesised list of one or more camelCase names";
883
884        /// A duplicate instance name in one component (rsdl §7, §16.1). Error.
885        /// Raised by the rsdl closure check.
886        RSDL_306 = "RSDL-306", Error,
887            "duplicate instance name in one component";
888
889        /// `Unit` written in source — as a declared instance name, or as the
890        /// instance segment of a reference (rsdl §7, §16.1). Error. Raised by
891        /// the rsdl closure check.
892        RSDL_307 = "RSDL-307", Error,
893            "`Unit` written in source";
894
895        /// A component requires an interface listed by a service it offers
896        /// (rsdl §3.2, §16.1). Error. Raised by the rsdl closure check.
897        RSDL_308 = "RSDL-308", Error,
898            "a component requires an interface listed by a service it offers";
899
900        /// The same service on two `offers` lines, or the same interface on two
901        /// `requires` lines, of one component (rsdl §3.2, §16.1). Error. Raised
902        /// by the rsdl closure check.
903        RSDL_309 = "RSDL-309", Error,
904            "the same service or interface on two lines of one component";
905
906        /// An `offers` line names something that is not a service, or nothing
907        /// (rsdl §3.2, §16.1). Error. Raised by the rsdl closure check.
908        RSDL_310 = "RSDL-310", Error,
909            "an `offers` line names something that is not a service";
910
911        /// A `requires` line names a service whose shape is a list of
912        /// interfaces; the diagnostic lists them (rsdl §3.2, §16.1). Error.
913        /// Raised by the rsdl closure check.
914        RSDL_311 = "RSDL-311", Error,
915            "a `requires` line names a service whose shape is a list of interfaces";
916
917        /// A `requires` line names something that is neither an interface nor
918        /// an inline-shape service, or nothing (rsdl §3.2, §16.1). Error. Raised
919        /// by the rsdl closure check.
920        RSDL_312 = "RSDL-312", Error,
921            "a `requires` line names neither an interface nor an inline-shape service";
922
923        /// `external` written with a value — it is a flag (rsdl §5, §16.1).
924        /// Error. Raised by the rsdl attribute check.
925        RSDL_313 = "RSDL-313", Error,
926            "`external` written with a value";
927
928        /// A closure component requires an interface that no closure service
929        /// lists — a missing provider (rsdl §8, §16.1). Error. Raised by the rsdl
930        /// resolution.
931        RSDL_403 = "RSDL-403", Error,
932            "a closure component requires an interface no closure service lists";
933
934        /// An interface listed by two services of the closure, raised for every
935        /// interface they list (rsdl §8, §16.1). Error. Raised by the rsdl
936        /// resolution.
937        RSDL_408 = "RSDL-408", Error,
938            "an interface listed by two services of the closure";
939
940        /// A `requires` resolves to a redundant provider set — an offering
941        /// component with more than one instance (rsdl §7, §16.1). Warning, not
942        /// yet realizable: the lowering proceeds. Raised by the rsdl resolution.
943        RSDL_409 = "RSDL-409", Warning,
944            "a `requires` resolves to a redundant provider set";
945
946        /// Two closure components offer one service (rsdl §8, §16.1). Error.
947        /// Raised by the rsdl resolution.
948        RSDL_502 = "RSDL-502", Error,
949            "two closure components offer one service";
950
951        /// A member line names a service by its name while a declared component
952        /// offers it; the diagnostic names the offerer (rsdl §6, §16.1). Error.
953        /// Raised by the rsdl closure check.
954        RSDL_504 = "RSDL-504", Error,
955            "a member line names a service that a declared component offers";
956
957        /// More than one `system` in the workspace (rsdl §3.1, §16.1). Error.
958        /// Raised by the rsdl closure check.
959        RSDL_601 = "RSDL-601", Error,
960            "more than one `system` in the workspace";
961
962        /// A `system` member line names nothing that is a component or a service
963        /// (rsdl §3.1, §16.1). Error. Raised by the rsdl closure check.
964        RSDL_602 = "RSDL-602", Error,
965            "a `system` member line names neither a component nor a service";
966
967        /// A name listed twice in one `system` body (rsdl §3.1, §16.1). Error.
968        /// Raised by the rsdl closure check.
969        RSDL_603 = "RSDL-603", Error,
970            "a name listed twice in one `system` body";
971
972        /// A declaration of another profile — a type, an interface, a service —
973        /// at the top level of an `.rsdl` file (rsdl §2, §16.1). Error. Raised
974        /// by the parser.
975        RSDL_604 = "RSDL-604", Error,
976            "a declaration of another profile in an `.rsdl` file";
977
978        /// An instance of a closure component with no placement in a deployment
979        /// (rsdl §9, §16.1). Error; blocks that deployment only (§13). Raised by
980        /// the rsdl placement check.
981        RSDL_701 = "RSDL-701", Error,
982            "an instance of a closure component with no placement in a deployment";
983
984        /// A placement line names a component, instance or service outside the
985        /// closure, or a name that resolves to nothing (rsdl §9, §16.1). Error.
986        /// Raised by the rsdl placement check.
987        RSDL_702 = "RSDL-702", Error,
988            "a placement line names something outside the closure, or nothing";
989
990        /// `deployment … for Y` where `Y` resolves to no declared `system`
991        /// (rsdl §3.4, §16.1). Error. Raised by the rsdl placement check.
992        RSDL_704 = "RSDL-704", Error,
993            "a deployment is `for` no declared `system`";
994
995        /// Two machines with one name in one deployment (rsdl §3.5, §16.1).
996        /// Error. Raised by the rsdl placement check.
997        RSDL_705 = "RSDL-705", Error,
998            "two machines with one name in one deployment";
999
1000        /// An instance placed twice in one deployment, also `Cruise` together
1001        /// with `Cruise.primary` (rsdl §9, §16.1). Error. Raised by the rsdl
1002        /// placement check.
1003        RSDL_706 = "RSDL-706", Error,
1004            "an instance placed twice in one deployment";
1005
1006        /// An `external` machine lists an implemented component (rsdl §9,
1007        /// §16.1). Error. Raised by the rsdl placement check.
1008        RSDL_707 = "RSDL-707", Error,
1009            "an `external` machine lists an implemented component";
1010
1011        /// Two deployments with one name in the workspace (rsdl §3.4, §16.1).
1012        /// Error. Raised by the rsdl placement check.
1013        RSDL_708 = "RSDL-708", Error,
1014            "two deployments with one name in the workspace";
1015
1016        /// A backend key whose namespace no configured backend claims (rsdl §5,
1017        /// §16.1). Warning: the key is still carried. Raised by `ridlc`, which
1018        /// knows the configured backends (plan decision P-B4).
1019        RSDL_804 = "RSDL-804", Warning,
1020            "a backend key whose namespace no configured backend claims";
1021
1022        /// A `PLATFORM` distribution holds a component whose `requires` resolves
1023        /// into an `APPLICATION` distribution — tier inversion; a distribution
1024        /// without `tier` is exempt (rsdl §3.3, §16.1). Error. Raised by the
1025        /// rsdl distribution check.
1026        RSDL_901 = "RSDL-901", Error,
1027            "a `PLATFORM` distribution requires into an `APPLICATION` distribution";
1028
1029        /// A distribution member line names something outside the closure, or
1030        /// nothing (rsdl §3.3, §16.1). Error. Raised by the rsdl distribution
1031        /// check.
1032        RSDL_903 = "RSDL-903", Error,
1033            "a distribution member line names something outside the closure, or nothing";
1034
1035        /// An implemented closure component in no distribution, while the
1036        /// workspace declares at least one (rsdl §3.3, §16.1). Error. Raised by
1037        /// the rsdl distribution check.
1038        RSDL_904 = "RSDL-904", Error,
1039            "an implemented closure component in no distribution";
1040
1041        /// A component listed by two distributions (rsdl §3.3, §16.1). Error.
1042        /// Raised by the rsdl distribution check.
1043        RSDL_905 = "RSDL-905", Error,
1044            "a component listed by two distributions";
1045
1046        /// A name listed twice in one distribution body (rsdl §3.3, §16.1).
1047        /// Error. Raised by the rsdl distribution check.
1048        RSDL_906 = "RSDL-906", Error,
1049            "a name listed twice in one distribution body";
1050
1051        /// An `external` component listed by a distribution (rsdl §3.3, §16.1).
1052        /// Error. Raised by the rsdl distribution check.
1053        RSDL_907 = "RSDL-907", Error,
1054            "an `external` component listed by a distribution";
1055
1056        /// A `tier` value other than `PLATFORM` or `APPLICATION` (rsdl §5,
1057        /// §16.1). Error. Raised by the rsdl attribute check.
1058        RSDL_908 = "RSDL-908", Error,
1059            "`tier` value other than `PLATFORM` or `APPLICATION`";
1060    }
1061
1062    /// The manifest catalogue (ADR-0007 decision 2): the manifest `0xx` codes the
1063    /// `ridl.toml` parser (E1.5) and the package loader (E1.3) emit, and the
1064    /// distribution `1xx` codes the import materializer (E1.6) emits. Listed here
1065    /// even for `MANI-004`, whose emission site is the loader rather than the
1066    /// standalone parser, so the error index (E4.2) has one authoritative source.
1067    MANI_CATALOG {
1068        /// The `ridl.toml` text is not valid TOML.
1069        MANI_001 = "MANI-001", Error,
1070            "invalid manifest TOML";
1071
1072        /// The manifest declares both `[package]` and `[workspace]`; the two modes
1073        /// are mutually exclusive (ADR-0002 §4).
1074        MANI_002 = "MANI-002", Error,
1075            "manifest declares both `[package]` and `[workspace]`";
1076
1077        /// The manifest declares neither `[package]` nor `[workspace]` (ADR-0002 §4).
1078        MANI_003 = "MANI-003", Error,
1079            "manifest declares neither `[package]` nor `[workspace]`";
1080
1081        /// A workspace member's own manifest declares `[workspace]`; nested
1082        /// workspaces are forbidden (ADR-0002 §4). Defined here, but emitted by the
1083        /// package loader (E1.3, task 8) when a member manifest is read — a single
1084        /// manifest parsed in isolation cannot know it is a member.
1085        MANI_004 = "MANI-004", Error,
1086            "nested workspace: a member manifest declares `[workspace]`";
1087
1088        /// An unrecognized key in the manifest or one of its sections (warning).
1089        MANI_005 = "MANI-005", Warning,
1090            "unknown manifest key";
1091
1092        /// The package name is not lowercase dot-separated segments (ADR-0002 §1).
1093        MANI_006 = "MANI-006", Error,
1094            "invalid package name";
1095
1096        /// An `[imports]` value is not a valid import URL.
1097        MANI_007 = "MANI-007", Error,
1098            "invalid import URL";
1099
1100        /// A workspace member directory is missing or has no `ridl.toml`. Emitted
1101        /// by the package loader (E1.3), which is where member paths are resolved
1102        /// against the filesystem.
1103        MANI_008 = "MANI-008", Error,
1104            "workspace member directory has no `ridl.toml`";
1105
1106        /// The manifest `[defaults].timing` value is not a valid range (ridl §9.1,
1107        /// ADR-0008 decision 13). The manifest parser stores the raw string
1108        /// unparsed — `ridl-core` cannot depend on `ridl-sem` — so the checker
1109        /// parses it and emits this code (E2 task 9).
1110        MANI_009 = "MANI-009", Error,
1111            "invalid `[defaults].timing` value";
1112
1113        /// A remote import could not be fetched (network failure, a non-2xx HTTP
1114        /// status, or a value that is not a fetchable `http(s)` URL).
1115        MANI_101 = "MANI-101", Error,
1116            "remote import fetch failed";
1117
1118        /// Fetched content hashes to a value that does not match the SHA-256 the
1119        /// lockfile pins for the same URL (ADR-0002 §7).
1120        MANI_102 = "MANI-102", Error,
1121            "fetched content hash does not match the lockfile";
1122
1123        /// `--frozen` was requested but the lockfile has no entry for a remote
1124        /// import; a frozen build never regenerates the lockfile (ADR-0002 §7).
1125        MANI_103 = "MANI-103", Error,
1126            "`--frozen`: no lockfile entry for a remote import";
1127
1128        /// `--frozen` was requested and a lockfile-pinned import is not present in
1129        /// the cache; a frozen build never fetches (ADR-0002 §7).
1130        MANI_104 = "MANI-104", Error,
1131            "`--frozen`: a lockfile-pinned import is not cached";
1132    }
1133}
1134
1135/// A diagnostic's severity. Warnings and info diagnostics arrive with later
1136/// passes; every code the E1.10 pipeline emits is an [`Error`](Severity::Error).
1137#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1138pub enum Severity {
1139    Error,
1140    Warning,
1141    Info,
1142}
1143
1144/// An interned file id, issued by [`SourceMap::file_id`]. It indexes the file's
1145/// path and text inside the [`SourceMap`], which the renderer reads to draw the
1146/// source snippet.
1147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
1148#[serde(transparent)]
1149pub struct FileId(u32);
1150
1151impl FileId {
1152    /// A sentinel id for a diagnostic that is not tied to any source file. The
1153    /// lockfile, cache, and fetch diagnostics (MANI-1xx) concern a URL rather
1154    /// than a byte span, so they carry this id; [`render`](render()) draws them as a bare
1155    /// coded message with no source snippet. No [`SourceMap`] ever issues it.
1156    pub const DETACHED: FileId = FileId(u32::MAX);
1157}
1158
1159/// A source location: a byte range inside a specific file. The range is a
1160/// `rowan::TextRange` — the same coordinate space parse and semantic passes work
1161/// in — so an offset never has to be translated on the way into a diagnostic.
1162#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1163pub struct Span {
1164    pub file: FileId,
1165    #[serde(serialize_with = "serialize_text_range")]
1166    pub range: TextRange,
1167}
1168
1169/// Serializes a `rowan::TextRange` as `{ "start": u32, "end": u32 }`, keeping
1170/// the byte offsets readable and exact in JSON snapshots.
1171fn serialize_text_range<S: Serializer>(
1172    range: &TextRange,
1173    serializer: S,
1174) -> Result<S::Ok, S::Error> {
1175    use serde::ser::SerializeStruct;
1176    let mut state = serializer.serialize_struct("TextRange", 2)?;
1177    state.serialize_field("start", &u32::from(range.start()))?;
1178    state.serialize_field("end", &u32::from(range.end()))?;
1179    state.end()
1180}
1181
1182/// A secondary annotation: a span with a message, drawn under the source
1183/// alongside the primary span.
1184#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1185pub struct Label {
1186    pub span: Span,
1187    pub message: String,
1188}
1189
1190/// A suggested edit: replace the text at `span` with `replacement`. `label`
1191/// describes the fix for a human. Rendered as a note under the diagnostic; a
1192/// later LSP task maps it to a code action.
1193#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1194pub struct FixIt {
1195    pub span: Span,
1196    pub replacement: String,
1197    pub label: String,
1198}
1199
1200/// One coded diagnostic. `primary` is the main span the message points at;
1201/// `labels` are secondary annotations; `fixits` are suggested edits.
1202#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1203pub struct Diagnostic {
1204    pub code: DiagCode,
1205    pub severity: Severity,
1206    pub message: String,
1207    pub primary: Span,
1208    pub labels: Vec<Label>,
1209    pub fixits: Vec<FixIt>,
1210}
1211
1212/// The path and text of one interned file.
1213#[derive(Debug)]
1214struct SourceEntry {
1215    path: String,
1216    text: String,
1217}
1218
1219/// The file table the renderer reads: it maps every [`FileId`] to the path and
1220/// text a diagnostic's spans point into. Ids are interned by path, so asking for
1221/// the same path twice returns the same id.
1222#[derive(Debug, Default)]
1223pub struct SourceMap {
1224    files: Vec<SourceEntry>,
1225}
1226
1227impl SourceMap {
1228    /// An empty source map.
1229    pub fn new() -> Self {
1230        Self::default()
1231    }
1232
1233    /// The [`FileId`] for `path`, interning `path` and `text` on first sight.
1234    /// A pass holding a file's path and text calls this to stamp its spans.
1235    pub fn file_id(&mut self, path: &str, text: &str) -> FileId {
1236        if let Some(index) = self.files.iter().position(|entry| entry.path == path) {
1237            return FileId(index as u32);
1238        }
1239        let id = FileId(self.files.len() as u32);
1240        self.files.push(SourceEntry {
1241            path: path.to_string(),
1242            text: text.to_string(),
1243        });
1244        id
1245    }
1246
1247    /// The path an interned [`FileId`] stands for, or `None` for an id this map
1248    /// never issued (including [`FileId::DETACHED`]). This is the reverse of
1249    /// [`file_id`](Self::file_id): a caller holding a diagnostic's `FileId` reads
1250    /// back the file it points at without probing candidate paths.
1251    pub fn path(&self, id: FileId) -> Option<&str> {
1252        self.files
1253            .get(id.0 as usize)
1254            .map(|entry| entry.path.as_str())
1255    }
1256
1257    /// The text an interned [`FileId`] stands for, or `None` for an id this map
1258    /// never issued (including [`FileId::DETACHED`]).
1259    pub fn text(&self, id: FileId) -> Option<&str> {
1260        self.files
1261            .get(id.0 as usize)
1262            .map(|entry| entry.text.as_str())
1263    }
1264}
1265
1266/// A 1-based line and column. The column counts Unicode scalar values — Rust
1267/// `char`s — not UTF-8 bytes and not the UTF-16 code units LSP positions use.
1268#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
1269pub struct LineCol {
1270    pub line: u32,
1271    pub column: u32,
1272}
1273
1274/// The line and column of a byte `offset` into `text`. An offset past the end
1275/// of the text, or inside a multi-byte character, is moved back to the nearest
1276/// character boundary at or before it.
1277pub fn line_col(text: &str, offset: TextSize) -> LineCol {
1278    let mut offset = usize::from(offset).min(text.len());
1279    while !text.is_char_boundary(offset) {
1280        offset -= 1;
1281    }
1282    let before = &text[..offset];
1283    let line = before.matches('\n').count() as u32 + 1;
1284    let column = match before.rfind('\n') {
1285        Some(newline) => before[newline + 1..].chars().count(),
1286        None => before.chars().count(),
1287    } as u32
1288        + 1;
1289    LineCol { line, column }
1290}
1291
1292/// A span in the JSON diagnostic contract: the file's path as registered in the
1293/// [`SourceMap`] and 1-based start and end positions. `end` is exclusive: the
1294/// position one past the last character in the span, not the position of the
1295/// last character itself.
1296#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1297pub struct JsonSpan {
1298    pub path: String,
1299    pub start: LineCol,
1300    pub end: LineCol,
1301}
1302
1303/// A fix-it in the JSON diagnostic contract, verbatim from the compiler.
1304#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1305pub struct JsonFixIt {
1306    pub label: String,
1307    pub replacement: String,
1308    pub span: JsonSpan,
1309}
1310
1311/// A label in the JSON diagnostic contract, verbatim from the compiler.
1312#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1313pub struct JsonLabel {
1314    pub message: String,
1315    pub span: JsonSpan,
1316}
1317
1318/// One diagnostic in the JSON contract `ridl check --format json` and the MCP
1319/// `ridl_check` tool emit. This is the first agent-facing diagnostic contract
1320/// (ADR-0005 §7): a change to its shape is a change to an external contract.
1321/// `code` passes the diagnostic's [`DiagCode`] through verbatim, including the
1322/// empty string a diagnostic with no assigned catalogue code carries; the
1323/// field is always present, never omitted. `labels` passes the diagnostic's
1324/// secondary annotations through verbatim, in the order the diagnostic holds
1325/// them; the array is always present, empty when the diagnostic carries none.
1326#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1327pub struct JsonDiagnostic {
1328    pub code: String,
1329    pub severity: String,
1330    pub message: String,
1331    pub span: JsonSpan,
1332    pub labels: Vec<JsonLabel>,
1333    pub fixes: Vec<JsonFixIt>,
1334}
1335
1336fn json_span(span: Span, sources: &SourceMap) -> JsonSpan {
1337    let path = sources.path(span.file).unwrap_or("").to_string();
1338    let text = sources.text(span.file).unwrap_or("");
1339    JsonSpan {
1340        path,
1341        start: line_col(text, span.range.start()),
1342        end: line_col(text, span.range.end()),
1343    }
1344}
1345
1346fn severity_name(severity: Severity) -> &'static str {
1347    match severity {
1348        Severity::Error => "error",
1349        Severity::Warning => "warning",
1350        Severity::Info => "info",
1351    }
1352}
1353
1354/// Projects `diagnostics` onto the JSON contract, resolving every span through
1355/// `sources`.
1356pub fn to_json(diagnostics: &[Diagnostic], sources: &SourceMap) -> Vec<JsonDiagnostic> {
1357    diagnostics
1358        .iter()
1359        .map(|diagnostic| JsonDiagnostic {
1360            code: diagnostic.code.0.to_string(),
1361            severity: severity_name(diagnostic.severity).to_string(),
1362            message: diagnostic.message.clone(),
1363            span: json_span(diagnostic.primary, sources),
1364            labels: diagnostic
1365                .labels
1366                .iter()
1367                .map(|label| JsonLabel {
1368                    message: label.message.clone(),
1369                    span: json_span(label.span, sources),
1370                })
1371                .collect(),
1372            fixes: diagnostic
1373                .fixits
1374                .iter()
1375                .map(|fixit| JsonFixIt {
1376                    label: fixit.label.clone(),
1377                    replacement: fixit.replacement.clone(),
1378                    span: json_span(fixit.span, sources),
1379                })
1380                .collect(),
1381        })
1382        .collect()
1383}
1384
1385/// Remaps per-package diagnostics onto a renderer's [`SourceMap`] ids.
1386///
1387/// The package-scoped passes (`resolve_package`, `check_package` in
1388/// `ridl-sem`) stamp their spans with a [`FileId`] that indexes the package's
1389/// `files` **in order** — they run inside salsa queries and cannot share the
1390/// caller's [`SourceMap`]. A renderer first interns each package file into its
1391/// own map (collecting the issued ids in the same file order), then calls this
1392/// to rewrite every span onto those ids. [`FileId::DETACHED`] spans and any
1393/// index past `render_ids` are left untouched.
1394pub fn remap_diagnostics(
1395    diagnostics: impl IntoIterator<Item = Diagnostic>,
1396    render_ids: &[FileId],
1397) -> Vec<Diagnostic> {
1398    let remap_file =
1399        |file: FileId| -> FileId { render_ids.get(file.0 as usize).copied().unwrap_or(file) };
1400    diagnostics
1401        .into_iter()
1402        .map(|mut diagnostic| {
1403            diagnostic.primary.file = remap_file(diagnostic.primary.file);
1404            for label in &mut diagnostic.labels {
1405                label.span.file = remap_file(label.span.file);
1406            }
1407            for fixit in &mut diagnostic.fixits {
1408                fixit.span.file = remap_file(fixit.span.file);
1409            }
1410            diagnostic
1411        })
1412        .collect()
1413}
1414
1415/// One row of a diagnostic catalogue: a code, its default severity, and a short
1416/// human summary. The catalogue is the static SSOT the error index (E4.2) reads;
1417/// the per-diagnostic [`Severity`] a pass emits is set independently.
1418#[derive(Debug, Clone, Copy)]
1419pub struct CatalogEntry {
1420    pub code: DiagCode,
1421    pub severity: Severity,
1422    pub summary: &'static str,
1423}
1424
1425/// Polishes a raw parser message into the house diagnostic style —
1426/// description-first, with backticked names (fixes issue #102). Most parser
1427/// messages are already house-style and pass through unchanged; the parser's
1428/// `expect` path emits a `Debug`-shaped token name (`expected RBracket`), which
1429/// this maps to a backticked glyph (`` expected `]` ``).
1430///
1431/// Keeping the raw parser message as the input leaves `ridl-syntax` and its
1432/// tests untouched — they assert on codes and ranges, not message text — while
1433/// the rendered diagnostics still read in one consistent style.
1434pub fn house_style_message(raw: &str) -> String {
1435    if let Some(token) = raw.strip_prefix("expected ")
1436        && let Some(glyph) = punctuation_glyph(token)
1437    {
1438        return format!("expected {glyph}");
1439    }
1440    raw.to_string()
1441}
1442
1443/// The backticked glyph for a punctuation or operator `SyntaxKind` `Debug`
1444/// name, or `None` when the name is not a known single-glyph token. Covers every
1445/// kind the parser can name in a FORM-101 `expected` message, so the mapping
1446/// stays correct if new `expect` call sites are added — an invariant the
1447/// `every_expectable_token_has_a_glyph` test enforces against the parser source.
1448fn punctuation_glyph(debug_name: &str) -> Option<&'static str> {
1449    Some(match debug_name {
1450        "Colon" => "`:`",
1451        "Eq" => "`=`",
1452        "Semicolon" => "`;`",
1453        "Comma" => "`,`",
1454        "LBracket" => "`[`",
1455        "RBracket" => "`]`",
1456        "LBrace" => "`{`",
1457        "RBrace" => "`}`",
1458        "LParen" => "`(`",
1459        "RParen" => "`)`",
1460        "DotDot" => "`..`",
1461        "Dot" => "`.`",
1462        "Question" => "`?`",
1463        "At" => "`@`",
1464        "Pipe" => "`|`",
1465        // `>` closes a stream type `<T>` (ridl reference §12), which is the
1466        // one operator token the parser reaches through `expect`.
1467        "Gt" => "`>`",
1468        _ => return None,
1469    })
1470}
1471
1472impl SourceMap {
1473    /// The interned files, in id order — the renderer replays them into a
1474    /// `codespan_reporting` file table so `FileId(i)` lines up with codespan id
1475    /// `i`.
1476    pub(crate) fn iter_files(&self) -> impl Iterator<Item = (&str, &str)> {
1477        self.files
1478            .iter()
1479            .map(|entry| (entry.path.as_str(), entry.text.as_str()))
1480    }
1481}
1482
1483#[cfg(test)]
1484mod tests {
1485    use super::*;
1486
1487    #[test]
1488    fn source_map_interns_by_path() {
1489        let mut map = SourceMap::new();
1490        let a = map.file_id("a.typl", "type A: m");
1491        let b = map.file_id("b.typl", "type B: s");
1492        let a_again = map.file_id("a.typl", "type A: m");
1493        assert_ne!(a, b, "distinct paths get distinct ids");
1494        assert_eq!(a, a_again, "the same path interns to the same id");
1495    }
1496
1497    #[test]
1498    fn source_map_path_reverses_file_id() {
1499        let mut map = SourceMap::new();
1500        let a = map.file_id("a.typl", "type A: m");
1501        let b = map.file_id("b.typl", "type B: s");
1502        assert_eq!(map.path(a), Some("a.typl"));
1503        assert_eq!(map.path(b), Some("b.typl"));
1504        assert_eq!(
1505            map.path(FileId::DETACHED),
1506            None,
1507            "a detached id has no path"
1508        );
1509        assert_eq!(
1510            map.path(FileId(2)),
1511            None,
1512            "an id the map never issued has no path",
1513        );
1514    }
1515
1516    #[test]
1517    fn remap_diagnostics_rewrites_package_relative_ids() {
1518        // A render map that already interned an unrelated file, so the render
1519        // ids do not coincide with the package-relative indices.
1520        let mut render = SourceMap::new();
1521        let _other = render.file_id("other.typl", "");
1522        let a = render.file_id("pkg/a.typl", "type A: m");
1523        let b = render.file_id("pkg/b.typl", "type B: s");
1524        let render_ids = vec![a, b];
1525
1526        let span = |file: FileId| Span {
1527            file,
1528            range: TextRange::default(),
1529        };
1530        let diagnostic = |file: FileId| Diagnostic {
1531            code: DiagCode::TYPL_009,
1532            severity: Severity::Error,
1533            message: "duplicate declaration of `X`".to_string(),
1534            primary: span(file),
1535            labels: vec![Label {
1536                span: span(file),
1537                message: "first declared here".to_string(),
1538            }],
1539            fixits: Vec::new(),
1540        };
1541
1542        // Package-relative ids 0 and 1, plus a detached diagnostic.
1543        let mut pass_map = SourceMap::new();
1544        let pkg_a = pass_map.file_id("pkg/a.typl", "type A: m");
1545        let pkg_b = pass_map.file_id("pkg/b.typl", "type B: s");
1546        let remapped = remap_diagnostics(
1547            vec![
1548                diagnostic(pkg_a),
1549                diagnostic(pkg_b),
1550                diagnostic(FileId::DETACHED),
1551            ],
1552            &render_ids,
1553        );
1554
1555        assert_eq!(remapped[0].primary.file, a);
1556        assert_eq!(remapped[0].labels[0].span.file, a);
1557        assert_eq!(remapped[1].primary.file, b);
1558        assert_eq!(
1559            remapped[2].primary.file,
1560            FileId::DETACHED,
1561            "a detached diagnostic stays detached",
1562        );
1563    }
1564
1565    /// The rendered text for every `SyntaxKind` the parser hands to `expect`.
1566    ///
1567    /// One row per kind in the reachable set the
1568    /// `every_expectable_token_has_a_glyph` test derives, so a wrong glyph is
1569    /// caught here and a missing one is caught there.
1570    #[test]
1571    fn house_style_rewrites_debug_token_names() {
1572        assert_eq!(house_style_message("expected RBracket"), "expected `]`");
1573        assert_eq!(house_style_message("expected Colon"), "expected `:`");
1574        assert_eq!(house_style_message("expected Eq"), "expected `=`");
1575        assert_eq!(house_style_message("expected Semicolon"), "expected `;`");
1576        assert_eq!(house_style_message("expected RParen"), "expected `)`");
1577        assert_eq!(house_style_message("expected DotDot"), "expected `..`");
1578        // Reached since stream types landed: `query a(): <Speed` with no `>`.
1579        assert_eq!(house_style_message("expected Gt"), "expected `>`");
1580    }
1581
1582    /// Every `SyntaxKind` the parser hands to `expect` has a glyph.
1583    ///
1584    /// `expect` is the one call site in the workspace that formats a
1585    /// `SyntaxKind` `Debug` name into a diagnostic message, and every caller of
1586    /// [`house_style_message`] feeds it a parser message, so the set of kinds
1587    /// that can reach [`punctuation_glyph`] is exactly the set of literal
1588    /// arguments `expect` is called with. A kind outside the table renders as
1589    /// its raw `Debug` name — `expected Gt` reached users this way, because
1590    /// stream types added an `expect(SyntaxKind::Gt)` call site and nothing
1591    /// tied the two files together.
1592    ///
1593    /// The first assertion pins that single-producer premise, and pins it
1594    /// **workspace-wide**: a second `Debug`-shaped emitter anywhere would widen
1595    /// the reachable set past what the scan below reads, so it has to fail
1596    /// rather than pass silently. Reading only the parser would leave the
1597    /// premise's own scope unchecked — the same shape of gap as the one this
1598    /// test exists to close.
1599    #[test]
1600    fn every_expectable_token_has_a_glyph() {
1601        const CALL: &str = ".expect(SyntaxKind::";
1602
1603        let root = workspace_root();
1604        let mut sources = Vec::new();
1605        collect_rust_sources(&root, &mut sources);
1606        assert!(
1607            sources.len() >= 60,
1608            "the walk found only {} `.rs` files under {} — it is not reaching \
1609             the workspace",
1610            sources.len(),
1611            root.display(),
1612        );
1613
1614        let parser = root.join("crates/ridl-syntax/src/parser.rs");
1615        let emitters: Vec<String> = sources
1616            .iter()
1617            .filter(|path| {
1618                let text = std::fs::read_to_string(path)
1619                    .unwrap_or_else(|err| panic!("cannot read {}: {err}", path.display()));
1620                let stripped = strip_line_comments(&text);
1621                stripped
1622                    .match_indices(r#""expected {"#)
1623                    .any(|(at, matched)| is_whole_debug_message(&stripped[at + matched.len()..]))
1624            })
1625            .map(|path| path.display().to_string())
1626            .collect();
1627        assert_eq!(
1628            emitters,
1629            vec![parser.display().to_string()],
1630            "the workspace no longer has exactly one message that is a \
1631             `Debug`-formatted token name and nothing else, so the reachable \
1632             kinds are no longer just `expect`'s arguments in the parser. Either \
1633             route the new emitter through `expect`, or widen the scan below to \
1634             read its argument too",
1635        );
1636
1637        let text = std::fs::read_to_string(&parser)
1638            .unwrap_or_else(|err| panic!("cannot read {}: {err}", parser.display()));
1639        let despaced: String = strip_line_comments(&text)
1640            .chars()
1641            .filter(|c| !c.is_whitespace())
1642            .collect();
1643        let mut expectable = std::collections::BTreeSet::new();
1644        for (at, _) in despaced.match_indices(CALL) {
1645            let rest = &despaced[at + CALL.len()..];
1646            let end = rest
1647                .find(')')
1648                .expect("an `expect` call closes its parenthesis");
1649            expectable.insert(rest[..end].to_string());
1650        }
1651
1652        assert!(
1653            expectable.len() >= 7,
1654            "the scan found only {} expectable kinds in {} — it is not reading \
1655             the call sites",
1656            expectable.len(),
1657            parser.display(),
1658        );
1659        for kind in &expectable {
1660            assert!(
1661                punctuation_glyph(kind).is_some(),
1662                "the parser can emit `expected {kind}`, which renders the raw \
1663                 `Debug` name to the user. Add `{kind}` to `punctuation_glyph`.",
1664            );
1665        }
1666    }
1667
1668    #[test]
1669    fn house_style_passes_through_already_styled_messages() {
1670        // Already description-first with backticks — unchanged.
1671        assert_eq!(house_style_message("expected a name"), "expected a name");
1672        assert_eq!(house_style_message("unclosed `{`"), "unclosed `{`");
1673        assert_eq!(
1674            house_style_message("missing `package` declaration"),
1675            "missing `package` declaration",
1676        );
1677    }
1678
1679    /// Every catalogue entry is well formed, every catalogue is sorted, and no
1680    /// code is declared twice.
1681    ///
1682    /// This is what is left to check once [`diag_codes!`] produces the
1683    /// catalogues. Completeness is structural — the constant and its entry come
1684    /// out of the same line — so the assertions here cover only the properties
1685    /// the expansion does not fix. There is deliberately no expected list of
1686    /// codes: comparing a catalogue against a second hand-written list is the
1687    /// guard this change removed.
1688    /// A retired code is never declared again (ADR-0008 decision 13): every
1689    /// number in [`RETIRED_RIDL_CODES`] stays out of the `RIDL-` catalogue.
1690    #[test]
1691    fn retired_ridl_codes_are_never_redeclared() {
1692        for entry in RIDL_CATALOG {
1693            let code = entry.code.as_str();
1694            let number: u16 = code
1695                .strip_prefix("RIDL-")
1696                .and_then(|digits| digits.parse().ok())
1697                .unwrap_or_else(|| panic!("`{code}` is not spelled `RIDL-NNN`"));
1698            assert!(
1699                !RETIRED_RIDL_CODES.contains(&number),
1700                "`{code}` is retired and must not be declared again",
1701            );
1702        }
1703    }
1704
1705    #[test]
1706    fn catalog_entries_are_well_formed_ordered_and_unique() {
1707        let mut seen: Vec<&str> = Vec::new();
1708        for (name, catalog) in ALL_CATALOGS {
1709            let prefix = name
1710                .strip_suffix("_CATALOG")
1711                .unwrap_or_else(|| panic!("`{name}` is not named `<PREFIX>_CATALOG`"));
1712            let mut previous = "";
1713            for entry in *catalog {
1714                let code = entry.code.as_str();
1715                let (written_prefix, number) = code
1716                    .split_once('-')
1717                    .unwrap_or_else(|| panic!("`{code}` is not spelled `PREFIX-NNN`"));
1718                assert_eq!(
1719                    written_prefix, prefix,
1720                    "`{code}` is listed in {name}, which holds the `{prefix}-` namespace",
1721                );
1722                assert!(
1723                    number.len() == 3 && number.bytes().all(|byte| byte.is_ascii_digit()),
1724                    "`{code}` does not carry a three-digit number",
1725                );
1726                assert!(!entry.summary.is_empty(), "`{code}` has an empty summary");
1727                // Codes in one catalogue share a prefix and a three-digit
1728                // number, so byte order is numeric order.
1729                assert!(
1730                    previous < code,
1731                    "{name} is out of order: `{previous}` is listed before `{code}`",
1732                );
1733                previous = code;
1734                assert!(
1735                    !seen.contains(&code),
1736                    "`{code}` is declared in more than one catalogue",
1737                );
1738                seen.push(code);
1739            }
1740        }
1741        // Width. The loops above say nothing if `ALL_CATALOGS` is ever empty.
1742        // The macro cannot produce an empty one, but a floor makes a vacuous
1743        // pass unreachable rather than merely unlikely, and codes are never
1744        // withdrawn (ADR-0007 decision 2), so the bound only gets safer.
1745        assert!(
1746            seen.len() >= 90,
1747            "only {} codes reached the catalogues — the guards below are \
1748             checking almost nothing",
1749            seen.len(),
1750        );
1751    }
1752
1753    /// Each constant's name is the code string it expands to, with `-` written
1754    /// `_`.
1755    ///
1756    /// [`diag_codes!`] takes the two side by side — `TYPL_007 = "TYPL-007"` — so
1757    /// a typo can still pair a name with another code's string, and every
1758    /// emission through that constant would then render the wrong code.
1759    /// `CODE_CONSTANT_NAMES` comes out of the same entries, so this compares the
1760    /// expansion against itself and not against a list someone maintains.
1761    #[test]
1762    fn each_constant_name_is_the_code_it_expands_to() {
1763        for (name, code) in CODE_CONSTANT_NAMES {
1764            assert_eq!(
1765                &name.replace('_', "-"),
1766                code,
1767                "`DiagCode::{name}` expands to `{code}`",
1768            );
1769        }
1770        assert!(CODE_CONSTANT_NAMES.len() >= 90, "the entry list went empty");
1771    }
1772
1773    /// The two namespace-wide severity rules: every FORM code is an error, and
1774    /// every MANI code is an error but the unknown-key warning.
1775    ///
1776    /// Neither rule enumerates codes, so neither is a shadow list — one states a
1777    /// property of a whole namespace, the other adds a single named exception.
1778    /// TYPL and RIDL have no such rule: their severities are per-code, set by
1779    /// the reference §16 tables, and writing them out here would rebuild exactly
1780    /// the second list this change removed. A wrong severity on a TYPL or RIDL
1781    /// entry is not caught by anything in this module.
1782    #[test]
1783    fn form_and_mani_severities_follow_their_namespace_rule() {
1784        for entry in FORM_CATALOG {
1785            assert_eq!(
1786                entry.severity,
1787                Severity::Error,
1788                "every FORM code is an error, but {} is not",
1789                entry.code.as_str(),
1790            );
1791        }
1792        for entry in MANI_CATALOG {
1793            let expected = if entry.code == DiagCode::MANI_005 {
1794                Severity::Warning
1795            } else {
1796                Severity::Error
1797            };
1798            assert_eq!(
1799                entry.severity,
1800                expected,
1801                "unexpected severity for {}",
1802                entry.code.as_str(),
1803            );
1804        }
1805    }
1806
1807    /// Every `"PREFIX-NNN"` string literal in the workspace's Rust sources names
1808    /// a catalogued code.
1809    ///
1810    /// This is the half [`diag_codes!`] cannot reach, and it is not a handful of
1811    /// call sites that forgot to use the type — it is a layering fact.
1812    /// `crates/ridl-syntax` cannot reference [`DiagCode`] at all: `ridl-core`
1813    /// depends on `ridl-syntax`, so the edge cannot run the other way, and
1814    /// `SyntaxError::code` is a `&'static str` by construction. Every code the
1815    /// lexer and parser emit is therefore a bare string literal — 11 distinct
1816    /// codes across 74 call sites when this guard was written. Five of them have
1817    /// no `DiagCode::` reference anywhere and their constants are dead
1818    /// declarations (FORM-005, FORM-104, FORM-105, RIDL-403, TYPL-304); TYPL-303
1819    /// had no constant at all until this change added one. Repairing that means
1820    /// moving the codes somewhere both crates can see, which is its own change
1821    /// (issue #172).
1822    ///
1823    /// **What this catches.** A code emitted, asserted, or declared anywhere in
1824    /// the workspace's `.rs` files that no catalogue lists — a new parser
1825    /// diagnostic included, verified by renaming the parser's TYPL-303 emission
1826    /// and watching this fail and name the file.
1827    ///
1828    /// **What this does not catch**, and must not be read as covering:
1829    ///
1830    /// - a code assembled rather than spelled: `concat!("TYPL-", "303")`, or one
1831    ///   built at run time. The scan is textual. `diag_codes!` takes a `literal`
1832    ///   so the assembled form cannot be written inside it, and
1833    ///   `no_diagnostic_constant_is_declared_outside_the_macro` covers the
1834    ///   hand-written-constant case; a `concat!` at a *parser* emission site
1835    ///   evades both;
1836    /// - a code spelled **inside a longer literal**, such as
1837    ///   `"error[TYPL-905]: boom"`. A quote is required on both sides of the
1838    ///   code, which is what keeps prose out, and it is also what lets an
1839    ///   embedded code through;
1840    /// - a **four-digit** code, `"TYPL-9060"`. The scan takes exactly three
1841    ///   digits followed by the closing quote, matching the shape ADR-0007
1842    ///   decision 2 fixes. Neither of these two is live: an audit of all 104
1843    ///   `PREFIX-NNN` occurrences in `.rs` sources regardless of quoting found
1844    ///   the only uncatalogued ones are the reserved codes and the typl §16
1845    ///   codes named below, every one of them in prose;
1846    /// - a code written in a **comment**, which is stripped before the scan
1847    ///   runs. Nothing emits a diagnostic from a comment, and leaving comments
1848    ///   in made this file report its own prose about reserved and absent
1849    ///   codes;
1850    /// - a code written only in Markdown, in a `.typl`/`.ridl` fixture, or in a
1851    ///   snapshot. The typl reference §16 documents six codes no constant
1852    ///   declares — TYPL-107, TYPL-112, TYPL-205, and TYPL-401 to TYPL-403 — so
1853    ///   widening the scan to `.md` would fail today. That inventory belongs to
1854    ///   issue #172, not to this guard;
1855    /// - a catalogued code that nothing emits. FORM-001 to FORM-004 are declared
1856    ///   and catalogued and no pass emits them;
1857    /// - a code **withdrawn** from a catalogue. Deleting an entry deletes its
1858    ///   constant, so any code a pass emits through `DiagCode::` stops the build
1859    ///   — but a code nothing references, such as FORM-001, can be removed and
1860    ///   nothing here notices. The floor in
1861    ///   `catalog_entries_are_well_formed_ordered_and_unique` catches a bulk
1862    ///   withdrawal, not a single one;
1863    /// - a wrong severity, or a summary that describes the wrong rule, on an
1864    ///   entry that exists.
1865    #[test]
1866    fn codes_written_as_string_literals_are_all_catalogued() {
1867        let root = workspace_root();
1868        let mut sources = Vec::new();
1869        collect_rust_sources(&root, &mut sources);
1870
1871        let catalogued: std::collections::BTreeSet<&str> = ALL_CATALOGS
1872            .iter()
1873            .flat_map(|(_, catalog)| catalog.iter().map(|entry| entry.code.as_str()))
1874            .collect();
1875
1876        let mut uncatalogued: Vec<String> = Vec::new();
1877        let mut files_holding_codes = 0usize;
1878        let mut codes_outside_this_module: std::collections::BTreeSet<String> =
1879            std::collections::BTreeSet::new();
1880
1881        for path in &sources {
1882            let text = std::fs::read_to_string(path)
1883                .unwrap_or_else(|err| panic!("cannot read {}: {err}", path.display()));
1884            // Comments first: a diagnostic is never emitted from one, and prose
1885            // about a code that is deliberately absent — a reserved number, a
1886            // worked example of the shape this file rejects — would otherwise
1887            // be reported as an escape.
1888            let text = strip_line_comments(&text);
1889            let literals = code_literals(&text);
1890            if !literals.is_empty() {
1891                files_holding_codes += 1;
1892            }
1893            let is_this_module = path.ends_with("ridl-core/src/diag.rs");
1894            for code in literals {
1895                if !catalogued.contains(code) {
1896                    uncatalogued.push(format!("{}: {code}", path.display()));
1897                }
1898                if !is_this_module {
1899                    codes_outside_this_module.insert(code.to_string());
1900                }
1901            }
1902        }
1903
1904        assert!(
1905            uncatalogued.is_empty(),
1906            "these code strings are written in Rust sources but no catalogue \
1907             lists them, so the error index (E4.2) has nothing to key them on \
1908             and nothing connects them to a `DiagCode`. Declare each one in \
1909             `diag_codes!`:\n{}",
1910            uncatalogued.join("\n"),
1911        );
1912
1913        // Width. Every assertion above is vacuous if the walk finds nothing, and
1914        // a walk rooted at the wrong directory finds nothing quietly. These
1915        // floors are well under what the workspace holds today — 79 `.rs` files,
1916        // 21 of them carrying a code, 92 distinct codes outside this module —
1917        // and fail loudly if the scan stops reaching past its own crate. The
1918        // three figures are measured, not maintained: they are a comment, and
1919        // the assertions below hold whether or not they drift.
1920        assert!(
1921            sources.len() >= 60,
1922            "the walk found only {} `.rs` files under {} — it is not reaching \
1923             the workspace",
1924            sources.len(),
1925            root.display(),
1926        );
1927        assert!(
1928            files_holding_codes >= 10,
1929            "only {files_holding_codes} files carried a code literal",
1930        );
1931        assert!(
1932            codes_outside_this_module.len() >= 60,
1933            "only {} distinct codes were seen outside `diag.rs` — the scan is \
1934             checking this module against itself",
1935            codes_outside_this_module.len(),
1936        );
1937    }
1938
1939    /// No `DiagCode` constant is declared outside [`diag_codes!`], anywhere in
1940    /// the workspace.
1941    ///
1942    /// The scan above already reports a hand-written constant whose code is
1943    /// spelled as a literal, because the literal is what it looks for — but one
1944    /// whose code is assembled compiles and slips past it. This catches that
1945    /// form, and any other, by looking at the declaration rather than at the
1946    /// code string.
1947    ///
1948    /// The surface is the whole workspace, not this crate. An inherent
1949    /// `impl DiagCode` can only be written here, but the newtype's field is
1950    /// public, so any crate can construct one and give it a name. A constant of
1951    /// this type declared in `ridl-sem` with an assembled code compiles and
1952    /// passes both the suite and clippy when this walks `ridl-core` alone, so it
1953    /// walks everything.
1954    ///
1955    /// Matching is whitespace-insensitive and accepts a path-qualified type,
1956    /// because a declaration in another crate writes the type as
1957    /// `ridl_core::diag::…` and rustfmt may break it across lines. Comments are
1958    /// stripped first, so prose describing the forbidden shape — including this
1959    /// paragraph — does not report itself; the cost is that a `//` inside a
1960    /// string literal hides the rest of that line from the scan.
1961    ///
1962    /// It remains a textual check: it recognises the two shapes a `DiagCode`
1963    /// constant is written in and rejects everything else, so a declaration
1964    /// reworded to avoid both evades it. The two evasions are not symmetric,
1965    /// and only their combination gets through:
1966    ///
1967    /// - a declaration writing the type under an alias (`use … DiagCode as DC;`
1968    ///   then `const RIDL_199: DC = DC("RIDL-199");`) is invisible here, but its
1969    ///   code is spelled, so `codes_written_as_string_literals_are_all_catalogued`
1970    ///   reports it;
1971    /// - a declaration with an assembled code is invisible to that scan, but
1972    ///   names the type, so this one reports it — verified against a qualified,
1973    ///   line-broken `concat!` declaration in `ridl-sem` and against one in a
1974    ///   child module of `diag`;
1975    /// - **both at once** — an aliased type and an assembled code — passes the
1976    ///   whole workspace suite and clippy. That is a surviving escape, and it is
1977    ///   a deliberate act rather than the omission this file defends against.
1978    #[test]
1979    fn no_diagnostic_constant_is_declared_outside_the_macro() {
1980        // Assembled rather than spelled: this test lives in a file it scans, so
1981        // writing the shapes out whole would make the test report itself.
1982        let anchor = format!("DiagCode{}", '=');
1983        // The macro body, expanding one entry into its constant.
1984        let in_macro = format!("pubconst$konst:{anchor}DiagCode($code);");
1985        // The sentinel, which has no catalogue entry by design.
1986        let sentinel = format!("pubconstNONE:{anchor}DiagCode(\"\");");
1987        let accepted = [in_macro.as_str(), sentinel.as_str()];
1988
1989        let root = workspace_root();
1990        let mut sources = Vec::new();
1991        collect_rust_sources(&root, &mut sources);
1992        assert!(
1993            sources.len() >= 60,
1994            "the walk found only {} `.rs` files under {} — it is not reaching \
1995             the workspace",
1996            sources.len(),
1997            root.display(),
1998        );
1999
2000        let mut declarations = 0usize;
2001        for path in &sources {
2002            let text = std::fs::read_to_string(path)
2003                .unwrap_or_else(|err| panic!("cannot read {}: {err}", path.display()));
2004            let stripped = strip_line_comments(&text);
2005            let despaced: String = stripped.chars().filter(|c| !c.is_whitespace()).collect();
2006
2007            for (at, _) in despaced.match_indices(&anchor) {
2008                let recognised = accepted.iter().any(|form| {
2009                    let offset = form.find(&anchor).expect("each form holds the anchor");
2010                    at >= offset && despaced[at - offset..].starts_with(form)
2011                });
2012                assert!(
2013                    recognised,
2014                    "{}: `…{}…` declares a `DiagCode` constant outside \
2015                     `diag_codes!`, so it carries no catalogue entry. Move it \
2016                     into the macro.",
2017                    path.display(),
2018                    &despaced[at.saturating_sub(40)..(at + 40).min(despaced.len())],
2019                );
2020                declarations += 1;
2021            }
2022        }
2023        assert_eq!(
2024            declarations, 2,
2025            "expected exactly two `DiagCode` constant declarations in the \
2026             workspace — the macro body and the `NONE` sentinel, both in this \
2027             file",
2028        );
2029    }
2030
2031    /// The family overview's `FORM-` and `MANI-` tables list exactly the codes
2032    /// this module declares, at the same severities.
2033    ///
2034    /// The overview says of those two tables that `crates/ridl-core/src/diag.rs`
2035    /// "is the single source of truth these two tables mirror" — and until this
2036    /// test, nothing checked the mirror. A code added to one and not the other
2037    /// compiled and passed, and so did a severity that disagreed; the drift was
2038    /// found the ordinary way, by a reviewer reading both.
2039    ///
2040    /// **Codes and severities only.** The `Rule` column is prose written for a
2041    /// reader and the catalogue `summary` is written for the error index, so
2042    /// they are deliberately not compared — pinning two prose strings to each
2043    /// other would make every wording improvement a two-file edit for no gain.
2044    /// What this catches is a code present in one list and absent from the
2045    /// other, and a severity that disagrees. What it does not catch is a row
2046    /// whose prose describes the wrong rule.
2047    ///
2048    /// TYPL and RIDL have no counterpart here: their tables live in their own
2049    /// language references, and those tables carry codes no constant declares
2050    /// yet (typl §16 documents six, recorded in issue #172), so the same
2051    /// equality would fail today for a reason that is not drift.
2052    #[test]
2053    fn the_overview_form_and_mani_tables_mirror_the_catalogues() {
2054        let overview = workspace_root().join("docs/specification/ridl-family-overview.md");
2055        let text = std::fs::read_to_string(&overview)
2056            .unwrap_or_else(|err| panic!("cannot read {}: {err}", overview.display()));
2057
2058        // `| CODE | rule | severity |`, tolerant of the column padding prim
2059        // applies. A row whose severity word is unknown is a malformed table,
2060        // not something to skip quietly.
2061        let mut documented: Vec<(String, Severity)> = Vec::new();
2062        for line in text.lines() {
2063            let mut cells = line.split('|').map(str::trim);
2064            if cells.next() != Some("") {
2065                continue;
2066            }
2067            let (Some(code), Some(_rule), Some(severity)) =
2068                (cells.next(), cells.next(), cells.next())
2069            else {
2070                continue;
2071            };
2072            if !(code.starts_with("FORM-") || code.starts_with("MANI-")) {
2073                continue;
2074            }
2075            let severity = match severity {
2076                "error" => Severity::Error,
2077                "warning" => Severity::Warning,
2078                "info" => Severity::Info,
2079                other => panic!("{code} in the overview carries no severity: `{other}`"),
2080            };
2081            documented.push((code.to_string(), severity));
2082        }
2083
2084        let declared: Vec<(String, Severity)> = FORM_CATALOG
2085            .iter()
2086            .chain(MANI_CATALOG)
2087            .map(|entry| (entry.code.as_str().to_string(), entry.severity))
2088            .collect();
2089
2090        let names = |rows: &[(String, Severity)]| -> Vec<String> {
2091            let mut names: Vec<String> = rows.iter().map(|(code, _)| code.clone()).collect();
2092            names.sort();
2093            names
2094        };
2095        assert_eq!(
2096            names(&documented),
2097            names(&declared),
2098            "the family overview §7 tables and the FORM/MANI catalogues list \
2099             different codes — {} documents the two namespaces `diag.rs` owns, \
2100             so a code minted in one belongs in the other",
2101            overview.display(),
2102        );
2103
2104        for (code, severity) in &declared {
2105            let (_, documented_severity) = documented
2106                .iter()
2107                .find(|(name, _)| name == code)
2108                .expect("the code sets are equal");
2109            assert_eq!(
2110                documented_severity, severity,
2111                "{code} is {severity:?} in the catalogue and \
2112                 {documented_severity:?} in the overview",
2113            );
2114        }
2115
2116        // Width: a scan that matched nothing would satisfy both assertions
2117        // against an empty catalogue, and cannot against a real one.
2118        assert!(
2119            documented.len() >= 25,
2120            "only {} rows were read out of the overview tables — the parse is \
2121             not finding them",
2122            documented.len(),
2123        );
2124    }
2125
2126    /// Whether `rest` — the source just past a `"expected {` — closes the
2127    /// format string immediately as `ident:?}"`, making the whole message a
2128    /// `Debug`-formatted value and nothing else.
2129    ///
2130    /// That exact shape is what reaches [`punctuation_glyph`]: anything with
2131    /// prose after the placeholder (`"expected {text:?} to parse"`) is not a
2132    /// bare token name, and a `Display` placeholder (`"expected {name}"`) is not
2133    /// a `Debug` name. Both occur in the workspace and both are correctly
2134    /// ignored. What this does not catch is an emitter that formats the name
2135    /// through a variable rather than inline; no such site exists, and the
2136    /// recurrence worth guarding is a second `expect`-shaped helper.
2137    fn is_whole_debug_message(rest: &str) -> bool {
2138        let Some(colon) = rest.find(':') else {
2139            return false;
2140        };
2141        let placeholder = &rest[..colon];
2142        !placeholder.is_empty()
2143            && placeholder
2144                .chars()
2145                .all(|c| c.is_ascii_alphanumeric() || c == '_')
2146            && rest[colon..].starts_with(":?}\"")
2147    }
2148
2149    /// `text` with every `//` line comment removed, so prose about a forbidden
2150    /// code shape is not mistaken for the shape itself. A `//` inside a string
2151    /// literal takes the rest of its line with it.
2152    fn strip_line_comments(text: &str) -> String {
2153        text.lines()
2154            .map(|line| match line.find("//") {
2155                Some(at) => &line[..at],
2156                None => line,
2157            })
2158            .collect::<Vec<_>>()
2159            .join("\n")
2160    }
2161
2162    /// The workspace root: two levels above `crates/ridl-core`.
2163    fn workspace_root() -> std::path::PathBuf {
2164        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2165            .parent()
2166            .and_then(std::path::Path::parent)
2167            .expect("`crates/ridl-core` sits two levels below the workspace root")
2168            .to_path_buf();
2169        let manifest = std::fs::read_to_string(root.join("Cargo.toml"))
2170            .unwrap_or_else(|err| panic!("no manifest at {}: {err}", root.display()));
2171        assert!(
2172            manifest.contains("[workspace]"),
2173            "{} is not the workspace root",
2174            root.display(),
2175        );
2176        root
2177    }
2178
2179    /// Every `.rs` file under `dir`, skipping `target` and dot-directories — the
2180    /// latter keeps the walk out of `.git` and out of any `.claude/worktrees`
2181    /// checkout of this same repository.
2182    fn collect_rust_sources(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
2183        let entries = std::fs::read_dir(dir)
2184            .unwrap_or_else(|err| panic!("cannot read {}: {err}", dir.display()));
2185        for entry in entries {
2186            let entry = entry.unwrap_or_else(|err| panic!("cannot read {}: {err}", dir.display()));
2187            let name = entry.file_name();
2188            let name = name.to_string_lossy();
2189            if name.starts_with('.') || name == "target" {
2190                continue;
2191            }
2192            let path = entry.path();
2193            if path.is_dir() {
2194                collect_rust_sources(&path, out);
2195            } else if path.extension().is_some_and(|extension| extension == "rs") {
2196                out.push(path);
2197            }
2198        }
2199    }
2200
2201    /// Every `"PREFIX-NNN"` string literal in `text`, where `PREFIX` is two or
2202    /// more uppercase ASCII letters.
2203    ///
2204    /// The quotes are required on both sides, which is what keeps prose out: the
2205    /// doc comments in this module name RIDL-111 and RIDL-142 as reserved and
2206    /// not yet declared, and a scan that read unquoted text would report them.
2207    /// Matching is position-local rather than quote-pairing, so an escaped quote
2208    /// earlier in a string cannot shift the scan out of alignment.
2209    fn code_literals(text: &str) -> Vec<&str> {
2210        let bytes = text.as_bytes();
2211        let mut found = Vec::new();
2212        for dash in 0..bytes.len() {
2213            if bytes[dash] != b'-' || dash + 4 >= bytes.len() || bytes[dash + 4] != b'"' {
2214                continue;
2215            }
2216            if !bytes[dash + 1..dash + 4].iter().all(u8::is_ascii_digit) {
2217                continue;
2218            }
2219            let mut start = dash;
2220            while start > 0 && bytes[start - 1].is_ascii_uppercase() {
2221                start -= 1;
2222            }
2223            if dash - start < 2 || start == 0 || bytes[start - 1] != b'"' {
2224                continue;
2225            }
2226            found.push(&text[start..dash + 4]);
2227        }
2228        found
2229    }
2230}
2231
2232#[cfg(test)]
2233mod json_tests {
2234    use super::*;
2235
2236    #[test]
2237    fn line_col_is_one_based_and_counts_chars() {
2238        let text = "ab\ncé\n";
2239        assert_eq!(
2240            line_col(text, TextSize::from(0)),
2241            LineCol { line: 1, column: 1 }
2242        );
2243        assert_eq!(
2244            line_col(text, TextSize::from(2)),
2245            LineCol { line: 1, column: 3 }
2246        );
2247        assert_eq!(
2248            line_col(text, TextSize::from(3)),
2249            LineCol { line: 2, column: 1 }
2250        );
2251        // `é` is two bytes; the column after it is the third character.
2252        assert_eq!(
2253            line_col(text, TextSize::from(6)),
2254            LineCol { line: 2, column: 3 }
2255        );
2256        // An offset past the end clamps to the end of the text.
2257        assert_eq!(
2258            line_col(text, TextSize::from(99)),
2259            LineCol { line: 3, column: 1 }
2260        );
2261    }
2262
2263    #[test]
2264    fn to_json_projects_spans_and_fixits_onto_lines_and_columns() {
2265        let mut sources = SourceMap::new();
2266        let file = sources.file_id("a.typl", "package p\ntype X:\n");
2267        let span = Span {
2268            file,
2269            range: TextRange::new(TextSize::from(10), TextSize::from(17)),
2270        };
2271        // A different span from the primary one — a different line and a
2272        // different column — so a fix-it's span cannot pass this test by
2273        // being serialized from the primary span instead of its own.
2274        let fixit_span = Span {
2275            file,
2276            range: TextRange::new(TextSize::from(8), TextSize::from(9)),
2277        };
2278        let diagnostic = Diagnostic {
2279            // A real catalogued code, not a fabricated literal: the
2280            // `codes_written_as_string_literals_are_all_catalogued` workspace
2281            // scan rejects any `PREFIX-NNN` string literal that is not in a
2282            // catalogue, including one written in a test fixture.
2283            code: DiagCode::TYPL_009,
2284            severity: Severity::Error,
2285            message: "expected a type".to_string(),
2286            primary: span,
2287            labels: Vec::new(),
2288            fixits: vec![FixIt {
2289                span: fixit_span,
2290                replacement: "type X: integer".to_string(),
2291                label: "give `X` a backing type".to_string(),
2292            }],
2293        };
2294
2295        let json = to_json(&[diagnostic], &sources);
2296
2297        assert_eq!(json.len(), 1);
2298        let first = &json[0];
2299        assert_eq!(first.code, "TYPL-009");
2300        assert_eq!(first.severity, "error");
2301        assert_eq!(first.message, "expected a type");
2302        assert_eq!(first.span.path, "a.typl");
2303        assert_eq!(first.span.start, LineCol { line: 2, column: 1 });
2304        assert_eq!(first.span.end, LineCol { line: 2, column: 8 });
2305        assert_eq!(first.fixes.len(), 1);
2306        assert_eq!(first.fixes[0].label, "give `X` a backing type");
2307        assert_eq!(first.fixes[0].replacement, "type X: integer");
2308        assert_eq!(
2309            first.fixes[0].span.start,
2310            LineCol { line: 1, column: 9 },
2311            "the fix-it's span is its own, not the primary span",
2312        );
2313        assert_eq!(
2314            first.fixes[0].span.end,
2315            LineCol {
2316                line: 1,
2317                column: 10
2318            }
2319        );
2320    }
2321
2322    /// The struct-field assertions in the test above are checked against
2323    /// `JsonDiagnostic` itself and stay green through a consistent field
2324    /// rename or an added `#[serde(rename = ...)]` on the struct. This
2325    /// snapshot instead pins the serialized JSON key names — the actual wire
2326    /// contract the MCP `ridl_check` tool and `ridl check --format json` are
2327    /// both required to emit identically.
2328    #[test]
2329    fn to_json_snapshot_pins_the_wire_key_names() {
2330        let mut sources = SourceMap::new();
2331        let file = sources.file_id("a.typl", "package p\ntype X:\n");
2332        let span = Span {
2333            file,
2334            range: TextRange::new(TextSize::from(10), TextSize::from(17)),
2335        };
2336        // A different span from the primary one, so the snapshot cannot pass
2337        // by serializing the fix-it's span from the primary span instead of
2338        // its own.
2339        let fixit_span = Span {
2340            file,
2341            range: TextRange::new(TextSize::from(8), TextSize::from(9)),
2342        };
2343        let diagnostic = Diagnostic {
2344            code: DiagCode::TYPL_009,
2345            severity: Severity::Error,
2346            message: "expected a type".to_string(),
2347            primary: span,
2348            labels: Vec::new(),
2349            fixits: vec![FixIt {
2350                span: fixit_span,
2351                replacement: "type X: integer".to_string(),
2352                label: "give `X` a backing type".to_string(),
2353            }],
2354        };
2355
2356        insta::assert_json_snapshot!(to_json(&[diagnostic], &sources));
2357    }
2358
2359    #[test]
2360    fn to_json_tolerates_a_span_on_an_unknown_file() {
2361        let sources = SourceMap::new();
2362        let diagnostic = Diagnostic {
2363            code: DiagCode::MANI_101,
2364            severity: Severity::Warning,
2365            message: "detached".to_string(),
2366            primary: Span {
2367                file: FileId::DETACHED,
2368                range: TextRange::new(TextSize::from(0), TextSize::from(0)),
2369            },
2370            labels: Vec::new(),
2371            fixits: Vec::new(),
2372        };
2373        let json = to_json(&[diagnostic], &sources);
2374        assert_eq!(json[0].severity, "warning");
2375        assert_eq!(json[0].span.path, "");
2376        assert_eq!(json[0].span.start, LineCol { line: 1, column: 1 });
2377    }
2378
2379    /// A source map holding two files, with a diagnostic whose primary span
2380    /// and label span both point into the second one. Every other JSON
2381    /// fixture in this module registers exactly one file, under which
2382    /// `json_span` resolving every span against a hard-coded `FileId(0)`
2383    /// would still pass. The two files here also lay out their lines
2384    /// differently, so a wrong-file lookup reads the wrong line and column,
2385    /// not only the wrong path.
2386    #[test]
2387    fn to_json_resolves_spans_in_the_second_of_two_files() {
2388        let mut sources = SourceMap::new();
2389        let _first = sources.file_id("a.typl", "package p\n");
2390        let second = sources.file_id("b.typl", "package p\nimport a\ntype Y:\n");
2391        let primary = Span {
2392            file: second,
2393            range: TextRange::new(TextSize::from(19), TextSize::from(26)),
2394        };
2395        let label_span = Span {
2396            file: second,
2397            range: TextRange::new(TextSize::from(10), TextSize::from(18)),
2398        };
2399        let diagnostic = Diagnostic {
2400            code: DiagCode::TYPL_009,
2401            severity: Severity::Error,
2402            message: "expected a type".to_string(),
2403            primary,
2404            labels: vec![Label {
2405                span: label_span,
2406                message: "imported here".to_string(),
2407            }],
2408            fixits: Vec::new(),
2409        };
2410
2411        let json = to_json(&[diagnostic], &sources);
2412
2413        let first = &json[0];
2414        assert_eq!(first.span.path, "b.typl");
2415        assert_eq!(first.span.start, LineCol { line: 3, column: 1 });
2416        assert_eq!(first.span.end, LineCol { line: 3, column: 8 });
2417        assert_eq!(first.labels.len(), 1);
2418        assert_eq!(first.labels[0].message, "imported here");
2419        assert_eq!(first.labels[0].span.path, "b.typl");
2420        assert_eq!(first.labels[0].span.start, LineCol { line: 2, column: 1 });
2421        assert_eq!(first.labels[0].span.end, LineCol { line: 2, column: 9 });
2422    }
2423
2424    /// `Severity::Info` renders as `"info"`. The other two variants
2425    /// (`"error"`, `"warning"`) are already exercised above.
2426    #[test]
2427    fn to_json_reports_info_severity() {
2428        let sources = SourceMap::new();
2429        let diagnostic = Diagnostic {
2430            code: DiagCode::TYPL_115,
2431            severity: Severity::Info,
2432            message: "type has no derivable init value".to_string(),
2433            primary: Span {
2434                file: FileId::DETACHED,
2435                range: TextRange::new(TextSize::from(0), TextSize::from(0)),
2436            },
2437            labels: Vec::new(),
2438            fixits: Vec::new(),
2439        };
2440        let json = to_json(&[diagnostic], &sources);
2441        assert_eq!(json[0].severity, "info");
2442    }
2443
2444    /// `code` stays present on the wire, as an empty string, for a diagnostic
2445    /// carrying [`DiagCode::NONE`] — never omitted or turned into `null`. A
2446    /// snapshot pins the whole serialized object, so a `#[serde(skip_serializing_if
2447    /// = "String::is_empty")]` mutation on `code` (which a struct-field-only
2448    /// assertion would not catch) drops the key and fails this comparison.
2449    #[test]
2450    fn to_json_keeps_the_code_field_present_when_empty() {
2451        let sources = SourceMap::new();
2452        let diagnostic = Diagnostic {
2453            code: DiagCode::NONE,
2454            severity: Severity::Error,
2455            message: "expected a type, but `FROB` names a constant".to_string(),
2456            primary: Span {
2457                file: FileId::DETACHED,
2458                range: TextRange::new(TextSize::from(0), TextSize::from(0)),
2459            },
2460            labels: Vec::new(),
2461            fixits: Vec::new(),
2462        };
2463        insta::assert_json_snapshot!(to_json(&[diagnostic], &sources));
2464    }
2465}