Skip to main content

ide_diagnostics/handlers/
cannot_be_dereferenced.rs

1use hir::HirDisplay;
2
3use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext};
4
5// Diagnostic: cannot-be-dereferenced
6//
7// This diagnostic is triggered if the operand of a dereference expression
8// cannot be dereferenced.
9pub(crate) fn cannot_be_dereferenced(
10    ctx: &DiagnosticsContext<'_, '_>,
11    d: &hir::CannotBeDereferenced<'_>,
12) -> Diagnostic {
13    Diagnostic::new_with_syntax_node_ptr(
14        ctx,
15        DiagnosticCode::RustcHardError("E0614"),
16        format!(
17            "type `{}` cannot be dereferenced",
18            d.found.display(ctx.sema.db, ctx.display_target)
19        ),
20        d.expr.map(Into::into),
21    )
22    .stable()
23}
24
25#[cfg(test)]
26mod tests {
27    use crate::tests::check_diagnostics;
28
29    #[test]
30    fn cannot_be_dereferenced() {
31        check_diagnostics(
32            r#"
33fn f() {
34    let x = 1i32;
35    let _ = *x;
36          //^^ error: type `i32` cannot be dereferenced
37}
38"#,
39        );
40    }
41
42    #[test]
43    fn allows_reference_deref() {
44        check_diagnostics(
45            r#"
46fn f(x: &i32) {
47    let _ = *x;
48}
49"#,
50        );
51    }
52
53    #[test]
54    fn allows_overloaded_deref() {
55        check_diagnostics(
56            r#"
57//- minicore: deref
58struct Wrapper(i32);
59
60impl core::ops::Deref for Wrapper {
61    type Target = i32;
62
63    fn deref(&self) -> &i32 {
64        &self.0
65    }
66}
67
68fn f(x: Wrapper) {
69    let _ = *x;
70}
71"#,
72        );
73    }
74}