praxis-source 0.2.0

Source files, spans, line maps, and diagnostics for the Praxis compiler.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
//! Diagnostics: structured problems reported against source spans.
//!
//! A [`Diagnostic`] always carries a [`Severity`], a structured [`DiagnosticCode`],
//! a message, and a primary [`FileSpan`]. There is no such thing as a diagnostic
//! without a code or a primary location: those fields are non-optional, so the
//! thing you most want to know about an error (where, what kind, what message)
//! can never be missing.
//!
//! The [`Renderer`] produces the §8.2/§8.3 layout:
//!
//! ```text
//! error[T012]: expected Int, found Text
//!
//!   day03.px:18:14
//!   18 | total += line
//!      |          ^^^^ this value is Text
//!
//! hint: parse it with the input parser or call line.int()
//! ```

use std::fmt::Write;

use crate::file::SourceMap;
use crate::span::{BytePos, FileSpan};
use crate::style;

/// How serious a diagnostic is. Non-exhaustive so future severities (e.g. an
/// "advice" level for inlay context) don't break match exhaustiveness downstream.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum Severity {
    Error,
    Warning,
    Note,
    Hint,
}

impl Severity {
    /// The lowercase label used in the rendered header (`error`, `warning`...).
    pub fn label(self) -> &'static str {
        match self {
            Severity::Error => "error",
            Severity::Warning => "warning",
            Severity::Note => "note",
            Severity::Hint => "hint",
        }
    }
}

/// The broad category a diagnostic belongs to. The category + a per-category
/// number together form the user-facing code (`T012`, `P003`, ...). Categories
/// are closed and compiler-owned, matching the design's "closed tables"
/// philosophy (§4.8).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum DiagnosticCategory {
    /// Lexical errors (`T0xx`). `T` for Token.
    Lex,
    /// Syntax / parse errors (`P0xx`).
    Parse,
    /// Name-resolution errors (`N0xx`).
    Name,
    /// Type-inference errors (`Y0xx`). `Y` for tYpe.
    Type,
    /// Input-parser errors (`I0xx`).
    Input,
    /// Runtime faults surfaced as compile-time-relevant diagnostics (`R0xx`).
    Runtime,
}

impl DiagnosticCategory {
    /// The single-letter prefix used in the rendered code.
    pub fn prefix(self) -> char {
        match self {
            DiagnosticCategory::Lex => 'T',
            DiagnosticCategory::Parse => 'P',
            DiagnosticCategory::Name => 'N',
            DiagnosticCategory::Type => 'Y',
            DiagnosticCategory::Input => 'I',
            DiagnosticCategory::Runtime => 'R',
        }
    }
}

/// A structured diagnostic code: a category plus a per-category number.
///
/// Because the category is a closed enum and the number is a `u32`, arbitrary
/// free-text codes are unrepresentable. The `Display` impl renders the §8.2
/// `T012`-style form (prefix + zero-padded three-digit number; numbers ≥ 1000
/// are not zero-padded so they stay readable).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct DiagnosticCode {
    category: DiagnosticCategory,
    number: u32,
}

impl DiagnosticCode {
    /// Create a code. The number is per-category: `Lex`/1 and `Parse`/1 are two
    /// distinct codes and both are valid.
    ///
    /// `pub(crate)` on purpose: the only way to reach a code from outside is
    /// [`DiagCode::code`], so a number nobody registered in [`DiagCode`] has no
    /// way into a diagnostic.
    #[inline]
    pub(crate) const fn new(category: DiagnosticCategory, number: u32) -> DiagnosticCode {
        DiagnosticCode { category, number }
    }

    #[inline]
    pub const fn category(self) -> DiagnosticCategory {
        self.category
    }

    #[inline]
    pub const fn number(self) -> u32 {
        self.number
    }
}

impl std::fmt::Display for DiagnosticCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let n = self.number;
        if n < 1000 {
            write!(f, "{}{:03}", self.category.prefix(), n)
        } else {
            write!(f, "{}{}", self.category.prefix(), n)
        }
    }
}

