]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/types/box_collection.rs
Merge commit 'ac0e10aa68325235069a842f47499852b2dee79e' into clippyup
[rust.git] / src / tools / clippy / clippy_lints / src / types / box_collection.rs
1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::{path_def_id, qpath_generic_tys};
3 use rustc_hir::{self as hir, def_id::DefId, QPath};
4 use rustc_lint::LateContext;
5 use rustc_span::{sym, Symbol};
6
7 use super::BOX_COLLECTION;
8
9 pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, qpath: &QPath<'_>, def_id: DefId) -> bool {
10     if_chain! {
11         if Some(def_id) == cx.tcx.lang_items().owned_box();
12         if let Some(item_type) = get_std_collection(cx, qpath);
13         then {
14             let generic = match item_type {
15                 sym::String => "",
16                 _ => "<..>",
17             };
18
19             let box_content = format!("{item_type}{generic}");
20             span_lint_and_help(
21                 cx,
22                 BOX_COLLECTION,
23                 hir_ty.span,
24                 &format!(
25                     "you seem to be trying to use `Box<{box_content}>`. Consider using just `{box_content}`"),
26                 None,
27                 &format!(
28                     "`{box_content}` is already on the heap, `Box<{box_content}>` makes an extra allocation")
29             );
30             true
31         } else {
32             false
33         }
34     }
35 }
36
37 fn get_std_collection(cx: &LateContext<'_>, qpath: &QPath<'_>) -> Option<Symbol> {
38     let param = qpath_generic_tys(qpath).next()?;
39     let id = path_def_id(cx, param)?;
40     cx.tcx.get_diagnostic_name(id).filter(|&name| {
41         matches!(
42             name,
43             sym::HashMap
44                 | sym::String
45                 | sym::Vec
46                 | sym::HashSet
47                 | sym::VecDeque
48                 | sym::LinkedList
49                 | sym::BTreeMap
50                 | sym::BTreeSet
51                 | sym::BinaryHeap
52         )
53     })
54 }