typeck-lang 0.3.0

Profile-driven type checking over HIR: dynamic, gradual, static (generics, traits, inference), and Hindley-Milner from one checker.
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
//! Typed diagnostics.
//!
//! A diagnostic is data: a [`DiagnosticKind`] (with the types and names
//! involved), the HIR node it is about, and that node's [`Origin`] (source
//! span and expansion). [`Typed::message`](crate::Typed::message) renders the
//! text. Each kind has a stable code (`T0001`...).

use alloc::string::String;
use core::fmt::Write as _;

use hir_lang::{ItemId, Member, NodeRef, OpKind, Origin, Symbol, VariantId};
use intern_lang::Lookup;

use crate::types::{TypeId, Types};

/// A language feature the checker recognises but this version does not
/// check. Each is recorded in `dev/ROADMAP.md`.
///
/// # Examples
///
/// ```
/// use typeck_lang::Feature;
///
/// assert_eq!(Feature::GenericAssocTypes.name(), "generic associated types");
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Feature {
    /// Associated types with generic parameters of their own (`type
    /// Item<'a>`, `type Map<T>`).
    GenericAssocTypes,
    /// Multi-segment unresolved paths (`T::Assoc::method`): resolution by
    /// type covers one trailing segment.
    LongAssocPaths,
}

impl Feature {
    /// A short name for messages.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(typeck_lang::Feature::LongAssocPaths.name(), "multi-segment associated paths");
    /// ```
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::GenericAssocTypes => "generic associated types",
            Self::LongAssocPaths => "multi-segment associated paths",
        }
    }
}

/// How serious a diagnostic is.
///
/// # Examples
///
/// ```
/// use typeck_lang::Severity;
///
/// assert!(Severity::Warning < Severity::Error);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Severity {
    /// Legal, but almost certainly a mistake (an unreachable `match` arm).
    Warning,
    /// The program is ill-typed under the profile.
    Error,
}