/// The closed set of diagnostics the compiler can emit.
///
/// Every `(category, number)` pair is written in exactly one place —
/// [`DiagCode::code`]'s exhaustive match — so allocating a code is a
/// compile-time act with a name rather than an integer literal at a call site.
/// [`DiagnosticCode::new`] is `pub(crate)` for the same reason: an unregistered
/// number has no route into a [`Diagnostic`].
///
/// **The allocation is ADR-051.** Adding a variant means amending it first;
/// `every_code_is_distinct` is what catches a collision if you do not.
///
/// The numbers are not contiguous and are not meant to be: `Y09x` is internal
/// errors, `Y11x` member errors, `Y12x` match errors. Renumbering them would
/// change identifiers users have already seen.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum DiagCode {
    // --- Lex (`T0xx`) ---
    /// `T001` — a `/*` with no matching `*/`.
    UnterminatedBlockComment,
    /// `T002` — a backtick template with no closing backtick.
    UnterminatedTemplate,
    /// `T003` — a character the lexer cannot classify.
    UnexpectedCharacter,
    /// `T004` — a text literal with no closing quote.
    UnterminatedTextLiteral,
    /// `T005` — a `\` escape the lexer does not recognize. Shared by both
    /// literal spellings, with one message each: the escape tables of `"…"` and
    /// `'…'` are the same table (ADR-141), so a `\x` is the same mistake in
    /// either.
    InvalidEscape,
    /// `T006` — a character literal with no closing quote.
    UnterminatedCharLiteral,
    /// `T007` — a character literal that does not name exactly one character.
    ///
    /// Two messages under one code, because `''` and `'ab'` are one rule broken
    /// in two directions. This is the code that closes `"##"[0]`'s silent
    /// truncation at the front end (ADR-141 Decision 2).
    CharLiteralIsNotOneCharacter,

    // --- Parse (`P0xx`) ---
    /// `P001` — a token that cannot appear here.
    UnexpectedToken,
    /// `P002` — two statements with no `;` and no line break between them.
    ExpectedStatementSeparator,

    // --- Name (`N0xx`) ---
    /// `N000` — internal: the parse tree's root is not a `SOURCE_FILE`.
    InternalNotASourceFile,
    /// `N001` — a name that is not in scope.
    UnknownName,
    /// `N002` — a type annotation naming a type that does not exist.
    UnknownType,
    /// `N003` — a name used in type position that names a value.
    NameIsNotAType,
    /// `N004` — one name declared twice in one scope.
    DuplicateDeclaration,
    /// `N005` — a function declared inside a function.
    NestedFunction,
    /// `N006` — a `struct`/`enum` declaration that refers to itself, directly or
    /// through a cycle (ADR-063).
    ///
    /// A declaration mistake, so it is in this category next to `N004`/`N005`
    /// rather than in `Y0xx`: the mistake is what was *declared*, and there is no
    /// pair of types to have failed to unify.
    RecursiveTypeDeclaration,
    /// `N007` — a `fn` body naming a binding declared outside it (ADR-068).
    ///
    /// A declaration mistake in the same sense `N005` is: the name resolves, and
    /// what is wrong is *where* it was declared relative to what reads it. A `fn`
    /// does not capture (§4.9/§4.10 — closures do, functions do not), so the
    /// binding has no storage the body can reach.
    ///
    /// It has two message forms. The usual one names both ways out, a parameter
    /// or a closure. When the `fn` is recursive — directly or mutually — it names
    /// only the parameter and carries an advisory `help:` line saying why: a
    /// closure cannot name itself, which is `N001`. One code either way, because
    /// it is the same mistake with one fewer way out.
    FunctionReadsOuterBinding,
    /// `N008` — a record literal whose head does not name a `struct`.
    ///
    /// A declaration mistake in `N003`'s sense: a record literal's head is a type
    /// position, and the name reaches the wrong sort of declaration. Reported in
    /// inference and not at lowering, so `praxis check` rejects a literal on a
    /// non-`struct` head rather than letting it produce a value with no
    /// representation.
    NotARecordLiteralHead,
    /// `N009` — a **retired keyword** written where a statement starts.
    ///
    /// `let` is the only one so far: it was the binding keyword before ADR-125
    /// chose `var`, so it is the first thing a reader of an old example meets.
    ///
    /// Not `N001`: it is not a name that happens to be missing, and treating it
    /// as one gives the wrong help. The suggestion budget is `max(1, len/3)`,
    /// `let` is three characters, so the budget is 1 — and the nearest name in
    /// scope one edit away is `Set`. The rule is right in general (it is
    /// rustc's); the outcome for a retired keyword is not, because the answer is
    /// known exactly and is not a spelling correction.
    ///
    /// `let` stays a legal **identifier** (`var let = 5` compiles), which is why
    /// this is raised where a statement starts rather than in the lexer.
    RetiredKeyword,

    // --- Type (`Y0xx`), the user block ---
    /// `Y001` — two types that could not be unified.
    TypeMismatch,
    /// `Y002` — an occurs-check failure.
    InfiniteType,
    /// `Y003` — an annotation that conflicts with what inference derived.
    AnnotationConflict,
    /// `Y004` — a type whose values cannot be compared with `==`.
    NotEquatable,
    /// `Y005` — a type that cannot be iterated.
    NotIterable,
    /// `Y006` — a type that has no ordering.
    NotOrderable,
    /// `Y007` — a type constructor given the wrong number of type arguments.
    /// `Option[Int, Text]` is the same mistake.
    WrongTypeArgumentCount,
    /// `Y008` — a `struct`/`enum` declaring one field or variant twice.
    DuplicateMember,
    // `Y009` is **retired** (ADR-125). It reported an assignment to something
    // that was not a `var`, and the language no longer has a binding that
    // cannot be written. The number stays spent: a code is a permanent
    // user-facing identifier, and re-issuing one is how an old message and a new
    // one come to share a name.
    /// `Y010` — a compound assignment whose operands are not numeric.
    CompoundAssignNonNumeric,
    /// `Y011` — `return` outside a function.
    ReturnOutsideFunction,
    /// `Y012` — `break`/`continue` outside a loop.
    BreakOutsideLoop,
    /// `Y013` — an integer literal outside the representable range.
    IntLiteralOutOfRange,
    /// `Y014` — a `Map`/`Set` key type that cannot be hashed.
    NotHashable,
    /// `Y015` — a non-numeric type where a numeric one is required.
    NotNumeric,
    /// `Y016` — an operator not defined for these operand types.
    OperatorNotDefined,
    /// `Y017` — a `break` carrying a value out of a `while`/`for`.
    ValueBreakOutsideLoopExpression,
    /// `Y018` — a **generic** `fn` used as a value (ADR-061).
    ///
    /// A monomorphic one is a closure over its adapter; a generic one has no
    /// instantiation to adapt, because monomorphization is driven by call sites
    /// and a value has none. `|x| id(x)` is the spelling that works — the
    /// closure's body *is* a call site.
    GenericFunctionAsValue,
    /// `Y019` — a `.0` element access on something that has no such element: a
    /// receiver that is not a tuple, or an index past its arity.
    ///
    /// Not `Y112` ("no field on this type"): a tuple has no field *names*, so a
    /// message about a missing field would name the wrong thing. Both are
    /// emitted in inference and both reach `praxis check` (ADR-093); the reason
    /// for the separate code is the *message*.
    NoTupleElement,
    /// `Y020` — a subscript on a type that has none, in either direction: `s[0]`
    /// on a `Set`, `t[0] = c` on a `Text` (which can be read through a subscript
    /// and is immutable, so it has no element store), or `grid[x]` — the wrong
    /// *arity* for a receiver that does index, since `grid[x, y]` is the
    /// spelling §6.4 gives.
    ///
    /// Not `Y110` ("no such method"): a subscript names no method, so a message
    /// about one would name something the program did not write. Both are
    /// emitted in inference and both reach `praxis check` (ADR-093); the reason
    /// for the separate code is the *message*.
    NotIndexable,
    /// `Y021` — an assignment whose left side is not a place at all: `f() = 1`,
    /// `a + b[0] = 1`. A **field** is a place and is not among them: `p.x = 5`
    /// stores (§4.5).
    NotAnAssignmentTarget,
    /// `Y022` — a prelude builtin or an enum constructor named without being
    /// called.
    ///
    /// [`GenericFunctionAsValue`](DiagCode::GenericFunctionAsValue)'s neighbour,
    /// one symbol kind over. A user `fn` in value position becomes a closure
    /// over its adapter (ADR-061); a builtin and a constructor have no adapter to
    /// close over, so there is nothing for the name to lower to — without this
    /// code `var h = abs` then `out(h(-3))` prints nothing and exits 0.
    ///
    /// `out(pi)` is the shape a reader meets first: `pi` is a nullary function,
    /// so the missing parentheses are the whole mistake.
    NameHasNoFunctionValue,
    /// `Y023` — a backtick parser template written where a value is expected
    /// (ADR-084). §7.1 says the parser-expression sublanguage is entered
    /// at `read` or at `parse(text, …)` and nowhere else, so `` `n = {int}` ``
    /// standing alone is a template with nothing to parse.
    ///
    /// Reported from inference, not the parser, so `praxis check` sees it. The
    /// token still parses to a `LITERAL` node so the tree round-trips the source
    /// and one mistake produces one diagnostic.
    ParserTemplateOutsideRead,
    /// `Y024` — a call whose argument count does not match the function's
    /// (ADR-089).
    ///
    /// A name in Praxis has exactly one signature — no arity-based overloading,
    /// no optional or default parameters — so a count mismatch is never a
    /// candidate for some other overload and can be reported as the mistake it
    /// is. It sits next to `Y007`, which names collection arity, and `Y110`,
    /// which names method arity; without it the mistake arrives as a `Y001`
    /// showing two whole function types to diff by eye.
    ///
    /// Raised from `TypeDb::unify`, which compares the two lengths anyway, so
    /// every function-to-function unification reports it rather than just a
    /// direct call.
    CallArityMismatch,

    // --- Type (`Y09x`), internal ---
    /// `Y099` — internal: a type the compiler expected was absent.
    InternalMissingType,

    // --- Type (`Y11x`), member errors ---
    /// `Y110` — no such method on this type at this arity.
    NoMethodOnType,
    /// `Y112` — no such field on this type.
    NoFieldOnType,
    /// `Y113` — a record literal missing one or more fields.
    MissingRecordFields,
    /// `Y114` — a record literal *or pattern* naming a field the type does not
    /// have.
    UnknownRecordField,
    /// `Y115` — a record literal *or pattern* naming one field twice. In a
    /// pattern the second sub-pattern would silently replace the first, so one
    /// of the two bindings the program wrote would never happen.
    DuplicateRecordField,

    // --- Type (`Y12x`), match errors ---
    /// `Y120` — a `match` that does not cover every value.
    NonExhaustiveMatch,
    /// `Y121` — a `match` arm an earlier arm already covers.
    UnreachableArm,
    /// `Y122` — a pattern naming a variant the scrutinee's type has not.
    UnknownEnumVariant,
    /// `Y123` — a pattern whose shape cannot match the scrutinee, or one no
    /// value can have at all: a one-element tuple pattern, or a record pattern
    /// whose head names something that is not a record.
    NotAPatternForType,
    /// `Y125` — a pattern that must match every value but can fail: a literal or
    /// a variant in a **binding** position, such as a `for` header.
    ///
    /// A binding has no second arm for an item to fall through to, so a pattern
    /// that tests would silently skip the steps it does not match.
    RefutableBinding,
    /// `Y124` — a pattern whose sub-patterns do not fit the variant's payload
    /// (ADR-134).
    ///
    /// Two shapes reach this code:
    ///
    /// - **More** sub-patterns than the variant has slots. `Wrap(a, b)` against
    ///   a one-slot variant would read a payload the object does not have.
    /// - A **bare variant name** for a variant that carries a payload. `A => …`
    ///   against `A(Int)` says nothing about the value `A` holds, and it reads
    ///   like a payload-less variant to anyone who did not check the
    ///   declaration. Write `A(_)` to say "any payload" out loud.
    ///
    /// Naming *fewer* inside parentheses is legal and is padded with wildcards,
    /// so `Some(_)` and `Some(n)` are one test. Bare `Some` is not a third
    /// spelling of it.
    PayloadArityMismatch,

    // --- Input (`I0xx`) ---
    /// `I000` — a parser expression the lowerer cannot read at all.
    MalformedParserExpression,
    /// `I001` — a parser AST that could not be converted to a type or plan.
    ParserConversion,
    /// `I010` — an atomic parser name that does not exist.
    UnknownAtomic,
    /// `I011` — an invalid capture name in a template.
    InvalidCaptureName,
    /// `I012` — a capture kind that does not exist.
    UnknownCaptureKind,
    /// `I013` — a parser constructor that does not exist.
    UnknownConstructor,
    /// `I014` — a constructor argument that is invalid or in excess.
    InvalidConstructorArgument,
    /// `I020` — named and anonymous captures mixed in one template (§7.3).
    MixedCaptureNaming,
    /// `I021` — one capture name used twice in a template.
    DuplicateCaptureName,
    /// `I022` — a constructor called with the wrong number of arguments.
    ConstructorArity,
    /// `I023` — an empty separator, which cannot advance a cursor.
    EmptySeparator,
    /// `I024` — a section or block field declared twice.
    DuplicateSectionField,
    /// `I025` — a `sections`/`choice` with no field or case at all.
    EmptyFieldList,
    /// `I026` — a positional `block` item returning a scalar with no name.
    UnnamedScalarBlockItem,
    /// `I027` — a `choice` case declared twice.
    DuplicateChoiceCase,
    /// `I028` — a misplaced or repeated `repeated(...)` tail.
    MisplacedRepeatedTail,
    /// `I030` — a backtick template the scanner could not read.
    TemplateScan,
}

