Skip to main content

typeck_lang/
diag.rs

1//! Typed diagnostics.
2//!
3//! A diagnostic is data: a [`DiagnosticKind`] (with the types and names
4//! involved), the HIR node it is about, and that node's [`Origin`] (source
5//! span and expansion). [`Typed::message`](crate::Typed::message) renders the
6//! text. Each kind has a stable code (`T0001`...).
7
8use alloc::string::String;
9use core::fmt::Write as _;
10
11use hir_lang::{ItemId, Member, NodeRef, OpKind, Origin, Symbol, VariantId};
12use intern_lang::Lookup;
13
14use crate::types::{TypeId, Types};
15
16/// A language feature the checker recognises but this version does not
17/// check. Each is recorded in `dev/ROADMAP.md`.
18///
19/// # Examples
20///
21/// ```
22/// use typeck_lang::Feature;
23///
24/// assert_eq!(Feature::GenericAssocTypes.name(), "generic associated types");
25/// ```
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27#[non_exhaustive]
28pub enum Feature {
29    /// Associated types with generic parameters of their own (`type
30    /// Item<'a>`, `type Map<T>`).
31    GenericAssocTypes,
32    /// Multi-segment unresolved paths (`T::Assoc::method`): resolution by
33    /// type covers one trailing segment.
34    LongAssocPaths,
35}
36
37impl Feature {
38    /// A short name for messages.
39    ///
40    /// # Examples
41    ///
42    /// ```
43    /// assert_eq!(typeck_lang::Feature::LongAssocPaths.name(), "multi-segment associated paths");
44    /// ```
45    #[must_use]
46    pub const fn name(self) -> &'static str {
47        match self {
48            Self::GenericAssocTypes => "generic associated types",
49            Self::LongAssocPaths => "multi-segment associated paths",
50        }
51    }
52}
53
54/// How serious a diagnostic is.
55///
56/// # Examples
57///
58/// ```
59/// use typeck_lang::Severity;
60///
61/// assert!(Severity::Warning < Severity::Error);
62/// ```
63#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
64pub enum Severity {
65    /// Legal, but almost certainly a mistake (an unreachable `match` arm).
66    Warning,
67    /// The program is ill-typed under the profile.
68    Error,
69}
70
71/// What a diagnostic says. Types are ids into the
72/// [`Typed`](crate::Typed)'s store, resolved (no inference variables).
73///
74/// # Examples
75///
76/// ```
77/// use typeck_lang::{DiagnosticKind, TypeId};
78///
79/// let k = DiagnosticKind::Mismatch { expected: TypeId::UNIT, found: TypeId::NULL };
80/// assert_eq!(k.code(), "T0001");
81/// ```
82#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
83#[non_exhaustive]
84pub enum DiagnosticKind {
85    /// The expression's type does not fit its context.
86    Mismatch {
87        /// What the context requires.
88        expected: TypeId,
89        /// What the expression has.
90        found: TypeId,
91    },
92    /// A static profile needs a declared type here (parameter, return of a
93    /// signature slot written `_`, field, constant, global).
94    MissingAnnotation,
95    /// A name that resolution never resolved.
96    Unresolved,
97    /// A host or other-unit definition whose type was not declared to the
98    /// checker.
99    UnknownExtern {
100        /// The name as written (last segment).
101        name: Option<Symbol>,
102    },
103    /// The path names something that is not a value (a type, a module, a
104    /// record with named fields).
105    NotAValue,
106    /// The path names something that is not a type.
107    NotAType,
108    /// Wrong number of arguments or pattern elements.
109    Arity {
110        /// The fewest accepted.
111        min: u32,
112        /// The most accepted (`None`: unbounded).
113        max: Option<u32>,
114        /// How many were given.
115        found: u32,
116    },
117    /// A named argument that matches no parameter.
118    UnknownNamedArg {
119        /// The argument name.
120        name: Symbol,
121    },
122    /// A parameter given twice (positionally and by name).
123    DuplicateArg {
124        /// The parameter name.
125        name: Option<Symbol>,
126    },
127    /// A required parameter not given.
128    MissingArg {
129        /// The first missing parameter's name.
130        name: Option<Symbol>,
131        /// How many are missing.
132        count: u32,
133    },
134    /// Calling a value whose type is not a function.
135    NotCallable {
136        /// The callee's type.
137        ty: TypeId,
138    },
139    /// No such field.
140    NoField {
141        /// The accessed type.
142        ty: TypeId,
143        /// The member.
144        member: Member,
145    },
146    /// No such method or associated item.
147    NoMethod {
148        /// The receiver or owner type.
149        ty: TypeId,
150        /// The name.
151        name: Symbol,
152    },
153    /// Several impl blocks define the method.
154    AmbiguousMethod {
155        /// The receiver type.
156        ty: TypeId,
157        /// The name.
158        name: Symbol,
159    },
160    /// A record literal or pattern names a field the record does not have.
161    UnknownField {
162        /// The record type.
163        ty: TypeId,
164        /// The field name.
165        name: Symbol,
166    },
167    /// A record literal leaves out fields that have no default.
168    MissingFields {
169        /// The first missing field.
170        first: Symbol,
171        /// How many are missing.
172        count: u32,
173    },
174    /// A union literal must initialise exactly one field.
175    UnionLiteral {
176        /// How many it initialises.
177        count: u32,
178    },
179    /// Indexing a type that cannot be indexed.
180    NotIndexable {
181        /// The indexed type.
182        ty: TypeId,
183    },
184    /// Dereferencing a type that is not a reference or pointer.
185    CannotDeref {
186        /// The type.
187        ty: TypeId,
188    },
189    /// Awaiting a value that is not awaitable.
190    NotAwaitable {
191        /// The type.
192        ty: TypeId,
193    },
194    /// An operation (OPS) is not defined for the operand type.
195    OpType {
196        /// The operation.
197        op: OpKind,
198        /// The offending operand's type.
199        ty: TypeId,
200    },
201    /// The `promote` overflow policy on an operation whose result is
202    /// statically typed (`promote` is only for dynamic results).
203    PromoteOnStatic {
204        /// The operation (`None`: a cast).
205        op: Option<OpKind>,
206    },
207    /// A conversion op whose source or target width is wrong
208    /// (`sext` to a narrower type, `bitcast` between different widths).
209    BadConversion {
210        /// The operation.
211        op: OpKind,
212        /// The source type.
213        from: TypeId,
214    },
215    /// An `as` cast the profile does not allow.
216    InvalidCast {
217        /// The source type.
218        from: TypeId,
219        /// The target type.
220        to: TypeId,
221    },
222    /// An integer literal outside the range of the type it got.
223    LiteralOutOfRange {
224        /// The literal's type.
225        ty: TypeId,
226    },
227    /// No type could be inferred; add an annotation.
228    CannotInfer,
229    /// An operation on a dynamic (`any`) value under a static profile;
230    /// cast or type-test it first.
231    DynamicOperation,
232    /// A dynamic-only form (`$$x`, `$o->$m()`, `$a = &$b`, `$a[]`) under a
233    /// static profile.
234    DynamicForm,
235    /// Using a nullable value as if it were not null.
236    NullableAccess {
237        /// The nullable type.
238        ty: TypeId,
239    },
240    /// A `match` that leaves values uncovered. The values are listed by
241    /// [`Typed::witnesses`](crate::Typed::witnesses) and in the message.
242    NonExhaustive {
243        /// The variant the first missing value starts with, when the
244        /// scrutinee is a sum.
245        missing: Option<VariantId>,
246    },
247    /// A `match` arm no value reaches (a warning).
248    UnreachableArm,
249    /// An or-pattern alternative that only matches values earlier
250    /// alternatives or arms already match (a warning).
251    RedundantAlternative,
252    /// A bound, supertrait, or `impl` header names something that is not an
253    /// interface.
254    NotAnInterface,
255    /// The wrong number of generic arguments.
256    GenericArity {
257        /// How many the item declares.
258        expected: u32,
259        /// How many are written.
260        found: u32,
261    },
262    /// `T::Name` or `Iface<Name = ..>` where no interface in reach declares
263    /// an associated type `Name`.
264    NoAssocType {
265        /// The name.
266        name: Symbol,
267    },
268    /// `T::Name` where several interfaces of `T` declare `Name`; qualify it
269    /// (`<T as Iface>::Name`).
270    AmbiguousAssocType {
271        /// The name.
272        name: Symbol,
273    },
274    /// A type does not implement an interface it must.
275    Unsatisfied {
276        /// The type.
277        ty: TypeId,
278        /// The interface (with its arguments).
279        interface: TypeId,
280    },
281    /// Several implementations of an interface apply to a type.
282    AmbiguousImpl {
283        /// The type.
284        ty: TypeId,
285        /// The interface.
286        interface: TypeId,
287    },
288    /// Two implementations of one interface overlap (reported at the
289    /// later one).
290    OverlappingImpls {
291        /// The earlier implementation.
292        other: ItemId,
293    },
294    /// An implementation lacks members its interface requires.
295    MissingMember {
296        /// The first missing member.
297        name: Symbol,
298        /// How many are missing.
299        count: u32,
300    },
301    /// An implementation defines a member its interface does not declare.
302    NotAMember {
303        /// The interface.
304        interface: TypeId,
305        /// The member.
306        name: Symbol,
307    },
308    /// An interface name used as a type under `Traits` polymorphism (write
309    /// `dyn Iface` or `impl Iface`).
310    InterfaceAsType,
311    /// `impl Trait` outside a function's parameter or return types.
312    ImplTraitPosition,
313    /// A `dyn` type that leaves an associated type of its interface
314    /// unspecified (`dyn Iterator` without `Item = ..`).
315    MissingAssocBinding {
316        /// The associated type.
317        name: Symbol,
318    },
319    /// Instantiating a generic item needs ever-larger instances
320    /// (polymorphic recursion), which copies cannot implement: the plan
321    /// stops at the budget's trait depth.
322    RecursiveInstantiation,
323    /// A `?` (through [`TryHook::Intrinsic`](crate::TryHook)) on a value, or
324    /// in a function, that is not a carrier of the same kind.
325    TryCarrier {
326        /// The offending type.
327        ty: TypeId,
328    },
329    /// A feature this version does not check (see [`Feature`]).
330    Unsupported {
331        /// Which feature.
332        feature: Feature,
333    },
334    /// A type alias that expands to itself.
335    CyclicAlias,
336    /// A class whose base classes form a cycle.
337    InheritanceCycle,
338    /// A constant context (array length, repeat count) that is not a
339    /// compile-time integer.
340    NotConstant,
341    /// A type test that can never succeed.
342    ImpossibleTypeTest {
343        /// The tested value's type.
344        from: TypeId,
345        /// The tested-for type.
346        to: TypeId,
347    },
348    /// A by-reference parameter given a value instead of a place argument.
349    ByRefNeedsPlace,
350    /// Assigning to something that is not assignable (a function, constant,
351    /// or constructor).
352    NotAssignable,
353}
354
355impl DiagnosticKind {
356    /// The stable code.
357    ///
358    /// # Examples
359    ///
360    /// ```
361    /// assert_eq!(typeck_lang::DiagnosticKind::CannotInfer.code(), "T0023");
362    /// ```
363    #[must_use]
364    pub const fn code(&self) -> &'static str {
365        match self {
366            Self::Mismatch { .. } => "T0001",
367            Self::MissingAnnotation => "T0002",
368            Self::Unresolved => "T0003",
369            Self::UnknownExtern { .. } => "T0004",
370            Self::NotAValue => "T0005",
371            Self::NotAType => "T0006",
372            Self::Arity { .. } => "T0007",
373            Self::UnknownNamedArg { .. } => "T0008",
374            Self::DuplicateArg { .. } => "T0009",
375            Self::MissingArg { .. } => "T0010",
376            Self::NotCallable { .. } => "T0011",
377            Self::NoField { .. } => "T0012",
378            Self::NoMethod { .. } => "T0013",
379            Self::UnknownField { .. } => "T0014",
380            Self::MissingFields { .. } => "T0015",
381            Self::NotIndexable { .. } => "T0016",
382            Self::CannotDeref { .. } => "T0017",
383            Self::OpType { .. } => "T0018",
384            Self::PromoteOnStatic { .. } => "T0019",
385            Self::InvalidCast { .. } => "T0020",
386            Self::BadConversion { .. } => "T0021",
387            Self::LiteralOutOfRange { .. } => "T0022",
388            Self::CannotInfer => "T0023",
389            Self::DynamicOperation => "T0024",
390            Self::DynamicForm => "T0025",
391            Self::NullableAccess { .. } => "T0026",
392            Self::NonExhaustive { .. } => "T0027",
393            Self::Unsupported { .. } => "T0028",
394            Self::CyclicAlias => "T0029",
395            Self::NotConstant => "T0030",
396            Self::ImpossibleTypeTest { .. } => "T0032",
397            Self::AmbiguousMethod { .. } => "T0033",
398            Self::ByRefNeedsPlace => "T0034",
399            Self::InheritanceCycle => "T0036",
400            Self::NotAwaitable { .. } => "T0037",
401            Self::NotAssignable => "T0038",
402            Self::UnionLiteral { .. } => "T0039",
403            Self::UnreachableArm => "T0040",
404            Self::RedundantAlternative => "T0041",
405            Self::NotAnInterface => "T0042",
406            Self::GenericArity { .. } => "T0043",
407            Self::NoAssocType { .. } => "T0044",
408            Self::AmbiguousAssocType { .. } => "T0045",
409            Self::Unsatisfied { .. } => "T0046",
410            Self::AmbiguousImpl { .. } => "T0047",
411            Self::OverlappingImpls { .. } => "T0048",
412            Self::MissingMember { .. } => "T0049",
413            Self::NotAMember { .. } => "T0050",
414            Self::InterfaceAsType => "T0051",
415            Self::ImplTraitPosition => "T0052",
416            Self::MissingAssocBinding { .. } => "T0053",
417            Self::RecursiveInstantiation => "T0054",
418            Self::TryCarrier { .. } => "T0055",
419        }
420    }
421
422    /// Calls `f` on every type the kind mentions (so finalisation can resolve
423    /// them).
424    pub(crate) fn types_mut(&mut self, mut f: impl FnMut(&mut TypeId)) {
425        match self {
426            Self::Mismatch { expected, found } => {
427                f(expected);
428                f(found);
429            }
430            Self::InvalidCast { from, to } | Self::ImpossibleTypeTest { from, to } => {
431                f(from);
432                f(to);
433            }
434            Self::Unsatisfied { ty, interface } | Self::AmbiguousImpl { ty, interface } => {
435                f(ty);
436                f(interface);
437            }
438            Self::NotAMember { interface, .. } => f(interface),
439            Self::TryCarrier { ty } => f(ty),
440            Self::NotCallable { ty }
441            | Self::NoField { ty, .. }
442            | Self::NoMethod { ty, .. }
443            | Self::AmbiguousMethod { ty, .. }
444            | Self::UnknownField { ty, .. }
445            | Self::NotIndexable { ty }
446            | Self::CannotDeref { ty }
447            | Self::NotAwaitable { ty }
448            | Self::OpType { ty, .. }
449            | Self::LiteralOutOfRange { ty }
450            | Self::NullableAccess { ty } => f(ty),
451            Self::BadConversion { from, .. } => f(from),
452            _ => {}
453        }
454    }
455
456    pub(crate) fn render<L: Lookup>(&self, types: &Types, names: &L, out: &mut String) {
457        let ty = |t: TypeId, out: &mut String| {
458            out.push('`');
459            types.render(t, names, out);
460            out.push('`');
461        };
462        let name = |s: Option<Symbol>, out: &mut String| {
463            out.push('`');
464            match s.and_then(|s| names.resolve_with(s, |t| out.push_str(t))) {
465                Some(()) => {}
466                None => out.push('?'),
467            }
468            out.push('`');
469        };
470        match *self {
471            Self::Mismatch { expected, found } => {
472                out.push_str("mismatched types: expected ");
473                ty(expected, out);
474                out.push_str(", found ");
475                ty(found, out);
476            }
477            Self::MissingAnnotation => out.push_str("a type annotation is required here"),
478            Self::Unresolved => out.push_str("unresolved name"),
479            Self::UnknownExtern { name: n } => {
480                out.push_str("the type of ");
481                name(n, out);
482                out.push_str(" is not declared to the checker");
483            }
484            Self::NotAValue => out.push_str("this names a type or module, not a value"),
485            Self::NotAType => out.push_str("this does not name a type"),
486            Self::Arity { min, max, found } => {
487                let _ = match max {
488                    Some(max) if max == min => {
489                        write!(out, "expected {min} arguments, found {found}")
490                    }
491                    Some(max) => write!(out, "expected {min} to {max} arguments, found {found}"),
492                    None => write!(out, "expected at least {min} arguments, found {found}"),
493                };
494            }
495            Self::UnknownNamedArg { name: n } => {
496                out.push_str("no parameter named ");
497                name(Some(n), out);
498            }
499            Self::DuplicateArg { name: n } => {
500                out.push_str("parameter ");
501                name(n, out);
502                out.push_str(" is given more than once");
503            }
504            Self::MissingArg { name: n, count } => {
505                out.push_str("missing argument for parameter ");
506                name(n, out);
507                if count > 1 {
508                    let _ = write!(out, " and {} more", count - 1);
509                }
510            }
511            Self::NotCallable { ty: t } => {
512                ty(t, out);
513                out.push_str(" is not callable");
514            }
515            Self::NoField { ty: t, member } => {
516                ty(t, out);
517                out.push_str(" has no field ");
518                match member {
519                    Member::Named(s) => name(Some(s), out),
520                    Member::Index(i) => {
521                        let _ = write!(out, "`{i}`");
522                    }
523                }
524            }
525            Self::NoMethod { ty: t, name: n } => {
526                ty(t, out);
527                out.push_str(" has no method or associated item ");
528                name(Some(n), out);
529            }
530            Self::AmbiguousMethod { ty: t, name: n } => {
531                out.push_str("several impl blocks of ");
532                ty(t, out);
533                out.push_str(" define ");
534                name(Some(n), out);
535            }
536            Self::UnknownField { ty: t, name: n } => {
537                ty(t, out);
538                out.push_str(" has no field ");
539                name(Some(n), out);
540            }
541            Self::MissingFields { first, count } => {
542                out.push_str("missing field ");
543                name(Some(first), out);
544                if count > 1 {
545                    let _ = write!(out, " and {} more", count - 1);
546                }
547            }
548            Self::UnionLiteral { count } => {
549                let _ = write!(
550                    out,
551                    "a union literal initialises exactly one field, found {count}"
552                );
553            }
554            Self::NotIndexable { ty: t } => {
555                ty(t, out);
556                out.push_str(" cannot be indexed");
557            }
558            Self::CannotDeref { ty: t } => {
559                ty(t, out);
560                out.push_str(" cannot be dereferenced");
561            }
562            Self::NotAwaitable { ty: t } => {
563                ty(t, out);
564                out.push_str(" is not awaitable");
565            }
566            Self::OpType { op, ty: t } => {
567                let _ = write!(out, "`{}` is not defined for ", op.name());
568                ty(t, out);
569            }
570            Self::PromoteOnStatic { op } => {
571                out.push_str("the `promote` overflow policy needs a dynamically typed result");
572                if let Some(op) = op {
573                    let _ = write!(out, " (`{}`)", op.name());
574                }
575            }
576            Self::BadConversion { op, from } => {
577                let _ = write!(out, "`{}` cannot convert from ", op.name());
578                ty(from, out);
579            }
580            Self::InvalidCast { from, to } => {
581                out.push_str("cannot cast ");
582                ty(from, out);
583                out.push_str(" to ");
584                ty(to, out);
585            }
586            Self::LiteralOutOfRange { ty: t } => {
587                out.push_str("literal out of range for ");
588                ty(t, out);
589            }
590            Self::CannotInfer => out.push_str("cannot infer a type here; add an annotation"),
591            Self::DynamicOperation => {
592                out.push_str("operation on a dynamic `any` value; cast or type-test it first")
593            }
594            Self::DynamicForm => {
595                out.push_str("this dynamic form is not allowed under a static profile");
596            }
597            Self::NullableAccess { ty: t } => {
598                ty(t, out);
599                out.push_str(" may be null");
600            }
601            Self::NonExhaustive { .. } => out.push_str("non-exhaustive match"),
602            Self::UnreachableArm => out.push_str("unreachable match arm"),
603            Self::RedundantAlternative => {
604                out.push_str("this alternative only matches values already matched");
605            }
606            Self::NotAnInterface => out.push_str("this does not name an interface"),
607            Self::GenericArity { expected, found } => {
608                let _ = write!(out, "expected {expected} generic arguments, found {found}");
609            }
610            Self::NoAssocType { name: n } => {
611                out.push_str("no associated type ");
612                name(Some(n), out);
613                out.push_str(" in reach");
614            }
615            Self::AmbiguousAssocType { name: n } => {
616                out.push_str("several interfaces declare an associated type ");
617                name(Some(n), out);
618            }
619            Self::Unsatisfied { ty: t, interface } => {
620                ty(t, out);
621                out.push_str(" does not implement ");
622                ty(interface, out);
623            }
624            Self::AmbiguousImpl { ty: t, interface } => {
625                out.push_str("several implementations of ");
626                ty(interface, out);
627                out.push_str(" apply to ");
628                ty(t, out);
629            }
630            Self::OverlappingImpls { .. } => {
631                out.push_str("this implementation overlaps an earlier one");
632            }
633            Self::MissingMember { name: n, count } => {
634                out.push_str("missing interface member ");
635                name(Some(n), out);
636                if count > 1 {
637                    let _ = write!(out, " and {} more", count - 1);
638                }
639            }
640            Self::NotAMember { interface, name: n } => {
641                name(Some(n), out);
642                out.push_str(" is not a member of ");
643                ty(interface, out);
644            }
645            Self::InterfaceAsType => {
646                out.push_str("an interface is not a type here; write `dyn` or `impl` before it");
647            }
648            Self::ImplTraitPosition => {
649                out.push_str("`impl` types are allowed only in function parameters and results");
650            }
651            Self::MissingAssocBinding { name: n } => {
652                out.push_str("the associated type ");
653                name(Some(n), out);
654                out.push_str(" must be specified");
655            }
656            Self::RecursiveInstantiation => {
657                out.push_str("instantiating this generic item recurses without bound");
658            }
659            Self::TryCarrier { ty: t } => {
660                ty(t, out);
661                out.push_str(" cannot propagate a failure here");
662            }
663            Self::Unsupported { feature } => {
664                let _ = write!(
665                    out,
666                    "{} are not supported by this profile in this version",
667                    feature.name()
668                );
669            }
670            Self::CyclicAlias => out.push_str("type alias expands to itself"),
671            Self::InheritanceCycle => out.push_str("class inherits from itself"),
672            Self::NotConstant => out.push_str("expected a compile-time integer constant"),
673            Self::ImpossibleTypeTest { from, to } => {
674                out.push_str("a value of type ");
675                ty(from, out);
676                out.push_str(" can never be a ");
677                ty(to, out);
678            }
679            Self::ByRefNeedsPlace => {
680                out.push_str("a by-reference parameter needs a place argument");
681            }
682            Self::NotAssignable => out.push_str("cannot assign to this"),
683        }
684    }
685}
686
687/// One finding about the checked program.
688///
689/// [`Typed::message`](crate::Typed::message) renders it as text.
690///
691/// # Examples
692///
693/// ```
694/// use hir_lang::{BinderKind, Builder, Name, NodeRef};
695/// use intern_lang::Interner;
696/// use typeck_lang::{check, DiagnosticKind, Profile};
697///
698/// let mut names = Interner::new();
699/// let mut b = Builder::new();
700/// // fn main() { let x; }   -- nothing determines x's type
701/// let x = b.new_binder(Name::new(names.intern("x")), BinderKind::Local);
702/// let pat = b.bind(x);
703/// let stmt = b.let_stmt(pat, None);
704/// let body = b.block(&[stmt], None);
705/// let main = b.func(Name::new(names.intern("main")), &[], body);
706/// let root = b.module(None, &[main]);
707/// let hir = b.finish(root)?;
708///
709/// let typed = check(&hir, &Profile::static_explicit()).unwrap();
710/// let d = typed.diagnostics()[0];
711/// assert_eq!(d.kind, DiagnosticKind::CannotInfer);
712/// assert_eq!(d.kind.code(), "T0023");
713/// assert_eq!(d.node, NodeRef::Pat(pat));
714/// assert_eq!(d.origin, hir.origin(NodeRef::Pat(pat)));
715/// # Ok::<(), hir_lang::HirError>(())
716/// ```
717#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
718#[non_exhaustive]
719pub struct Diagnostic {
720    /// What is wrong.
721    pub kind: DiagnosticKind,
722    /// The node it is about.
723    pub node: NodeRef,
724    /// The node's origin: source span and expansion.
725    pub origin: Origin,
726    /// Error or warning.
727    pub severity: Severity,
728}
729
730#[cfg(test)]
731mod tests {
732    use alloc::{string::String, vec::Vec};
733
734    use hir_lang::{Member, OpKind, Prim};
735    use intern_lang::Interner;
736
737    use super::*;
738
739    fn all_kinds() -> Vec<DiagnosticKind> {
740        let mut names = Interner::new();
741        let s = names.intern("n");
742        let t = TypeId::prim(Prim::I32);
743        alloc::vec![
744            DiagnosticKind::Mismatch {
745                expected: t,
746                found: t
747            },
748            DiagnosticKind::MissingAnnotation,
749            DiagnosticKind::Unresolved,
750            DiagnosticKind::UnknownExtern { name: Some(s) },
751            DiagnosticKind::NotAValue,
752            DiagnosticKind::NotAType,
753            DiagnosticKind::Arity {
754                min: 1,
755                max: Some(2),
756                found: 3
757            },
758            DiagnosticKind::UnknownNamedArg { name: s },
759            DiagnosticKind::DuplicateArg { name: Some(s) },
760            DiagnosticKind::MissingArg {
761                name: Some(s),
762                count: 2
763            },
764            DiagnosticKind::NotCallable { ty: t },
765            DiagnosticKind::NoField {
766                ty: t,
767                member: Member::Index(0)
768            },
769            DiagnosticKind::NoMethod { ty: t, name: s },
770            DiagnosticKind::AmbiguousMethod { ty: t, name: s },
771            DiagnosticKind::UnknownField { ty: t, name: s },
772            DiagnosticKind::MissingFields { first: s, count: 3 },
773            DiagnosticKind::UnionLiteral { count: 2 },
774            DiagnosticKind::NotIndexable { ty: t },
775            DiagnosticKind::CannotDeref { ty: t },
776            DiagnosticKind::NotAwaitable { ty: t },
777            DiagnosticKind::OpType {
778                op: OpKind::Add,
779                ty: t
780            },
781            DiagnosticKind::PromoteOnStatic { op: None },
782            DiagnosticKind::BadConversion {
783                op: OpKind::Sext(Prim::I8),
784                from: t
785            },
786            DiagnosticKind::InvalidCast { from: t, to: t },
787            DiagnosticKind::LiteralOutOfRange { ty: t },
788            DiagnosticKind::CannotInfer,
789            DiagnosticKind::DynamicOperation,
790            DiagnosticKind::DynamicForm,
791            DiagnosticKind::NullableAccess { ty: t },
792            DiagnosticKind::NonExhaustive { missing: None },
793            DiagnosticKind::Unsupported {
794                feature: Feature::GenericAssocTypes
795            },
796            DiagnosticKind::UnreachableArm,
797            DiagnosticKind::RedundantAlternative,
798            DiagnosticKind::NotAnInterface,
799            DiagnosticKind::GenericArity {
800                expected: 1,
801                found: 2
802            },
803            DiagnosticKind::NoAssocType { name: s },
804            DiagnosticKind::AmbiguousAssocType { name: s },
805            DiagnosticKind::Unsatisfied {
806                ty: t,
807                interface: t
808            },
809            DiagnosticKind::AmbiguousImpl {
810                ty: t,
811                interface: t
812            },
813            DiagnosticKind::MissingMember { name: s, count: 2 },
814            DiagnosticKind::NotAMember {
815                interface: t,
816                name: s
817            },
818            DiagnosticKind::InterfaceAsType,
819            DiagnosticKind::ImplTraitPosition,
820            DiagnosticKind::MissingAssocBinding { name: s },
821            DiagnosticKind::RecursiveInstantiation,
822            DiagnosticKind::TryCarrier { ty: t },
823            DiagnosticKind::CyclicAlias,
824            DiagnosticKind::InheritanceCycle,
825            DiagnosticKind::NotConstant,
826            DiagnosticKind::ImpossibleTypeTest { from: t, to: t },
827            DiagnosticKind::ByRefNeedsPlace,
828            DiagnosticKind::NotAssignable,
829        ]
830    }
831
832    #[test]
833    fn test_codes_are_unique_and_messages_render() {
834        let names = Interner::new();
835        let types = Types::new();
836        let mut kinds = all_kinds();
837        kinds.extend(
838            hir_lang::ItemId::from_index(0).map(|other| DiagnosticKind::OverlappingImpls { other }),
839        );
840        let mut codes: Vec<&str> = kinds.iter().map(DiagnosticKind::code).collect();
841        codes.sort_unstable();
842        let n = codes.len();
843        codes.dedup();
844        assert_eq!(codes.len(), n, "duplicate diagnostic codes");
845        for k in &kinds {
846            let mut out = String::new();
847            k.render(&types, &names, &mut out);
848            assert!(!out.is_empty(), "{k:?}");
849        }
850    }
851
852    #[test]
853    fn test_arity_wording() {
854        let names = Interner::new();
855        let types = Types::new();
856        let render = |k: DiagnosticKind| {
857            let mut out = String::new();
858            k.render(&types, &names, &mut out);
859            out
860        };
861        assert_eq!(
862            render(DiagnosticKind::Arity {
863                min: 2,
864                max: Some(2),
865                found: 1
866            }),
867            "expected 2 arguments, found 1"
868        );
869        assert_eq!(
870            render(DiagnosticKind::Arity {
871                min: 1,
872                max: Some(3),
873                found: 5
874            }),
875            "expected 1 to 3 arguments, found 5"
876        );
877        assert_eq!(
878            render(DiagnosticKind::Arity {
879                min: 1,
880                max: None,
881                found: 0
882            }),
883            "expected at least 1 arguments, found 0"
884        );
885        assert_eq!(
886            render(DiagnosticKind::UnknownExtern { name: None }),
887            "the type of `?` is not declared to the checker"
888        );
889    }
890
891    #[test]
892    fn test_feature_names() {
893        for f in [Feature::GenericAssocTypes, Feature::LongAssocPaths] {
894            assert!(!f.name().is_empty());
895        }
896    }
897}