]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/from_iter_instead_of_collect.rs
Merge commit '61eb38aeda6cb54b93b872bf503d70084c4d621c' into clippyup
[rust.git] / clippy_lints / src / methods / from_iter_instead_of_collect.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::ty::implements_trait;
3 use clippy_utils::{is_expr_path_def_path, paths, sugg};
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir as hir;
7 use rustc_lint::{LateContext, LintContext};
8 use rustc_middle::ty::Ty;
9 use rustc_span::sym;
10
11 use super::FROM_ITER_INSTEAD_OF_COLLECT;
12
13 pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>], func: &hir::Expr<'_>) {
14     if_chain! {
15         if is_expr_path_def_path(cx, func, &paths::FROM_ITERATOR_METHOD);
16         let ty = cx.typeck_results().expr_ty(expr);
17         let arg_ty = cx.typeck_results().expr_ty(&args[0]);
18         if let Some(iter_id) = cx.tcx.get_diagnostic_item(sym::Iterator);
19
20         if implements_trait(cx, arg_ty, iter_id, &[]);
21         then {
22             // `expr` implements `FromIterator` trait
23             let iter_expr = sugg::Sugg::hir(cx, &args[0], "..").maybe_par();
24             let turbofish = extract_turbofish(cx, expr, ty);
25             let sugg = format!("{}.collect::<{}>()", iter_expr, turbofish);
26             span_lint_and_sugg(
27                 cx,
28                 FROM_ITER_INSTEAD_OF_COLLECT,
29                 expr.span,
30                 "usage of `FromIterator::from_iter`",
31                 "use `.collect()` instead of `::from_iter()`",
32                 sugg,
33                 Applicability::MaybeIncorrect,
34             );
35         }
36     }
37 }
38
39 fn extract_turbofish(cx: &LateContext<'_>, expr: &hir::Expr<'_>, ty: Ty<'tcx>) -> String {
40     fn strip_angle_brackets(s: &str) -> Option<&str> {
41         s.strip_prefix('<')?.strip_suffix('>')
42     }
43
44     let call_site = expr.span.source_callsite();
45     if_chain! {
46         if let Ok(snippet) = cx.sess().source_map().span_to_snippet(call_site);
47         let snippet_split = snippet.split("::").collect::<Vec<_>>();
48         if let Some((_, elements)) = snippet_split.split_last();
49
50         then {
51             if_chain! {
52                 if let [type_specifier, _] = snippet_split.as_slice();
53                 if let Some(type_specifier) = strip_angle_brackets(type_specifier);
54                 if let Some((type_specifier, ..)) = type_specifier.split_once(" as ");
55                 then {
56                     type_specifier.to_string()
57                 } else {
58                     // is there a type specifier? (i.e.: like `<u32>` in `collections::BTreeSet::<u32>::`)
59                     if let Some(type_specifier) = snippet_split.iter().find(|e| strip_angle_brackets(e).is_some()) {
60                         // remove the type specifier from the path elements
61                         let without_ts = elements.iter().filter_map(|e| {
62                             if e == type_specifier { None } else { Some((*e).to_string()) }
63                         }).collect::<Vec<_>>();
64                         // join and add the type specifier at the end (i.e.: `collections::BTreeSet<u32>`)
65                         format!("{}{}", without_ts.join("::"), type_specifier)
66                     } else {
67                         // type is not explicitly specified so wildcards are needed
68                         // i.e.: 2 wildcards in `std::collections::BTreeMap<&i32, &char>`
69                         let ty_str = ty.to_string();
70                         let start = ty_str.find('<').unwrap_or(0);
71                         let end = ty_str.find('>').unwrap_or_else(|| ty_str.len());
72                         let nb_wildcard = ty_str[start..end].split(',').count();
73                         let wildcards = format!("_{}", ", _".repeat(nb_wildcard - 1));
74                         format!("{}<{}>", elements.join("::"), wildcards)
75                     }
76                 }
77             }
78         } else {
79             ty.to_string()
80         }
81     }
82 }