impl DiagCode {
    /// The rendered code. **The one place a `(category, number)` pair exists.**
    #[must_use]
    pub const fn code(self) -> DiagnosticCode {
        use DiagCode::*;
        use DiagnosticCategory::{Input, Lex, Name, Parse, Type};
        match self {
            UnterminatedBlockComment => DiagnosticCode::new(Lex, 1),
            UnterminatedTemplate => DiagnosticCode::new(Lex, 2),
            UnexpectedCharacter => DiagnosticCode::new(Lex, 3),
            UnterminatedTextLiteral => DiagnosticCode::new(Lex, 4),
            InvalidEscape => DiagnosticCode::new(Lex, 5),
            UnterminatedCharLiteral => DiagnosticCode::new(Lex, 6),
            CharLiteralIsNotOneCharacter => DiagnosticCode::new(Lex, 7),

            UnexpectedToken => DiagnosticCode::new(Parse, 1),
            ExpectedStatementSeparator => DiagnosticCode::new(Parse, 2),

            InternalNotASourceFile => DiagnosticCode::new(Name, 0),
            UnknownName => DiagnosticCode::new(Name, 1),
            UnknownType => DiagnosticCode::new(Name, 2),
            NameIsNotAType => DiagnosticCode::new(Name, 3),
            DuplicateDeclaration => DiagnosticCode::new(Name, 4),
            NestedFunction => DiagnosticCode::new(Name, 5),
            RecursiveTypeDeclaration => DiagnosticCode::new(Name, 6),
            FunctionReadsOuterBinding => DiagnosticCode::new(Name, 7),
            NotARecordLiteralHead => DiagnosticCode::new(Name, 8),
            RetiredKeyword => DiagnosticCode::new(Name, 9),

            TypeMismatch => DiagnosticCode::new(Type, 1),
            InfiniteType => DiagnosticCode::new(Type, 2),
            AnnotationConflict => DiagnosticCode::new(Type, 3),
            NotEquatable => DiagnosticCode::new(Type, 4),
            NotIterable => DiagnosticCode::new(Type, 5),
            NotOrderable => DiagnosticCode::new(Type, 6),
            WrongTypeArgumentCount => DiagnosticCode::new(Type, 7),
            DuplicateMember => DiagnosticCode::new(Type, 8),
            // 9 is retired (ADR-125) and deliberately not reissued.
            CompoundAssignNonNumeric => DiagnosticCode::new(Type, 10),
            ReturnOutsideFunction => DiagnosticCode::new(Type, 11),
            BreakOutsideLoop => DiagnosticCode::new(Type, 12),
            IntLiteralOutOfRange => DiagnosticCode::new(Type, 13),
            NotHashable => DiagnosticCode::new(Type, 14),
            NotNumeric => DiagnosticCode::new(Type, 15),
            OperatorNotDefined => DiagnosticCode::new(Type, 16),
            ValueBreakOutsideLoopExpression => DiagnosticCode::new(Type, 17),
            GenericFunctionAsValue => DiagnosticCode::new(Type, 18),
            NoTupleElement => DiagnosticCode::new(Type, 19),
            NotIndexable => DiagnosticCode::new(Type, 20),
            NotAnAssignmentTarget => DiagnosticCode::new(Type, 21),
            NameHasNoFunctionValue => DiagnosticCode::new(Type, 22),
            ParserTemplateOutsideRead => DiagnosticCode::new(Type, 23),
            CallArityMismatch => DiagnosticCode::new(Type, 24),

            InternalMissingType => DiagnosticCode::new(Type, 99),

            NoMethodOnType => DiagnosticCode::new(Type, 110),
            NoFieldOnType => DiagnosticCode::new(Type, 112),
            MissingRecordFields => DiagnosticCode::new(Type, 113),
            UnknownRecordField => DiagnosticCode::new(Type, 114),
            DuplicateRecordField => DiagnosticCode::new(Type, 115),

            NonExhaustiveMatch => DiagnosticCode::new(Type, 120),
            UnreachableArm => DiagnosticCode::new(Type, 121),
            UnknownEnumVariant => DiagnosticCode::new(Type, 122),
            NotAPatternForType => DiagnosticCode::new(Type, 123),
            PayloadArityMismatch => DiagnosticCode::new(Type, 124),
            RefutableBinding => DiagnosticCode::new(Type, 125),

            MalformedParserExpression => DiagnosticCode::new(Input, 0),
            ParserConversion => DiagnosticCode::new(Input, 1),
            UnknownAtomic => DiagnosticCode::new(Input, 10),
            InvalidCaptureName => DiagnosticCode::new(Input, 11),
            UnknownCaptureKind => DiagnosticCode::new(Input, 12),
            UnknownConstructor => DiagnosticCode::new(Input, 13),
            InvalidConstructorArgument => DiagnosticCode::new(Input, 14),
            MixedCaptureNaming => DiagnosticCode::new(Input, 20),
            DuplicateCaptureName => DiagnosticCode::new(Input, 21),
            ConstructorArity => DiagnosticCode::new(Input, 22),
            EmptySeparator => DiagnosticCode::new(Input, 23),
            DuplicateSectionField => DiagnosticCode::new(Input, 24),
            EmptyFieldList => DiagnosticCode::new(Input, 25),
            UnnamedScalarBlockItem => DiagnosticCode::new(Input, 26),
            DuplicateChoiceCase => DiagnosticCode::new(Input, 27),
            MisplacedRepeatedTail => DiagnosticCode::new(Input, 28),
            TemplateScan => DiagnosticCode::new(Input, 30),
        }
    }

