ide_diagnostics/handlers/
mismatched_array_pat_len.rs1use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext};
2
3pub(crate) fn mismatched_array_pat_len(
8 ctx: &DiagnosticsContext<'_, '_>,
9 d: &hir::MismatchedArrayPatLen,
10) -> Diagnostic {
11 let (code, message) = if d.has_rest {
12 (
13 "E0528",
14 format!(
15 "pattern requires at least {} element{} but array has {}",
16 d.found,
17 if d.found == 1 { "" } else { "s" },
18 d.expected,
19 ),
20 )
21 } else {
22 (
23 "E0527",
24 format!(
25 "pattern requires {} element{} but array has {}",
26 d.found,
27 if d.found == 1 { "" } else { "s" },
28 d.expected,
29 ),
30 )
31 };
32 Diagnostic::new_with_syntax_node_ptr(
33 ctx,
34 DiagnosticCode::RustcHardError(code),
35 message,
36 d.pat.map(Into::into),
37 )
38 .stable()
39}
40
41#[cfg(test)]
42mod tests {
43 use crate::tests::check_diagnostics;
44
45 #[test]
46 fn array_pattern_too_few_elements() {
47 check_diagnostics(
48 r#"
49fn f(arr: [i32; 3]) {
50 let [_a, _b] = arr;
51 //^^^^^^^^ error: pattern requires 2 elements but array has 3
52}
53"#,
54 );
55 }
56
57 #[test]
58 fn array_pattern_too_many_elements() {
59 check_diagnostics(
60 r#"
61fn f(arr: [i32; 2]) {
62 let [_a, _b, _c] = arr;
63 //^^^^^^^^^^^^ error: pattern requires 3 elements but array has 2
64}
65"#,
66 );
67 }
68
69 #[test]
70 fn array_pattern_with_rest_too_short() {
71 check_diagnostics(
72 r#"
73fn f(arr: [i32; 2]) {
74 let [_a, _b, _c, ..] = arr;
75 //^^^^^^^^^^^^^^^^ error: pattern requires at least 3 elements but array has 2
76}
77"#,
78 );
79 }
80
81 #[test]
82 fn array_pattern_with_rest_ok() {
83 check_diagnostics(
84 r#"
85fn f(arr: [i32; 5]) {
86 let [_a, _b, ..] = arr;
87}
88"#,
89 );
90 }
91
92 #[test]
93 fn array_pattern_exact_length_ok() {
94 check_diagnostics(
95 r#"
96fn f(arr: [i32; 3]) {
97 let [_a, _b, _c] = arr;
98}
99"#,
100 );
101 }
102
103 #[test]
104 fn array_pattern_singular_element_uses_singular() {
105 check_diagnostics(
106 r#"
107fn f(arr: [i32; 3]) {
108 let [_a] = arr;
109 //^^^^ error: pattern requires 1 element but array has 3
110}
111"#,
112 );
113 }
114}