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;
7 use rustc_lint::{LateContext, LintContext};
8 use rustc_middle::ty::Ty;
11 use super::FROM_ITER_INSTEAD_OF_COLLECT;
13 pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>], func: &hir::Expr<'_>) {
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);
20 if implements_trait(cx, arg_ty, iter_id, &[]);
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);
28 FROM_ITER_INSTEAD_OF_COLLECT,
30 "usage of `FromIterator::from_iter`",
31 "use `.collect()` instead of `::from_iter()`",
33 Applicability::MaybeIncorrect,
39 fn extract_turbofish(cx: &LateContext<'_>, expr: &hir::Expr<'_>, ty: Ty<'tcx>) -> String {
40 let call_site = expr.span.source_callsite();
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();
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)
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)