    /// Every code, so a test can assert the allocation is injective.
    ///
    /// [`code`](DiagCode::code)'s exhaustive match forces a new variant to be
    /// *numbered*; only `all_lists_every_variant` forces it to be listed here,
    /// and a variant missing from this list is one the injectivity test never
    /// checks.
    pub const ALL: &'static [DiagCode] = {
        use DiagCode::*;
        &[
            UnterminatedBlockComment,
            UnterminatedTemplate,
            UnexpectedCharacter,
            UnterminatedTextLiteral,
            InvalidEscape,
            UnterminatedCharLiteral,
            CharLiteralIsNotOneCharacter,
            UnexpectedToken,
            ExpectedStatementSeparator,
            InternalNotASourceFile,
            UnknownName,
            UnknownType,
            NameIsNotAType,
            DuplicateDeclaration,
            NestedFunction,
            RecursiveTypeDeclaration,
            FunctionReadsOuterBinding,
            NotARecordLiteralHead,
            RetiredKeyword,
            TypeMismatch,
            InfiniteType,
            AnnotationConflict,
            NotEquatable,
            NotIterable,
            NotOrderable,
            WrongTypeArgumentCount,
            DuplicateMember,
            CompoundAssignNonNumeric,
            ReturnOutsideFunction,
            BreakOutsideLoop,
            IntLiteralOutOfRange,
            NotHashable,
            NotNumeric,
            OperatorNotDefined,
            ValueBreakOutsideLoopExpression,
            GenericFunctionAsValue,
            NoTupleElement,
            NotIndexable,
            NotAnAssignmentTarget,
            NameHasNoFunctionValue,
            ParserTemplateOutsideRead,
            CallArityMismatch,
            InternalMissingType,
            NoMethodOnType,
            NoFieldOnType,
            MissingRecordFields,
            UnknownRecordField,
            DuplicateRecordField,
            NonExhaustiveMatch,
            UnreachableArm,
            UnknownEnumVariant,
            NotAPatternForType,
            PayloadArityMismatch,
            RefutableBinding,
            MalformedParserExpression,
            ParserConversion,
            UnknownAtomic,
            InvalidCaptureName,
            UnknownCaptureKind,
            UnknownConstructor,
            InvalidConstructorArgument,
            MixedCaptureNaming,
            DuplicateCaptureName,
            ConstructorArity,
            EmptySeparator,
            DuplicateSectionField,
            EmptyFieldList,
            UnnamedScalarBlockItem,
            DuplicateChoiceCase,
            MisplacedRepeatedTail,
            TemplateScan,
        ]
    };
}

