Skip to main content

ide_diagnostics/handlers/
invalid_lhs_of_assignment.rs

1use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext};
2
3// Diagnostic: invalid-lhs-of-assignment
4//
5// This diagnostic is triggered if the left-hand side of an assignment can't be assigned to.
6pub(crate) fn invalid_lhs_of_assignment(
7    ctx: &DiagnosticsContext<'_, '_>,
8    d: &hir::InvalidLhsOfAssignment,
9) -> Diagnostic {
10    Diagnostic::new_with_syntax_node_ptr(
11        ctx,
12        DiagnosticCode::RustcHardError("E0067"),
13        "invalid left-hand side of assignment",
14        d.lhs.map(Into::into),
15    )
16    .stable()
17}
18
19#[cfg(test)]
20mod tests {
21    use crate::tests::check_diagnostics;
22
23    #[test]
24    fn unit_struct_literal() {
25        check_diagnostics(
26            r#"
27//- minicore: add
28struct Struct;
29impl core::ops::AddAssign for Struct {
30    fn add_assign(&mut self, _other: Self) {}
31}
32fn test() {
33    Struct += Struct;
34 // ^^^^^^ error: invalid left-hand side of assignment
35}
36        "#,
37        );
38    }
39
40    #[test]
41    fn struct_literal() {
42        check_diagnostics(
43            r#"
44//- minicore: add
45struct Struct { foo: i32, bar: i32 }
46impl core::ops::AddAssign for Struct {
47    fn add_assign(&mut self, _other: Self) {}
48}
49fn test() {
50    Struct { foo: 0, bar: 0 } += Struct { foo: 1, bar: 2 };
51 // ^^^^^^^^^^^^^^^^^^^^^^^^^ error: invalid left-hand side of assignment
52}
53        "#,
54        );
55    }
56
57    #[test]
58    fn destructuring_assignment() {
59        // no diagnostic, as `=` is not a _compound_ assignment
60        check_diagnostics(
61            r#"
62//- minicore: add
63struct Struct { foo: i32, bar: i32 }
64impl core::ops::AddAssign for Struct {
65    fn add_assign(&mut self, _other: Self) {}
66}
67fn test(mut foo: i32, mut bar: i32) {
68    Struct { foo, bar } = Struct { foo: 1, bar: 2 };
69}
70        "#,
71        );
72    }
73
74    #[test]
75    fn destructuring_compound_assignment() {
76        check_diagnostics(
77            r#"
78//- minicore: add
79struct Struct { foo: i32, bar: i32 }
80impl core::ops::AddAssign for Struct {
81    fn add_assign(&mut self, _other: Self) {}
82}
83fn test(foo: i32, bar: i32) {
84    Struct { foo, bar } += Struct { foo: 1, bar: 2 };
85 // ^^^^^^^^^^^^^^^^^^^ error: invalid left-hand side of assignment
86}
87        "#,
88        );
89    }
90}