/// What a diagnostic says. Types are ids into the
/// [`Typed`](crate::Typed)'s store, resolved (no inference variables).
///
/// # Examples
///
/// ```
/// use typeck_lang::{DiagnosticKind, TypeId};
///
/// let k = DiagnosticKind::Mismatch { expected: TypeId::UNIT, found: TypeId::NULL };
/// assert_eq!(k.code(), "T0001");
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DiagnosticKind {
    /// The expression's type does not fit its context.
    Mismatch {
        /// What the context requires.
        expected: TypeId,
        /// What the expression has.
        found: TypeId,
    },
    /// A static profile needs a declared type here (parameter, return of a
    /// signature slot written `_`, field, constant, global).
    MissingAnnotation,
    /// A name that resolution never resolved.
    Unresolved,
    /// A host or other-unit definition whose type was not declared to the
    /// checker.
    UnknownExtern {
        /// The name as written (last segment).
        name: Option<Symbol>,
    },
    /// The path names something that is not a value (a type, a module, a
    /// record with named fields).
    NotAValue,
    /// The path names something that is not a type.
    NotAType,
    /// Wrong number of arguments or pattern elements.
    Arity {
        /// The fewest accepted.
        min: u32,
        /// The most accepted (`None`: unbounded).
        max: Option<u32>,
        /// How many were given.
        found: u32,
    },
    /// A named argument that matches no parameter.
    UnknownNamedArg {
        /// The argument name.
        name: Symbol,
    },
    /// A parameter given twice (positionally and by name).
    DuplicateArg {
        /// The parameter name.
        name: Option<Symbol>,
    },
    /// A required parameter not given.
    MissingArg {
        /// The first missing parameter's name.
        name: Option<Symbol>,
        /// How many are missing.
        count: u32,
    },
    /// Calling a value whose type is not a function.
    NotCallable {
        /// The callee's type.
        ty: TypeId,
    },
    /// No such field.
    NoField {
        /// The accessed type.
        ty: TypeId,
        /// The member.
        member: Member,
    },
    /// No such method or associated item.
    NoMethod {
        /// The receiver or owner type.
        ty: TypeId,
        /// The name.
        name: Symbol,
    },
    /// Several impl blocks define the method.
    AmbiguousMethod {
        /// The receiver type.
        ty: TypeId,
        /// The name.
        name: Symbol,
    },
    /// A record literal or pattern names a field the record does not have.
    UnknownField {
        /// The record type.
        ty: TypeId,
        /// The field name.
        name: Symbol,
    },
    /// A record literal leaves out fields that have no default.
    MissingFields {
        /// The first missing field.
        first: Symbol,
        /// How many are missing.
        count: u32,
    },
    /// A union literal must initialise exactly one field.
    UnionLiteral {
        /// How many it initialises.
        count: u32,
    },
    /// Indexing a type that cannot be indexed.
    NotIndexable {
        /// The indexed type.
        ty: TypeId,
    },
    /// Dereferencing a type that is not a reference or pointer.
    CannotDeref {
        /// The type.
        ty: TypeId,
    },
    /// Awaiting a value that is not awaitable.
    NotAwaitable {
        /// The type.
        ty: TypeId,
    },
    /// An operation (OPS) is not defined for the operand type.
    OpType {
        /// The operation.
        op: OpKind,
        /// The offending operand's type.
        ty: TypeId,
    },
    /// The `promote` overflow policy on an operation whose result is
    /// statically typed (`promote` is only for dynamic results).
    PromoteOnStatic {
        /// The operation (`None`: a cast).
        op: Option<OpKind>,
    },
    /// A conversion op whose source or target width is wrong
    /// (`sext` to a narrower type, `bitcast` between different widths).
    BadConversion {
        /// The operation.
        op: OpKind,
        /// The source type.
        from: TypeId,
    },
    /// An `as` cast the profile does not allow.
    InvalidCast {
        /// The source type.
        from: TypeId,
        /// The target type.
        to: TypeId,
    },
    /// An integer literal outside the range of the type it got.
    LiteralOutOfRange {
        /// The literal's type.
        ty: TypeId,
    },
    /// No type could be inferred; add an annotation.
    CannotInfer,
    /// An operation on a dynamic (`any`) value under a static profile;
    /// cast or type-test it first.
    DynamicOperation,
    /// A dynamic-only form (`$$x`, `$o->$m()`, `$a = &$b`, `$a[]`) under a
    /// static profile.
    DynamicForm,
    /// Using a nullable value as if it were not null.
    NullableAccess {
        /// The nullable type.
        ty: TypeId,
    },
    /// A `match` that leaves values uncovered. The values are listed by
    /// [`Typed::witnesses`](crate::Typed::witnesses) and in the message.
    NonExhaustive {
        /// The variant the first missing value starts with, when the
        /// scrutinee is a sum.
        missing: Option<VariantId>,
    },
    /// A `match` arm no value reaches (a warning).
    UnreachableArm,
    /// An or-pattern alternative that only matches values earlier
    /// alternatives or arms already match (a warning).
    RedundantAlternative,
    /// A bound, supertrait, or `impl` header names something that is not an
    /// interface.
    NotAnInterface,
    /// The wrong number of generic arguments.
    GenericArity {
        /// How many the item declares.
        expected: u32,
        /// How many are written.
        found: u32,
    },
    /// `T::Name` or `Iface<Name = ..>` where no interface in reach declares
    /// an associated type `Name`.
    NoAssocType {
        /// The name.
        name: Symbol,
    },
    /// `T::Name` where several interfaces of `T` declare `Name`; qualify it
    /// (`<T as Iface>::Name`).
    AmbiguousAssocType {
        /// The name.
        name: Symbol,
    },
    /// A type does not implement an interface it must.
    Unsatisfied {
        /// The type.
        ty: TypeId,
        /// The interface (with its arguments).
        interface: TypeId,
    },
    /// Several implementations of an interface apply to a type.
    AmbiguousImpl {
        /// The type.
        ty: TypeId,
        /// The interface.
        interface: TypeId,
    },
    /// Two implementations of one interface overlap (reported at the
    /// later one).
    OverlappingImpls {
        /// The earlier implementation.
        other: ItemId,
    },
    /// An implementation lacks members its interface requires.
    MissingMember {
        /// The first missing member.
        name: Symbol,
        /// How many are missing.
        count: u32,
    },
    /// An implementation defines a member its interface does not declare.
    NotAMember {
        /// The interface.
        interface: TypeId,
        /// The member.
        name: Symbol,
    },
    /// An interface name used as a type under `Traits` polymorphism (write
    /// `dyn Iface` or `impl Iface`).
    InterfaceAsType,
    /// `impl Trait` outside a function's parameter or return types.
    ImplTraitPosition,
    /// A `dyn` type that leaves an associated type of its interface
    /// unspecified (`dyn Iterator` without `Item = ..`).
    MissingAssocBinding {
        /// The associated type.
        name: Symbol,
    },
    /// Instantiating a generic item needs ever-larger instances
    /// (polymorphic recursion), which copies cannot implement: the plan
    /// stops at the budget's trait depth.
    RecursiveInstantiation,
    /// A `?` (through [`TryHook::Intrinsic`](crate::TryHook)) on a value, or
    /// in a function, that is not a carrier of the same kind.
    TryCarrier {
        /// The offending type.
        ty: TypeId,
    },
    /// A feature this version does not check (see [`Feature`]).
    Unsupported {
        /// Which feature.
        feature: Feature,
    },
    /// A type alias that expands to itself.
    CyclicAlias,
    /// A class whose base classes form a cycle.
    InheritanceCycle,
    /// A constant context (array length, repeat count) that is not a
    /// compile-time integer.
    NotConstant,
    /// A type test that can never succeed.
    ImpossibleTypeTest {
        /// The tested value's type.
        from: TypeId,
        /// The tested-for type.
        to: TypeId,
    },
    /// A by-reference parameter given a value instead of a place argument.
    ByRefNeedsPlace,
    /// Assigning to something that is not assignable (a function, constant,
    /// or constructor).
    NotAssignable,
}