impl std::fmt::Display for DiagCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.code().fmt(f)
    }
}

/// A secondary span attached to a diagnostic, with its own message.
///
/// Used for the "related spans when inference connects distant expressions"
/// case in §8.2: a type error's primary span is the failing expression, and a
/// note can point at where the conflicting type was first inferred.
#[derive(Clone, Debug)]
pub struct DiagnosticNote {
    pub span: FileSpan,
    pub message: String,
}

/// A fix or piece of advice attached to a diagnostic.
///
/// When `replacement` is `Some`, it is a machine-applicable fix: replace `span`
/// with the given text (a "fix-it"). When `None`, the suggestion is advisory —
/// a `help:` line that explains how to resolve the problem without offering an
/// automatic rewrite (§8.2: "a concrete suggestion when available").
#[derive(Clone, Debug)]
pub struct Suggestion {
    pub span: FileSpan,
    /// `None` for advisory hints with no automatic replacement.
    pub replacement: Option<String>,
    pub label: String,
}

/// A structured diagnostic.
///
/// Construction goes through [`Diagnostic::new`] (required fields only) or the
/// [`DiagnosticBuilder`] (fluent, for the optional notes/suggestions). This
/// keeps the "a diagnostic always has severity + code + message + primary span"
/// invariant structural rather than conventional.
#[derive(Clone, Debug)]
pub struct Diagnostic {
    severity: Severity,
    /// The registered code. Stored as a [`DiagCode`] rather than a rendered
    /// pair so that a diagnostic cannot exist for a number nobody allocated;
    /// [`Diagnostic::code`] renders it on demand.
    code: DiagCode,
    message: String,
    primary: FileSpan,
    notes: Vec<DiagnosticNote>,
    suggestions: Vec<Suggestion>,
}

impl Diagnostic {
    /// The minimal complete diagnostic: severity, code, message, primary span.
    #[inline]
    pub fn new(
        severity: Severity,
        code: DiagCode,
        message: impl Into<String>,
        primary: FileSpan,
    ) -> Diagnostic {
        Diagnostic {
            severity,
            code,
            message: message.into(),
            primary,
            notes: Vec::new(),
            suggestions: Vec::new(),
        }
    }

    /// Begin a fluent build, starting from `new`'s required fields.
    #[inline]
    pub fn build(
        severity: Severity,
        code: DiagCode,
        message: impl Into<String>,
        primary: FileSpan,
    ) -> DiagnosticBuilder {
        DiagnosticBuilder {
            diag: Diagnostic::new(severity, code, message, primary),
        }
    }

    #[inline]
    pub fn severity(&self) -> Severity {
        self.severity
    }

    /// The rendered `T012`-style code.
    #[inline]
    pub fn code(&self) -> DiagnosticCode {
        self.code.code()
    }

    /// Which diagnostic this is, as the registered name.
    #[inline]
    pub fn kind(&self) -> DiagCode {
        self.code
    }

    #[inline]
    pub fn message(&self) -> &str {
        &self.message
    }

    #[inline]
    pub fn primary(&self) -> FileSpan {
        self.primary
    }

    /// The key that puts diagnostics in source order: the primary span's start,
    /// then its end.
    ///
    /// **The one comparator.** Every stage of the front end concatenates its own
    /// diagnostics onto the previous stage's and re-sorts, and they all sort by
    /// this key.
    ///
    /// The file is not part of the key: every list sorted this way is one file's
    /// diagnostics. [`sort_by_position`] is how a caller normally reaches this;
    /// the key itself is public for a caller sorting diagnostics that are
    /// decorated with something else.
    #[inline]
    pub fn sort_key(&self) -> (BytePos, BytePos) {
        (self.primary.span.start(), self.primary.span.end())
    }

    #[inline]
    pub fn notes(&self) -> &[DiagnosticNote] {
        &self.notes
    }

    #[inline]
    pub fn suggestions(&self) -> &[Suggestion] {
        &self.suggestions
    }

    /// Attach a secondary span with a message to an already-built diagnostic.
    ///
    /// The same operation [`DiagnosticBuilder::note`] performs, for a caller
    /// that received a finished `Diagnostic` from a wording helper and knows one
    /// thing the helper did not: where the requirement it violated was written
    /// (§8.2 "related spans when inference connects distant expressions").
    #[must_use]
    pub fn with_note(mut self, span: FileSpan, message: impl Into<String>) -> Diagnostic {
        self.notes.push(DiagnosticNote {
            span,
            message: message.into(),
        });
        self
    }

