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