impl DiagnosticKind {
    /// The stable code.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(typeck_lang::DiagnosticKind::CannotInfer.code(), "T0023");
    /// ```
    #[must_use]
    pub const fn code(&self) -> &'static str {
        match self {
            Self::Mismatch { .. } => "T0001",
            Self::MissingAnnotation => "T0002",
            Self::Unresolved => "T0003",
            Self::UnknownExtern { .. } => "T0004",
            Self::NotAValue => "T0005",
            Self::NotAType => "T0006",
            Self::Arity { .. } => "T0007",
            Self::UnknownNamedArg { .. } => "T0008",
            Self::DuplicateArg { .. } => "T0009",
            Self::MissingArg { .. } => "T0010",
            Self::NotCallable { .. } => "T0011",
            Self::NoField { .. } => "T0012",
            Self::NoMethod { .. } => "T0013",
            Self::UnknownField { .. } => "T0014",
            Self::MissingFields { .. } => "T0015",
            Self::NotIndexable { .. } => "T0016",
            Self::CannotDeref { .. } => "T0017",
            Self::OpType { .. } => "T0018",
            Self::PromoteOnStatic { .. } => "T0019",
            Self::InvalidCast { .. } => "T0020",
            Self::BadConversion { .. } => "T0021",
            Self::LiteralOutOfRange { .. } => "T0022",
            Self::CannotInfer => "T0023",
            Self::DynamicOperation => "T0024",
            Self::DynamicForm => "T0025",
            Self::NullableAccess { .. } => "T0026",
            Self::NonExhaustive { .. } => "T0027",
            Self::Unsupported { .. } => "T0028",
            Self::CyclicAlias => "T0029",
            Self::NotConstant => "T0030",
            Self::ImpossibleTypeTest { .. } => "T0032",
            Self::AmbiguousMethod { .. } => "T0033",
            Self::ByRefNeedsPlace => "T0034",
            Self::InheritanceCycle => "T0036",
            Self::NotAwaitable { .. } => "T0037",
            Self::NotAssignable => "T0038",
            Self::UnionLiteral { .. } => "T0039",
            Self::UnreachableArm => "T0040",
            Self::RedundantAlternative => "T0041",
            Self::NotAnInterface => "T0042",
            Self::GenericArity { .. } => "T0043",
            Self::NoAssocType { .. } => "T0044",
            Self::AmbiguousAssocType { .. } => "T0045",
            Self::Unsatisfied { .. } => "T0046",
            Self::AmbiguousImpl { .. } => "T0047",
            Self::OverlappingImpls { .. } => "T0048",
            Self::MissingMember { .. } => "T0049",
            Self::NotAMember { .. } => "T0050",
            Self::InterfaceAsType => "T0051",
            Self::ImplTraitPosition => "T0052",
            Self::MissingAssocBinding { .. } => "T0053",
            Self::RecursiveInstantiation => "T0054",
            Self::TryCarrier { .. } => "T0055",
        }
    }

    /// Calls `f` on every type the kind mentions (so finalisation can resolve
    /// them).
    pub(crate) fn types_mut(&mut self, mut f: impl FnMut(&mut TypeId)) {
        match self {
            Self::Mismatch { expected, found } => {
                f(expected);
                f(found);
            }
            Self::InvalidCast { from, to } | Self::ImpossibleTypeTest { from, to } => {
                f(from);
                f(to);
            }
            Self::Unsatisfied { ty, interface } | Self::AmbiguousImpl { ty, interface } => {
                f(ty);
                f(interface);
            }
            Self::NotAMember { interface, .. } => f(interface),
            Self::TryCarrier { ty } => f(ty),
            Self::NotCallable { ty }
            | Self::NoField { ty, .. }
            | Self::NoMethod { ty, .. }
            | Self::AmbiguousMethod { ty, .. }
            | Self::UnknownField { ty, .. }
            | Self::NotIndexable { ty }
            | Self::CannotDeref { ty }
            | Self::NotAwaitable { ty }
            | Self::OpType { ty, .. }
            | Self::LiteralOutOfRange { ty }
            | Self::NullableAccess { ty } => f(ty),
            Self::BadConversion { from, .. } => f(from),
            _ => {}
        }
    }

    pub(crate) fn render<L: Lookup>(&self, types: &Types, names: &L, out: &mut String) {
        let ty = |t: TypeId, out: &mut String| {
            out.push('`');
            types.render(t, names, out);
            out.push('`');
        };
        let name = |s: Option<Symbol>, out: &mut String| {
            out.push('`');
            match s.and_then(|s| names.resolve_with(s, |t| out.push_str(t))) {
                Some(()) => {}
                None => out.push('?'),
            }
            out.push('`');
        };
        match *self {
            Self::Mismatch { expected, found } => {
                out.push_str("mismatched types: expected ");
                ty(expected, out);
                out.push_str(", found ");
                ty(found, out);
            }
            Self::MissingAnnotation => out.push_str("a type annotation is required here"),
            Self::Unresolved => out.push_str("unresolved name"),
            Self::UnknownExtern { name: n } => {
                out.push_str("the type of ");
                name(n, out);
                out.push_str(" is not declared to the checker");
            }
            Self::NotAValue => out.push_str("this names a type or module, not a value"),
            Self::NotAType => out.push_str("this does not name a type"),
            Self::Arity { min, max, found } => {
                let _ = match max {
                    Some(max) if max == min => {
                        write!(out, "expected {min} arguments, found {found}")
                    }
                    Some(max) => write!(out, "expected {min} to {max} arguments, found {found}"),
                    None => write!(out, "expected at least {min} arguments, found {found}"),
                };
            }
            Self::UnknownNamedArg { name: n } => {
                out.push_str("no parameter named ");
                name(Some(n), out);
            }
            Self::DuplicateArg { name: n } => {
                out.push_str("parameter ");
                name(n, out);
                out.push_str(" is given more than once");
            }
            Self::MissingArg { name: n, count } => {
                out.push_str("missing argument for parameter ");
                name(n, out);
                if count > 1 {
                    let _ = write!(out, " and {} more", count - 1);
                }
            }
            Self::NotCallable { ty: t } => {
                ty(t, out);
                out.push_str(" is not callable");
            }
            Self::NoField { ty: t, member } => {
                ty(t, out);
                out.push_str(" has no field ");
                match member {
                    Member::Named(s) => name(Some(s), out),
                    Member::Index(i) => {
                        let _ = write!(out, "`{i}`");
                    }
                }
            }
            Self::NoMethod { ty: t, name: n } => {
                ty(t, out);
                out.push_str(" has no method or associated item ");
                name(Some(n), out);
            }
            Self::AmbiguousMethod { ty: t, name: n } => {
                out.push_str("several impl blocks of ");
                ty(t, out);
                out.push_str(" define ");
                name(Some(n), out);
            }
            Self::UnknownField { ty: t, name: n } => {
                ty(t, out);
                out.push_str(" has no field ");
                name(Some(n), out);
            }
            Self::MissingFields { first, count } => {
                out.push_str("missing field ");
                name(Some(first), out);
                if count > 1 {
                    let _ = write!(out, " and {} more", count - 1);
                }
            }
            Self::UnionLiteral { count } => {
                let _ = write!(
                    out,
                    "a union literal initialises exactly one field, found {count}"
                );
            }
            Self::NotIndexable { ty: t } => {
                ty(t, out);
                out.push_str(" cannot be indexed");
            }
            Self::CannotDeref { ty: t } => {
                ty(t, out);
                out.push_str(" cannot be dereferenced");
            }
            Self::NotAwaitable { ty: t } => {
                ty(t, out);
                out.push_str(" is not awaitable");
            }
            Self::OpType { op, ty: t } => {
                let _ = write!(out, "`{}` is not defined for ", op.name());
                ty(t, out);
            }
            Self::PromoteOnStatic { op } => {
                out.push_str("the `promote` overflow policy needs a dynamically typed result");
                if let Some(op) = op {
                    let _ = write!(out, " (`{}`)", op.name());
                }
            }
            Self::BadConversion { op, from } => {
                let _ = write!(out, "`{}` cannot convert from ", op.name());
                ty(from, out);
            }
            Self::InvalidCast { from, to } => {
                out.push_str("cannot cast ");
                ty(from, out);
                out.push_str(" to ");
                ty(to, out);
            }
            Self::LiteralOutOfRange { ty: t } => {
                out.push_str("literal out of range for ");
                ty(t, out);
            }
            Self::CannotInfer => out.push_str("cannot infer a type here; add an annotation"),
            Self::DynamicOperation => {
                out.push_str("operation on a dynamic `any` value; cast or type-test it first")
            }
            Self::DynamicForm => {
                out.push_str("this dynamic form is not allowed under a static profile");
            }
            Self::NullableAccess { ty: t } => {
                ty(t, out);
                out.push_str(" may be null");
            }
            Self::NonExhaustive { .. } => out.push_str("non-exhaustive match"),
            Self::UnreachableArm => out.push_str("unreachable match arm"),
            Self::RedundantAlternative => {
                out.push_str("this alternative only matches values already matched");
            }
            Self::NotAnInterface => out.push_str("this does not name an interface"),
            Self::GenericArity { expected, found } => {
                let _ = write!(out, "expected {expected} generic arguments, found {found}");
            }
            Self::NoAssocType { name: n } => {
                out.push_str("no associated type ");
                name(Some(n), out);
                out.push_str(" in reach");
            }
            Self::AmbiguousAssocType { name: n } => {
                out.push_str("several interfaces declare an associated type ");
                name(Some(n), out);
            }
            Self::Unsatisfied { ty: t, interface } => {
                ty(t, out);
                out.push_str(" does not implement ");
                ty(interface, out);
            }
            Self::AmbiguousImpl { ty: t, interface } => {
                out.push_str("several implementations of ");
                ty(interface, out);
                out.push_str(" apply to ");
                ty(t, out);
            }
            Self::OverlappingImpls { .. } => {
                out.push_str("this implementation overlaps an earlier one");
            }
            Self::MissingMember { name: n, count } => {
                out.push_str("missing interface member ");
                name(Some(n), out);
                if count > 1 {
                    let _ = write!(out, " and {} more", count - 1);
                }
            }
            Self::NotAMember { interface, name: n } => {
                name(Some(n), out);
                out.push_str(" is not a member of ");
                ty(interface, out);
            }
            Self::InterfaceAsType => {
                out.push_str("an interface is not a type here; write `dyn` or `impl` before it");
            }
            Self::ImplTraitPosition => {
                out.push_str("`impl` types are allowed only in function parameters and results");
            }
            Self::MissingAssocBinding { name: n } => {
                out.push_str("the associated type ");
                name(Some(n), out);
                out.push_str(" must be specified");
            }
            Self::RecursiveInstantiation => {
                out.push_str("instantiating this generic item recurses without bound");
            }
            Self::TryCarrier { ty: t } => {
                ty(t, out);
                out.push_str(" cannot propagate a failure here");
            }
            Self::Unsupported { feature } => {
                let _ = write!(
                    out,
                    "{} are not supported by this profile in this version",
                    feature.name()
                );
            }
            Self::CyclicAlias => out.push_str("type alias expands to itself"),
            Self::InheritanceCycle => out.push_str("class inherits from itself"),
            Self::NotConstant => out.push_str("expected a compile-time integer constant"),
            Self::ImpossibleTypeTest { from, to } => {
                out.push_str("a value of type ");
                ty(from, out);
                out.push_str(" can never be a ");
                ty(to, out);
            }
            Self::ByRefNeedsPlace => {
                out.push_str("a by-reference parameter needs a place argument");
            }
            Self::NotAssignable => out.push_str("cannot assign to this"),
        }
    }
}