    /// Attach a machine-applicable fix to an already-built diagnostic.
    ///
    /// [`DiagnosticBuilder::suggestion`]'s operation, for the same reason
    /// [`with_note`](Self::with_note) exists: the wording helper says what is
    /// wrong, and the caller is the one that knows where the fix goes. A
    /// zero-width `span` is an insertion.
    #[must_use]
    pub fn with_suggestion(
        mut self,
        span: FileSpan,
        replacement: impl Into<String>,
        label: impl Into<String>,
    ) -> Diagnostic {
        self.suggestions.push(Suggestion {
            span,
            replacement: Some(replacement.into()),
            label: label.into(),
        });
        self
    }

    /// Offer `near` as a fix over `at`, with the compiler's one "did you mean"
    /// wording (ADR-132).
    ///
    /// The near-miss fix is emitted from five places — an atomic parser, a
    /// capture's parser, a parser constructor, an unresolved name, a method —
    /// and every one of them writes `` did you mean `x`? `` over the span the
    /// report already underlines. The threshold that decides *whether* to offer
    /// a candidate is [`crate::nearest`]'s; this is where the sentence the user
    /// reads lives, so the five cannot drift apart. `praxis-lsp` asserts on this
    /// text, for one path at a time.
    #[must_use]
    pub fn with_did_you_mean(self, at: FileSpan, near: impl Into<String>) -> Diagnostic {
        let near = near.into();
        let label = format!("did you mean `{near}`?");
        self.with_suggestion(at, near, label)
    }
}

/// Fluent builder for the optional parts of a [`Diagnostic`].
pub struct DiagnosticBuilder {
    diag: Diagnostic,
}

impl DiagnosticBuilder {
    /// Attach a secondary span with a message.
    pub fn note(mut self, span: FileSpan, message: impl Into<String>) -> Self {
        self.diag.notes.push(DiagnosticNote {
            span,
            message: message.into(),
        });
        self
    }

    /// Attach a machine-applicable suggestion: replace `span` with `replacement`.
    pub fn suggestion(
        mut self,
        span: FileSpan,
        replacement: impl Into<String>,
        label: impl Into<String>,
    ) -> Self {
        self.diag.suggestions.push(Suggestion {
            span,
            replacement: Some(replacement.into()),
            label: label.into(),
        });
        self
    }

    /// Attach an advisory `help:` line (no automatic replacement). Use when the
    /// fix is not mechanical (e.g. "remove this expression" or "change the
    /// return type") — §8.2 names these as explanations rather than fix-its.
    pub fn help(mut self, span: FileSpan, label: impl Into<String>) -> Self {
        self.diag.suggestions.push(Suggestion {
            span,
            replacement: None,
            label: label.into(),
        });
        self
    }

    /// Finish building.
    #[inline]
    pub fn finish(self) -> Diagnostic {
        self.diag
    }
}

/// Put `diags` in source order, by [`Diagnostic::sort_key`].
///
/// This runs at every stage boundary of the front end, because each stage
/// appends its diagnostics to the previous stage's and the merged list has to be
/// re-ordered: parse onto lex, inference onto name resolution, analysis onto
/// parse.
///
/// **The sort is stable, and that is load-bearing.** Two diagnostics on the same
/// span keep the order the stages produced them in, so the earlier stage's is
/// still printed first — a lex error before the parse error it caused. Do not
/// reach for `sort_unstable_by_key` here.
pub fn sort_by_position(diags: &mut [Diagnostic]) {
    diags.sort_by_key(Diagnostic::sort_key);
}

// ---------------------------------------------------------------------
// Rendering.
// ---------------------------------------------------------------------

/// Renders diagnostics in the §8.2 layout.
///
/// The renderer borrows a [`SourceMap`] for source snippets and line/column
/// conversion; it holds a [`style::Palette`] that decides whether the output is
/// plain (the default, for snapshot-stable tests) or ANSI-styled. It is cheap to
/// construct per render.
pub struct Renderer<'a> {
    source: &'a SourceMap,
    palette: style::Palette,
}

