aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/merge_match_arms.rs
blob: 3b6a99895d485953e8b73aba640cee7af9b39288 (plain)
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
use crate::{Assist, AssistCtx, AssistId, TextRange, TextUnit};
use hir::db::HirDatabase;
use ra_syntax::ast::{AstNode, MatchArm};

pub(crate) fn merge_match_arms(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {
    let current_arm = ctx.node_at_offset::<MatchArm>()?;

    // We check if the following match arm matches this one. We could, but don't,
    // compare to the previous match arm as well.
    let next = current_arm.syntax().next_sibling();
    let next_arm = MatchArm::cast(next?)?;

    // Don't try to handle arms with guards for now - can add support for this later
    if current_arm.guard().is_some() || next_arm.guard().is_some() {
        return None;
    }

    let current_expr = current_arm.expr()?;
    let next_expr = next_arm.expr()?;

    // Check for match arm equality by comparing lengths and then string contents
    if current_expr.syntax().text_range().len() != next_expr.syntax().text_range().len() {
        return None;
    }
    if current_expr.syntax().text() != next_expr.syntax().text() {
        return None;
    }

    let cursor_to_end = current_arm.syntax().text_range().end() - ctx.frange.range.start();

    ctx.add_action(AssistId("merge_match_arms"), "merge match arms", |edit| {
        fn contains_placeholder(a: &MatchArm) -> bool {
            a.pats().any(|x| match x {
                ra_syntax::ast::Pat::PlaceholderPat(..) => true,
                _ => false,
            })
        }

        let pats = if contains_placeholder(&current_arm) || contains_placeholder(&next_arm) {
            "_".into()
        } else {
            let ps: Vec<String> = current_arm
                .pats()
                .map(|x| x.syntax().to_string())
                .chain(next_arm.pats().map(|x| x.syntax().to_string()))
                .collect();
            ps.join(" | ")
        };

        let arm = format!("{} => {}", pats, current_expr.syntax().text());
        let offset = TextUnit::from_usize(arm.len()) - cursor_to_end;

        let start = current_arm.syntax().text_range().start();
        let end = next_arm.syntax().text_range().end();

        edit.target(current_arm.syntax().text_range());
        edit.replace(TextRange::from_to(start, end), arm);
        edit.set_cursor(start + offset);
    });

    ctx.build()
}

#[cfg(test)]
mod tests {
    use super::merge_match_arms;
    use crate::helpers::{check_assist, check_assist_not_applicable};

    #[test]
    fn merge_match_arms_single_patterns() {
        check_assist(
            merge_match_arms,
            r#"
            #[derive(Debug)]
            enum X { A, B, C }

            fn main() {
                let x = X::A;
                let y = match x {
                    X::A => { 1i32<|> }
                    X::B => { 1i32 }
                    X::C => { 2i32 }
                }
            }
            "#,
            r#"
            #[derive(Debug)]
            enum X { A, B, C }

            fn main() {
                let x = X::A;
                let y = match x {
                    X::A | X::B => { 1i32<|> }
                    X::C => { 2i32 }
                }
            }
            "#,
        );
    }

    #[test]
    fn merge_match_arms_multiple_patterns() {
        check_assist(
            merge_match_arms,
            r#"
            #[derive(Debug)]
            enum X { A, B, C, D, E }

            fn main() {
                let x = X::A;
                let y = match x {
                    X::A | X::B => {<|> 1i32 },
                    X::C | X::D => { 1i32 },
                    X::E => { 2i32 },
                }
            }
            "#,
            r#"
            #[derive(Debug)]
            enum X { A, B, C, D, E }

            fn main() {
                let x = X::A;
                let y = match x {
                    X::A | X::B | X::C | X::D => {<|> 1i32 },
                    X::E => { 2i32 },
                }
            }
            "#,
        );
    }

    #[test]
    fn merge_match_arms_placeholder_pattern() {
        check_assist(
            merge_match_arms,
            r#"
            #[derive(Debug)]
            enum X { A, B, C, D, E }

            fn main() {
                let x = X::A;
                let y = match x {
                    X::A => { 1i32 },
                    X::B => { 2i<|>32 },
                    _ => { 2i32 }
                }
            }
            "#,
            r#"
            #[derive(Debug)]
            enum X { A, B, C, D, E }

            fn main() {
                let x = X::A;
                let y = match x {
                    X::A => { 1i32 },
                    _ => { 2i<|>32 }
                }
            }
            "#,
        );
    }

    #[test]
    fn merge_match_arms_rejects_guards() {
        check_assist_not_applicable(
            merge_match_arms,
            r#"
            #[derive(Debug)]
            enum X {
                A(i32),
                B,
                C
            }

            fn main() {
                let x = X::A;
                let y = match x {
                    X::A(a) if a > 5 => { <|>1i32 },
                    X::B => { 1i32 },
                    X::C => { 2i32 }
                }
            }
            "#,
        );
    }
}