/// One finding about the checked program.
///
/// [`Typed::message`](crate::Typed::message) renders it as text.
///
/// # Examples
///
/// ```
/// use hir_lang::{BinderKind, Builder, Name, NodeRef};
/// use intern_lang::Interner;
/// use typeck_lang::{check, DiagnosticKind, Profile};
///
/// let mut names = Interner::new();
/// let mut b = Builder::new();
/// // fn main() { let x; }   -- nothing determines x's type
/// let x = b.new_binder(Name::new(names.intern("x")), BinderKind::Local);
/// let pat = b.bind(x);
/// let stmt = b.let_stmt(pat, None);
/// let body = b.block(&[stmt], None);
/// let main = b.func(Name::new(names.intern("main")), &[], body);
/// let root = b.module(None, &[main]);
/// let hir = b.finish(root)?;
///
/// let typed = check(&hir, &Profile::static_explicit()).unwrap();
/// let d = typed.diagnostics()[0];
/// assert_eq!(d.kind, DiagnosticKind::CannotInfer);
/// assert_eq!(d.kind.code(), "T0023");
/// assert_eq!(d.node, NodeRef::Pat(pat));
/// assert_eq!(d.origin, hir.origin(NodeRef::Pat(pat)));
/// # Ok::<(), hir_lang::HirError>(())
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Diagnostic {
    /// What is wrong.
    pub kind: DiagnosticKind,
    /// The node it is about.
    pub node: NodeRef,
    /// The node's origin: source span and expansion.
    pub origin: Origin,
    /// Error or warning.
    pub severity: Severity,
}

