Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext};

// Diagnostic: mismatched-array-pat-len
//
// This diagnostic is triggered when an array pattern's element count does not
// match the array's declared length.
pub(crate) fn mismatched_array_pat_len(
    ctx: &DiagnosticsContext<'_, '_>,
    d: &hir::MismatchedArrayPatLen,
) -> Diagnostic {
    let (code, message) = if d.has_rest {
        (
            "E0528",
            format!(
                "pattern requires at least {} element{} but array has {}",
                d.found,
                if d.found == 1 { "" } else { "s" },
                d.expected,
            ),
        )
    } else {
        (
            "E0527",
            format!(
                "pattern requires {} element{} but array has {}",
                d.found,
                if d.found == 1 { "" } else { "s" },
                d.expected,
            ),
        )
    };
    Diagnostic::new_with_syntax_node_ptr(
        ctx,
        DiagnosticCode::RustcHardError(code),
        message,
        d.pat.map(Into::into),
    )
    .stable()
}

#[cfg(test)]
mod tests {
    use crate::tests::check_diagnostics;

    #[test]
    fn array_pattern_too_few_elements() {
        check_diagnostics(
            r#"
fn f(arr: [i32; 3]) {
    let [_a, _b] = arr;
      //^^^^^^^^ error: pattern requires 2 elements but array has 3
}
"#,
        );
    }

    #[test]
    fn array_pattern_too_many_elements() {
        check_diagnostics(
            r#"
fn f(arr: [i32; 2]) {
    let [_a, _b, _c] = arr;
      //^^^^^^^^^^^^ error: pattern requires 3 elements but array has 2
}
"#,
        );
    }

    #[test]
    fn array_pattern_with_rest_too_short() {
        check_diagnostics(
            r#"
fn f(arr: [i32; 2]) {
    let [_a, _b, _c, ..] = arr;
      //^^^^^^^^^^^^^^^^ error: pattern requires at least 3 elements but array has 2
}
"#,
        );
    }

    #[test]
    fn array_pattern_with_rest_ok() {
        check_diagnostics(
            r#"
fn f(arr: [i32; 5]) {
    let [_a, _b, ..] = arr;
}
"#,
        );
    }

    #[test]
    fn array_pattern_exact_length_ok() {
        check_diagnostics(
            r#"
fn f(arr: [i32; 3]) {
    let [_a, _b, _c] = arr;
}
"#,
        );
    }

    #[test]
    fn array_pattern_singular_element_uses_singular() {
        check_diagnostics(
            r#"
fn f(arr: [i32; 3]) {
    let [_a] = arr;
      //^^^^ error: pattern requires 1 element but array has 3
}
"#,
        );
    }
}