Skip to main content

ide_diagnostics/handlers/
duplicate_field.rs

1use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext};
2
3// Diagnostic: duplicate-field
4//
5// This diagnostic is triggered when a record expression or pattern specifies
6// the same field more than once.
7pub(crate) fn duplicate_field(
8    ctx: &DiagnosticsContext<'_, '_>,
9    d: &hir::DuplicateField,
10) -> Diagnostic {
11    Diagnostic::new_with_syntax_node_ptr(
12        ctx,
13        DiagnosticCode::RustcHardError("E0062"),
14        "field specified more than once",
15        d.field.map(Into::into),
16    )
17    .stable()
18}
19
20#[cfg(test)]
21mod tests {
22    use crate::tests::check_diagnostics;
23
24    #[test]
25    fn duplicate_field_in_struct_literal() {
26        check_diagnostics(
27            r#"
28struct S { foo: i32, bar: i32 }
29fn main() {
30    let _ = S {
31        foo: 1,
32        bar: 2,
33        foo: 3,
34      //^^^^^^ error: field specified more than once
35    };
36}
37"#,
38        );
39    }
40
41    #[test]
42    fn duplicate_field_in_enum_variant_literal() {
43        check_diagnostics(
44            r#"
45enum E { V { foo: i32 } }
46fn main() {
47    let _ = E::V {
48        foo: 1,
49        foo: 2,
50      //^^^^^^ error: field specified more than once
51    };
52}
53"#,
54        );
55    }
56
57    #[test]
58    fn no_duplicate_when_each_field_specified_once() {
59        check_diagnostics(
60            r#"
61struct S { foo: i32, bar: i32 }
62fn main() {
63    let _ = S { foo: 1, bar: 2 };
64}
65"#,
66        );
67    }
68
69    #[test]
70    fn no_duplicate_for_unknown_field_falls_through_to_no_such_field() {
71        check_diagnostics(
72            r#"
73struct S { foo: i32 }
74fn main() {
75    let _ = S {
76        foo: 1,
77        bar: 2,
78      //^^^^^^ 💡 error: no such field
79    };
80}
81"#,
82        );
83    }
84
85    #[test]
86    fn duplicate_field_in_struct_pattern() {
87        check_diagnostics(
88            r#"
89struct S { foo: i32, bar: i32 }
90fn f(s: S) {
91    let S {
92        foo,
93        bar,
94        foo,
95      //^^^ error: field specified more than once
96        ..
97    } = s;
98    let _ = (foo, bar);
99}
100"#,
101        );
102    }
103
104    #[test]
105    fn duplicate_field_in_enum_variant_pattern() {
106        check_diagnostics(
107            r#"
108enum E { V { foo: i32, bar: i32 } }
109fn f(e: E) {
110    match e {
111        E::V {
112            foo,
113            bar,
114            foo,
115          //^^^ error: field specified more than once
116            ..
117        } => { let _ = (foo, bar); }
118    }
119}
120"#,
121        );
122    }
123}