#[cfg(test)]
mod tests {
    use alloc::{string::String, vec::Vec};

    use hir_lang::{Member, OpKind, Prim};
    use intern_lang::Interner;

    use super::*;

    fn all_kinds() -> Vec<DiagnosticKind> {
        let mut names = Interner::new();
        let s = names.intern("n");
        let t = TypeId::prim(Prim::I32);
        alloc::vec![
            DiagnosticKind::Mismatch {
                expected: t,
                found: t
            },
            DiagnosticKind::MissingAnnotation,
            DiagnosticKind::Unresolved,
            DiagnosticKind::UnknownExtern { name: Some(s) },
            DiagnosticKind::NotAValue,
            DiagnosticKind::NotAType,
            DiagnosticKind::Arity {
                min: 1,
                max: Some(2),
                found: 3
            },
            DiagnosticKind::UnknownNamedArg { name: s },
            DiagnosticKind::DuplicateArg { name: Some(s) },
            DiagnosticKind::MissingArg {
                name: Some(s),
                count: 2
            },
            DiagnosticKind::NotCallable { ty: t },
            DiagnosticKind::NoField {
                ty: t,
                member: Member::Index(0)
            },
            DiagnosticKind::NoMethod { ty: t, name: s },
            DiagnosticKind::AmbiguousMethod { ty: t, name: s },
            DiagnosticKind::UnknownField { ty: t, name: s },
            DiagnosticKind::MissingFields { first: s, count: 3 },
            DiagnosticKind::UnionLiteral { count: 2 },
            DiagnosticKind::NotIndexable { ty: t },
            DiagnosticKind::CannotDeref { ty: t },
            DiagnosticKind::NotAwaitable { ty: t },
            DiagnosticKind::OpType {
                op: OpKind::Add,
                ty: t
            },
            DiagnosticKind::PromoteOnStatic { op: None },
            DiagnosticKind::BadConversion {
                op: OpKind::Sext(Prim::I8),
                from: t
            },
            DiagnosticKind::InvalidCast { from: t, to: t },
            DiagnosticKind::LiteralOutOfRange { ty: t },
            DiagnosticKind::CannotInfer,
            DiagnosticKind::DynamicOperation,
            DiagnosticKind::DynamicForm,
            DiagnosticKind::NullableAccess { ty: t },
            DiagnosticKind::NonExhaustive { missing: None },
            DiagnosticKind::Unsupported {
                feature: Feature::GenericAssocTypes
            },
            DiagnosticKind::UnreachableArm,
            DiagnosticKind::RedundantAlternative,
            DiagnosticKind::NotAnInterface,
            DiagnosticKind::GenericArity {
                expected: 1,
                found: 2
            },
            DiagnosticKind::NoAssocType { name: s },
            DiagnosticKind::AmbiguousAssocType { name: s },
            DiagnosticKind::Unsatisfied {
                ty: t,
                interface: t
            },
            DiagnosticKind::AmbiguousImpl {
                ty: t,
                interface: t
            },
            DiagnosticKind::MissingMember { name: s, count: 2 },
            DiagnosticKind::NotAMember {
                interface: t,
                name: s
            },
            DiagnosticKind::InterfaceAsType,
            DiagnosticKind::ImplTraitPosition,
            DiagnosticKind::MissingAssocBinding { name: s },
            DiagnosticKind::RecursiveInstantiation,
            DiagnosticKind::TryCarrier { ty: t },
            DiagnosticKind::CyclicAlias,
            DiagnosticKind::InheritanceCycle,
            DiagnosticKind::NotConstant,
            DiagnosticKind::ImpossibleTypeTest { from: t, to: t },
            DiagnosticKind::ByRefNeedsPlace,
            DiagnosticKind::NotAssignable,
        ]
    }

