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};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Feature {
GenericAssocTypes,
LongAssocPaths,
}
impl Feature {
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::GenericAssocTypes => "generic associated types",
Self::LongAssocPaths => "multi-segment associated paths",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Severity {
Warning,
Error,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DiagnosticKind {
Mismatch {
expected: TypeId,
found: TypeId,
},
MissingAnnotation,
Unresolved,
UnknownExtern {
name: Option<Symbol>,
},
NotAValue,
NotAType,
Arity {
min: u32,
max: Option<u32>,
found: u32,
},
UnknownNamedArg {
name: Symbol,
},
DuplicateArg {
name: Option<Symbol>,
},
MissingArg {
name: Option<Symbol>,
count: u32,
},
NotCallable {
ty: TypeId,
},
NoField {
ty: TypeId,
member: Member,
},
NoMethod {
ty: TypeId,
name: Symbol,
},
AmbiguousMethod {
ty: TypeId,
name: Symbol,
},
UnknownField {
ty: TypeId,
name: Symbol,
},
MissingFields {
first: Symbol,
count: u32,
},
UnionLiteral {
count: u32,
},
NotIndexable {
ty: TypeId,
},
CannotDeref {
ty: TypeId,
},
NotAwaitable {
ty: TypeId,
},
OpType {
op: OpKind,
ty: TypeId,
},
PromoteOnStatic {
op: Option<OpKind>,
},
BadConversion {
op: OpKind,
from: TypeId,
},
InvalidCast {
from: TypeId,
to: TypeId,
},
LiteralOutOfRange {
ty: TypeId,
},
CannotInfer,
DynamicOperation,
DynamicForm,
NullableAccess {
ty: TypeId,
},
NonExhaustive {
missing: Option<VariantId>,
},
UnreachableArm,
RedundantAlternative,
NotAnInterface,
GenericArity {
expected: u32,
found: u32,
},
NoAssocType {
name: Symbol,
},
AmbiguousAssocType {
name: Symbol,
},
Unsatisfied {
ty: TypeId,
interface: TypeId,
},
AmbiguousImpl {
ty: TypeId,
interface: TypeId,
},
OverlappingImpls {
other: ItemId,
},
MissingMember {
name: Symbol,
count: u32,
},
NotAMember {
interface: TypeId,
name: Symbol,
},
InterfaceAsType,
ImplTraitPosition,
MissingAssocBinding {
name: Symbol,
},
RecursiveInstantiation,
TryCarrier {
ty: TypeId,
},
Unsupported {
feature: Feature,
},
CyclicAlias,
InheritanceCycle,
NotConstant,
ImpossibleTypeTest {
from: TypeId,
to: TypeId,
},
ByRefNeedsPlace,
NotAssignable,
}
impl DiagnosticKind {
#[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",
}
}
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"),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Diagnostic {
pub kind: DiagnosticKind,
pub node: NodeRef,
pub origin: Origin,
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());
}
}
}