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