    #[test]
    fn test_codes_are_unique_and_messages_render() {
        let names = Interner::new();
        let types = Types::new();
        let mut kinds = all_kinds();
        kinds.extend(
            hir_lang::ItemId::from_index(0).map(|other| DiagnosticKind::OverlappingImpls { other }),
        );
        let mut codes: Vec<&str> = kinds.iter().map(DiagnosticKind::code).collect();
        codes.sort_unstable();
        let n = codes.len();
        codes.dedup();
        assert_eq!(codes.len(), n, "duplicate diagnostic codes");
        for k in &kinds {
            let mut out = String::new();
            k.render(&types, &names, &mut out);
            assert!(!out.is_empty(), "{k:?}");
        }
    }

    #[test]
    fn test_arity_wording() {
        let names = Interner::new();
        let types = Types::new();
        let render = |k: DiagnosticKind| {
            let mut out = String::new();
            k.render(&types, &names, &mut out);
            out
        };
        assert_eq!(
            render(DiagnosticKind::Arity {
                min: 2,
                max: Some(2),
                found: 1
            }),
            "expected 2 arguments, found 1"
        );
        assert_eq!(
            render(DiagnosticKind::Arity {
                min: 1,
                max: Some(3),
                found: 5
            }),
            "expected 1 to 3 arguments, found 5"
        );
        assert_eq!(
            render(DiagnosticKind::Arity {
                min: 1,
                max: None,
                found: 0
            }),
            "expected at least 1 arguments, found 0"
        );
        assert_eq!(
            render(DiagnosticKind::UnknownExtern { name: None }),
            "the type of `?` is not declared to the checker"
        );
    }

    #[test]
    fn test_feature_names() {
        for f in [Feature::GenericAssocTypes, Feature::LongAssocPaths] {
            assert!(!f.name().is_empty());
        }
    }
}