aboutsummaryrefslogtreecommitdiff
path: root/crates/ide_diagnostics/src/handlers/replace_filter_map_next_with_find_map.rs
blob: cd87a10bb282a992fa77a9a79a9dfebe007407b8 (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
use hir::{db::AstDatabase, InFile};
use ide_db::source_change::SourceChange;
use syntax::{
    ast::{self, ArgListOwner},
    AstNode, TextRange,
};
use text_edit::TextEdit;

use crate::{fix, Assist, Diagnostic, DiagnosticsContext, Severity};

// Diagnostic: replace-filter-map-next-with-find-map
//
// This diagnostic is triggered when `.filter_map(..).next()` is used, rather than the more concise `.find_map(..)`.
pub(crate) fn replace_filter_map_next_with_find_map(
    ctx: &DiagnosticsContext<'_>,
    d: &hir::ReplaceFilterMapNextWithFindMap,
) -> Diagnostic {
    Diagnostic::new(
        "replace-filter-map-next-with-find-map",
        "replace filter_map(..).next() with find_map(..)",
        ctx.sema.diagnostics_display_range(InFile::new(d.file, d.next_expr.clone().into())).range,
    )
    .severity(Severity::WeakWarning)
    .with_fixes(fixes(ctx, d))
}

fn fixes(
    ctx: &DiagnosticsContext<'_>,
    d: &hir::ReplaceFilterMapNextWithFindMap,
) -> Option<Vec<Assist>> {
    let root = ctx.sema.db.parse_or_expand(d.file)?;
    let next_expr = d.next_expr.to_node(&root);
    let next_call = ast::MethodCallExpr::cast(next_expr.syntax().clone())?;

    let filter_map_call = ast::MethodCallExpr::cast(next_call.receiver()?.syntax().clone())?;
    let filter_map_name_range = filter_map_call.name_ref()?.ident_token()?.text_range();
    let filter_map_args = filter_map_call.arg_list()?;

    let range_to_replace =
        TextRange::new(filter_map_name_range.start(), next_expr.syntax().text_range().end());
    let replacement = format!("find_map{}", filter_map_args.syntax().text());
    let trigger_range = next_expr.syntax().text_range();

    let edit = TextEdit::replace(range_to_replace, replacement);

    let source_change = SourceChange::from_text_edit(d.file.original_file(ctx.sema.db), edit);

    Some(vec![fix(
        "replace_with_find_map",
        "Replace filter_map(..).next() with find_map()",
        source_change,
        trigger_range,
    )])
}

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

    // Register the required standard library types to make the tests work
    #[track_caller]
    fn check_diagnostics(ra_fixture: &str) {
        let prefix = r#"
//- /main.rs crate:main deps:core
use core::iter::Iterator;
use core::option::Option::{self, Some, None};
"#;
        let suffix = r#"
//- /core/lib.rs crate:core
pub mod option {
    pub enum Option<T> { Some(T), None }
}
pub mod iter {
    pub trait Iterator {
        type Item;
        fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
        fn next(&mut self) -> Option<Self::Item>;
    }
    pub struct FilterMap {}
    impl Iterator for FilterMap {
        type Item = i32;
        fn next(&mut self) -> i32 { 7 }
    }
}
"#;
        crate::tests::check_diagnostics(&format!("{}{}{}", prefix, ra_fixture, suffix))
    }

    #[test]
    fn replace_filter_map_next_with_find_map2() {
        check_diagnostics(
            r#"
    fn foo() {
        let m = [1, 2, 3].iter().filter_map(|x| Some(92)).next();
    }         //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 💡 weak: replace filter_map(..).next() with find_map(..)
"#,
        );
    }

    #[test]
    fn replace_filter_map_next_with_find_map_no_diagnostic_without_next() {
        check_diagnostics(
            r#"
fn foo() {
    let m = [1, 2, 3]
        .iter()
        .filter_map(|x| Some(92))
        .len();
}
"#,
        );
    }

    #[test]
    fn replace_filter_map_next_with_find_map_no_diagnostic_with_intervening_methods() {
        check_diagnostics(
            r#"
fn foo() {
    let m = [1, 2, 3]
        .iter()
        .filter_map(|x| Some(92))
        .map(|x| x + 2)
        .len();
}
"#,
        );
    }

    #[test]
    fn replace_filter_map_next_with_find_map_no_diagnostic_if_not_in_chain() {
        check_diagnostics(
            r#"
fn foo() {
    let m = [1, 2, 3]
        .iter()
        .filter_map(|x| Some(92));
    let n = m.next();
}
"#,
        );
    }

    #[test]
    fn replace_with_wind_map() {
        check_fix(
            r#"
//- /main.rs crate:main deps:core
use core::iter::Iterator;
use core::option::Option::{self, Some, None};
fn foo() {
    let m = [1, 2, 3].iter().$0filter_map(|x| Some(92)).next();
}
//- /core/lib.rs crate:core
pub mod option {
    pub enum Option<T> { Some(T), None }
}
pub mod iter {
    pub trait Iterator {
        type Item;
        fn filter_map<B, F>(self, f: F) -> FilterMap where F: FnMut(Self::Item) -> Option<B> { FilterMap }
        fn next(&mut self) -> Option<Self::Item>;
    }
    pub struct FilterMap {}
    impl Iterator for FilterMap {
        type Item = i32;
        fn next(&mut self) -> i32 { 7 }
    }
}
"#,
            r#"
use core::iter::Iterator;
use core::option::Option::{self, Some, None};
fn foo() {
    let m = [1, 2, 3].iter().find_map(|x| Some(92));
}
"#,
        )
    }
}