Skip to main content

ide_diagnostics/handlers/
method_call_illegal_sized_bound.rs

1use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext};
2
3// Diagnostic: method-call-illegal-sized-bound
4//
5// This diagnostic is triggered when a method is called on a trait-object
6// receiver but the method's predicates require `Self: Sized`, which the
7// trait object cannot satisfy.
8pub(crate) fn method_call_illegal_sized_bound(
9    ctx: &DiagnosticsContext<'_, '_>,
10    d: &hir::MethodCallIllegalSizedBound,
11) -> Diagnostic {
12    Diagnostic::new_with_syntax_node_ptr(
13        ctx,
14        DiagnosticCode::RustcHardError("E0277"),
15        "the method cannot be invoked on a trait object because its `Self: Sized` bound is not satisfied",
16        d.call_expr.map(|it| it.into()),
17    )
18    .stable()
19}
20
21#[cfg(test)]
22mod tests {
23    use crate::tests::check_diagnostics;
24
25    #[test]
26    fn sized_bound_method_on_trait_object_errors() {
27        check_diagnostics(
28            r#"
29//- minicore: sized
30trait Foo {
31    fn cant_call(&self) where Self: Sized;
32}
33
34fn f(x: &dyn Foo) {
35    x.cant_call();
36  //^^^^^^^^^^^^^ error: the method cannot be invoked on a trait object because its `Self: Sized` bound is not satisfied
37}
38"#,
39        );
40    }
41
42    #[test]
43    fn method_without_sized_bound_on_trait_object_does_not_error() {
44        check_diagnostics(
45            r#"
46//- minicore: sized
47trait Foo {
48    fn dyn_safe(&self);
49}
50
51fn f(x: &dyn Foo) {
52    x.dyn_safe();
53}
54"#,
55        );
56    }
57
58    #[test]
59    fn sized_bound_method_on_concrete_type_does_not_error() {
60        check_diagnostics(
61            r#"
62//- minicore: sized
63trait Foo {
64    fn cant_dispatch(&self) where Self: Sized;
65}
66
67struct S;
68impl Foo for S {
69    fn cant_dispatch(&self) {}
70}
71
72fn f(s: &S) {
73    s.cant_dispatch();
74}
75"#,
76        );
77    }
78}