]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/from_iter_instead_of_collect.rs
Merge commit '98e2b9f25b6db4b2680a3d388456d9f95cb28344' 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     let call_site = expr.span.source_callsite();
41     if_chain! {
42         if let Ok(snippet) = cx.sess().source_map().span_to_snippet(call_site);
43         let snippet_split = snippet.split("::").collect::<Vec<_>>();
44         if let Some((_, elements)) = snippet_split.split_last();
45
46         then {
47             // is there a type specifier? (i.e.: like `<u32>` in `collections::BTreeSet::<u32>::`)
48             if let Some(type_specifier) = snippet_split.iter().find(|e| e.starts_with('<') && e.ends_with('>')) {
49                 // remove the type specifier from the path elements
50                 let without_ts = elements.iter().filter_map(|e| {
51                     if e == type_specifier { None } else { Some((*e).to_string()) }
52                 }).collect::<Vec<_>>();
53                 // join and add the type specifier at the end (i.e.: `collections::BTreeSet<u32>`)
54                 format!("{}{}", without_ts.join("::"), type_specifier)
55             } else {
56                 // type is not explicitly specified so wildcards are needed
57                 // i.e.: 2 wildcards in `std::collections::BTreeMap<&i32, &char>`
58                 let ty_str = ty.to_string();
59                 let start = ty_str.find('<').unwrap_or(0);
60                 let end = ty_str.find('>').unwrap_or_else(|| ty_str.len());
61                 let nb_wildcard = ty_str[start..end].split(',').count();
62                 let wildcards = format!("_{}", ", _".repeat(nb_wildcard - 1));
63                 format!("{}<{}>", elements.join("::"), wildcards)
64             }
65         } else {
66             ty.to_string()
67         }
68     }
69 }