1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27#[non_exhaustive]
28pub enum Feature {
29 GenericAssocTypes,
32 LongAssocPaths,
35}
36
37impl Feature {
38 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
64pub enum Severity {
65 Warning,
67 Error,
69}
70
71#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
83#[non_exhaustive]
84pub enum DiagnosticKind {
85 Mismatch {
87 expected: TypeId,
89 found: TypeId,
91 },
92 MissingAnnotation,
95 Unresolved,
97 UnknownExtern {
100 name: Option<Symbol>,
102 },
103 NotAValue,
106 NotAType,
108 Arity {
110 min: u32,
112 max: Option<u32>,
114 found: u32,
116 },
117 UnknownNamedArg {
119 name: Symbol,
121 },
122 DuplicateArg {
124 name: Option<Symbol>,
126 },
127 MissingArg {
129 name: Option<Symbol>,
131 count: u32,
133 },
134 NotCallable {
136 ty: TypeId,
138 },
139 NoField {
141 ty: TypeId,
143 member: Member,
145 },
146 NoMethod {
148 ty: TypeId,
150 name: Symbol,
152 },
153 AmbiguousMethod {
155 ty: TypeId,
157 name: Symbol,
159 },
160 UnknownField {
162 ty: TypeId,
164 name: Symbol,
166 },
167 MissingFields {
169 first: Symbol,
171 count: u32,
173 },
174 UnionLiteral {
176 count: u32,
178 },
179 NotIndexable {
181 ty: TypeId,
183 },
184 CannotDeref {
186 ty: TypeId,
188 },
189 NotAwaitable {
191 ty: TypeId,
193 },
194 OpType {
196 op: OpKind,
198 ty: TypeId,
200 },
201 PromoteOnStatic {
204 op: Option<OpKind>,
206 },
207 BadConversion {
210 op: OpKind,
212 from: TypeId,
214 },
215 InvalidCast {
217 from: TypeId,
219 to: TypeId,
221 },
222 LiteralOutOfRange {
224 ty: TypeId,
226 },
227 CannotInfer,
229 DynamicOperation,
232 DynamicForm,
235 NullableAccess {
237 ty: TypeId,
239 },
240 NonExhaustive {
243 missing: Option<VariantId>,
246 },
247 UnreachableArm,
249 RedundantAlternative,
252 NotAnInterface,
255 GenericArity {
257 expected: u32,
259 found: u32,
261 },
262 NoAssocType {
265 name: Symbol,
267 },
268 AmbiguousAssocType {
271 name: Symbol,
273 },
274 Unsatisfied {
276 ty: TypeId,
278 interface: TypeId,
280 },
281 AmbiguousImpl {
283 ty: TypeId,
285 interface: TypeId,
287 },
288 OverlappingImpls {
291 other: ItemId,
293 },
294 MissingMember {
296 name: Symbol,
298 count: u32,
300 },
301 NotAMember {
303 interface: TypeId,
305 name: Symbol,
307 },
308 InterfaceAsType,
311 ImplTraitPosition,
313 MissingAssocBinding {
316 name: Symbol,
318 },
319 RecursiveInstantiation,
323 TryCarrier {
326 ty: TypeId,
328 },
329 Unsupported {
331 feature: Feature,
333 },
334 CyclicAlias,
336 InheritanceCycle,
338 NotConstant,
341 ImpossibleTypeTest {
343 from: TypeId,
345 to: TypeId,
347 },
348 ByRefNeedsPlace,
350 NotAssignable,
353}
354
355impl DiagnosticKind {
356 #[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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
718#[non_exhaustive]
719pub struct Diagnostic {
720 pub kind: DiagnosticKind,
722 pub node: NodeRef,
724 pub origin: Origin,
726 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}