impl<'a> Renderer<'a> {
    /// A plain-text renderer (no ANSI). The default for snapshot tests, which
    /// must stay byte-stable regardless of terminal state.
    pub fn new(source: &'a SourceMap) -> Renderer<'a> {
        Renderer {
            source,
            palette: style::Palette::plain(),
        }
    }

    /// A renderer that styles its output when `palette` is [`style::Palette::styled`].
    pub fn new_styled(source: &'a SourceMap, palette: style::Palette) -> Renderer<'a> {
        Renderer { source, palette }
    }

    /// The diagnostic's severity in the [`style`] module's terms.
    fn style_severity(sev: Severity) -> style::Severity {
        match sev {
            Severity::Error => style::Severity::Error,
            Severity::Warning => style::Severity::Warning,
            Severity::Note => style::Severity::Note,
            Severity::Hint => style::Severity::Help,
        }
    }

    /// Render one diagnostic into `out`.
    pub fn render(&self, diag: &Diagnostic, out: &mut String) {
        self.render_header(diag, out);
        // §8.2 puts a blank line between the header and the location snippet.
        out.push('\n');

        // Primary location + source snippet, with the diagnostic message as the
        // caret-line label (§8.2: `^^^^ this value is Text`).
        self.render_location_and_snippet(
            diag.primary,
            Some(diag.message.as_str()),
            diag.severity,
            out,
        );

        // Related notes: each carries its own message + span snippet, set off by
        // a blank line so a multi-span diagnostic reads as distinct blocks.
        for note in &diag.notes {
            out.push('\n');
            let label = self
                .palette
                .paint(style::Style::Severity(style::Severity::Note), "note:");
            let _ = writeln!(out, "{label} {}", note.message);
            self.render_location_and_snippet(note.span, None, Severity::Note, out);
        }

        // Suggestions as rustc-style `help:` lines. A machine-applicable fix
        // shows its replacement on the next indented line; an advisory hint
        // shows only the explanation.
        for sugg in &diag.suggestions {
            out.push('\n');
            let label = self
                .palette
                .paint(style::Style::Severity(style::Severity::Help), "help:");
            let _ = writeln!(out, "{label} {}", sugg.label);
            if let Some(repl) = &sugg.replacement {
                // Line by line, skipping the leading break an *insertion* starts
                // with: a fix that adds a line writes `"\n        B => …"`, so
                // that break belongs to where the text goes rather than to what
                // it says, and printing it raw emits a line of trailing spaces.
                for line in repl.trim_start_matches('\n').lines() {
                    let _ = writeln!(out, "      {line}");
                }
            }
        }
    }

    /// Render `error[code]: message` (no trailing newline; the caller frames it).
    fn render_header(&self, diag: &Diagnostic, out: &mut String) {
        let sev = Self::style_severity(diag.severity);
        let label = self
            .palette
            .paint(style::Style::Severity(sev), diag.severity.label());
        let code = self
            .palette
            .paint(style::Style::Code, &format!("[{}]", diag.code));
        let _ = write!(out, "{label}{code}: {}", diag.message);
    }

    /// Render the `path:line:col` header followed by the source line(s) the
    /// span touches, with a clamped caret underline. `label` (when `Some`)
    /// trails the carets on the first underlined line. The caret is colored in
    /// the diagnostic's severity color when the palette is styled. Delegates the
    /// actual line/caret drawing to the shared
    /// [`snippet::render_span_snippet_styled`] so the compiler and crash debugger
    /// render spans identically.
    fn render_location_and_snippet(
        &self,
        span: FileSpan,
        label: Option<&str>,
        sev: Severity,
        out: &mut String,
    ) {
        let Some(file) = self.source.get(span.file) else {
            // Synthetic / unknown file: fall back to a location-only line.
            let _ = writeln!(out, "  <unknown file> [{:?}]", span);
            return;
        };
        let caret_label = match label {
            Some(s) if !s.is_empty() => crate::snippet::CaretLabel::Labelled(s),
            _ => crate::snippet::CaretLabel::Plain,
        };
        crate::snippet::render_span_snippet_styled(
            &file,
            span,
            caret_label,
            out,
            crate::snippet::MAX_SNIPPET_LINES,
            &self.palette,
            Some(Self::style_severity(sev)),
        );
    }
}

/// Helper used by tests and the CLI to render a single diagnostic to a string.
pub fn render_one(source: &SourceMap, diag: &Diagnostic) -> String {
    let mut out = String::new();
    Renderer::new(source).render(diag, &mut out);
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::file::FileId;
    use crate::span::Span;

    fn span(file: FileId, start: u32, end: u32) -> FileSpan {
        FileSpan::new(file, Span::new(start, end))
    }

    #[test]
    fn code_renders_zero_padded() {
        let code = DiagnosticCode::new(DiagnosticCategory::Lex, 12);
        assert_eq!(code.to_string(), "T012");
    }

    /// Two diagnostics must never render the same code.
    #[test]
    fn every_code_is_distinct() {
        let mut seen = std::collections::HashMap::new();
        for &code in DiagCode::ALL {
            if let Some(other) = seen.insert(code.to_string(), code) {
                panic!("{other:?} and {code:?} both render {code}");
            }
        }
    }

    /// …and `ALL` really is all of them. A variant left out of the list is a
    /// variant the injectivity test never checks.
    ///
    /// A count assertion cannot state this: `code()`'s exhaustive match forces a
    /// new variant to be *numbered*, nothing forces it into `ALL`, so a variant
    /// left out leaves the list and any expected length agreeing with each
    /// other. The match below forces the list instead, the way `CapKind::ALL` is
    /// guarded in `praxis-stdlib`: a new variant stops this test compiling, in
    /// the test whose whole subject is `ALL`.
    #[test]
    fn all_lists_every_variant() {
        use DiagCode::*;

        let unique: std::collections::HashSet<_> = DiagCode::ALL.iter().collect();
        assert_eq!(
            unique.len(),
            DiagCode::ALL.len(),
            "a variant is listed twice"
        );

        for &code in DiagCode::ALL {
            // Exhaustive on purpose, and the exhaustiveness is the whole of it:
            // adding a variant fails to compile here rather than passing
            // quietly out of `ALL`.
            match code {
                UnterminatedBlockComment
                | UnterminatedTemplate
                | UnexpectedCharacter
                | UnterminatedTextLiteral
                | InvalidEscape
                | UnterminatedCharLiteral
                | CharLiteralIsNotOneCharacter
                | UnexpectedToken
                | ExpectedStatementSeparator
                | InternalNotASourceFile
                | UnknownName
                | UnknownType
                | NameIsNotAType
                | DuplicateDeclaration
                | NestedFunction
                | RecursiveTypeDeclaration
                | FunctionReadsOuterBinding
                | NotARecordLiteralHead
                | RetiredKeyword
                | TypeMismatch
                | InfiniteType
                | AnnotationConflict
                | NotEquatable
                | NotIterable
                | NotOrderable
                | WrongTypeArgumentCount
                | DuplicateMember
                | CompoundAssignNonNumeric
                | ReturnOutsideFunction
                | BreakOutsideLoop
                | IntLiteralOutOfRange
                | NotHashable
                | NotNumeric
                | OperatorNotDefined
                | ValueBreakOutsideLoopExpression
                | GenericFunctionAsValue
                | NoTupleElement
                | NotIndexable
                | NotAnAssignmentTarget
                | NameHasNoFunctionValue
                | ParserTemplateOutsideRead
                | CallArityMismatch
                | InternalMissingType
                | NoMethodOnType
                | NoFieldOnType
                | MissingRecordFields
                | UnknownRecordField
                | DuplicateRecordField
                | NonExhaustiveMatch
                | UnreachableArm
                | UnknownEnumVariant
                | NotAPatternForType
                | RefutableBinding
                | PayloadArityMismatch
                | MalformedParserExpression
                | ParserConversion
                | UnknownAtomic
                | InvalidCaptureName
                | UnknownCaptureKind
                | UnknownConstructor
                | InvalidConstructorArgument
                | MixedCaptureNaming
                | DuplicateCaptureName
                | ConstructorArity
                | EmptySeparator
                | DuplicateSectionField
                | EmptyFieldList
                | UnnamedScalarBlockItem
                | DuplicateChoiceCase
                | MisplacedRepeatedTail
                | TemplateScan => {}
            }
        }
    }

    #[test]
    fn code_distinguishes_categories() {
        let lex = DiagnosticCode::new(DiagnosticCategory::Lex, 3);
        let parse = DiagnosticCode::new(DiagnosticCategory::Parse, 3);
        assert_eq!(lex.to_string(), "T003");
        assert_eq!(parse.to_string(), "P003");
        assert_ne!(lex, parse);
    }

    #[test]
    fn code_large_number_not_padded() {
        let code = DiagnosticCode::new(DiagnosticCategory::Type, 1234);
        assert_eq!(code.to_string(), "Y1234");
    }

    #[test]
    fn diagnostic_carries_required_fields() {
        let d = Diagnostic::new(
            Severity::Error,
            DiagCode::BreakOutsideLoop,
            "expected Int, found Text",
            span(FileId::SYNTHETIC, 0, 1),
        );
        assert_eq!(d.severity(), Severity::Error);
        // `Type` category renders as `Y`, matching the prefix table.
        assert_eq!(d.code().to_string(), "Y012");
        assert_eq!(d.kind(), DiagCode::BreakOutsideLoop);
        assert_eq!(d.message(), "expected Int, found Text");
        assert!(d.notes().is_empty());
        assert!(d.suggestions().is_empty());
    }

    #[test]
    fn builder_adds_notes_and_suggestions() {
        let d = Diagnostic::build(
            Severity::Error,
            DiagCode::UnknownName,
            "undefined name",
            span(FileId::SYNTHETIC, 0, 1),
        )
        .note(span(FileId::SYNTHETIC, 5, 6), "defined here")
        .suggestion(span(FileId::SYNTHETIC, 0, 1), "value", "did you mean")
        .finish();
        assert_eq!(d.notes().len(), 1);
        assert_eq!(d.suggestions().len(), 1);
        assert_eq!(d.suggestions()[0].replacement.as_deref(), Some("value"));
    }

    /// The near-miss wording, pinned where it is now written (ADR-132). Five
    /// front-end sites reach it through this one method, and `praxis-lsp`'s
    /// quick-fix tests each cover one of them.
    #[test]
    fn did_you_mean_labels_the_fix() {
        let at = span(FileId::SYNTHETIC, 0, 4);
        let d = Diagnostic::new(
            Severity::Error,
            DiagCode::UnknownName,
            "cannot find `lien`",
            at,
        )
        .with_did_you_mean(at, "line");
        assert_eq!(d.suggestions()[0].replacement.as_deref(), Some("line"));
        assert_eq!(d.suggestions()[0].label, "did you mean `line`?");
    }

    /// Source order by primary span, and **stable** — the property the front end
    /// relies on when it appends one stage's diagnostics to the previous
    /// stage's: two on the same span keep the order they were produced in.
    #[test]
    fn sort_by_position_is_stable_source_order() {
        let f = FileId::SYNTHETIC;
        let d = |start, end, msg: &str| {
            Diagnostic::new(
                Severity::Error,
                DiagCode::UnknownName,
                msg,
                span(f, start, end),
            )
        };
        let mut diags = vec![d(10, 12, "c"), d(0, 5, "a"), d(0, 3, "b"), d(0, 5, "a2")];
        sort_by_position(&mut diags);
        let order: Vec<&str> = diags.iter().map(Diagnostic::message).collect();
        assert_eq!(order, ["b", "a", "a2", "c"]);
    }

    #[test]
    fn render_snapshot_single_line() {
        let map = SourceMap::new();
        let id = map.intern("day03.px", "total += line\n");
        // "line" starts at byte 9, length 4.
        let d = Diagnostic::build(
            Severity::Error,
            DiagCode::BreakOutsideLoop,
            "expected Int, found Text",
            span(id, 9, 13),
        )
        .suggestion(
            span(id, 9, 13),
            "line.int()",
            "parse it with the input parser",
        )
        .finish();
        let rendered = render_one(&map, &d);
        insta::assert_snapshot!(rendered, @r"
error[Y012]: expected Int, found Text

  day03.px:1:10
  1 | total += line
    |          ^^^^ expected Int, found Text

help: parse it with the input parser
      line.int()
");
    }

    #[test]
    fn render_snapshot_two_lines_with_note() {
        let map = SourceMap::new();
        let id = map.intern("f.px", "var a = value\nvar b = a + 1\n");
        // Primary: "value" at 8..13 on line 1.
        let primary = span(id, 8, 13);
        let d = Diagnostic::build(
            Severity::Error,
            DiagCode::UnknownName,
            "undefined name `value`",
            primary,
        )
        .note(span(id, 23, 24), "the name `a` is defined here")
        .finish();
        let rendered = render_one(&map, &d);
        insta::assert_snapshot!(rendered, @r"
error[N001]: undefined name `value`

  f.px:1:9
  1 | var a = value
    |         ^^^^^ undefined name `value`

note: the name `a` is defined here

  f.px:2:10
  2 | var b = a + 1
    |          ^
");
    }

    #[test]
    fn styled_renderer_emits_ansi() {
        // The styled renderer wraps the severity label, code, carets, location,
        // and help label in ANSI escapes. The plain path (default) emits none.
        let map = SourceMap::new();
        let id = map.intern("f.px", "x = 1\n");
        let d = Diagnostic::build(
            Severity::Error,
            DiagCode::TypeMismatch,
            "expected Int, found Text",
            span(id, 0, 1),
        )
        .help(span(id, 0, 1), "call .int()")
        .finish();

        let mut plain = String::new();
        Renderer::new(&map).render(&d, &mut plain);
        assert!(
            !plain.contains("\x1b["),
            "plain output has no ANSI: {plain:?}"
        );

        let mut styled = String::new();
        Renderer::new_styled(&map, style::Palette::styled()).render(&d, &mut styled);
        // Header: bold-red `error` + bold `[Y001]`.
        assert!(
            styled.contains("\x1b[1;31merror\x1b[0m"),
            "styled error label: {styled:?}"
        );
        assert!(
            styled.contains("\x1b[1m[Y001]\x1b[0m"),
            "styled code: {styled:?}"
        );
        // Caret in the error color (red, not bold).
        assert!(
            styled.contains("\x1b[31m^\x1b[0m"),
            "styled caret: {styled:?}"
        );
        // help label in cyan.
        assert!(
            styled.contains("\x1b[1;36mhelp:\x1b[0m"),
            "styled help label: {styled:?}"
        );
    }
}