]> git.proxmox.com Git - rustc.git/blame - src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs
Update upstream source from tag 'upstream/1.52.1+dfsg1'
[rustc.git] / src / tools / clippy / clippy_lints / src / types / redundant_allocation.rs
CommitLineData
f20569fa
XL
1use rustc_errors::Applicability;
2use rustc_hir::{self as hir, def_id::DefId, LangItem, QPath, TyKind};
3use rustc_lint::LateContext;
4use rustc_span::symbol::sym;
5
6use crate::utils::{
7 get_qpath_generic_tys, is_ty_param_diagnostic_item, is_ty_param_lang_item, snippet_with_applicability,
8 span_lint_and_sugg,
9};
10
11use super::{utils, REDUNDANT_ALLOCATION};
12
13pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, qpath: &QPath<'_>, def_id: DefId) -> bool {
14 if Some(def_id) == cx.tcx.lang_items().owned_box() {
15 if let Some(span) = utils::match_borrows_parameter(cx, qpath) {
16 let mut applicability = Applicability::MachineApplicable;
17 span_lint_and_sugg(
18 cx,
19 REDUNDANT_ALLOCATION,
20 hir_ty.span,
21 "usage of `Box<&T>`",
22 "try",
23 snippet_with_applicability(cx, span, "..", &mut applicability).to_string(),
24 applicability,
25 );
26 return true;
27 }
28 }
29
30 if cx.tcx.is_diagnostic_item(sym::Rc, def_id) {
31 if let Some(ty) = is_ty_param_diagnostic_item(cx, qpath, sym::Rc) {
32 let mut applicability = Applicability::MachineApplicable;
33 span_lint_and_sugg(
34 cx,
35 REDUNDANT_ALLOCATION,
36 hir_ty.span,
37 "usage of `Rc<Rc<T>>`",
38 "try",
39 snippet_with_applicability(cx, ty.span, "..", &mut applicability).to_string(),
40 applicability,
41 );
42 true
43 } else if let Some(ty) = is_ty_param_lang_item(cx, qpath, LangItem::OwnedBox) {
44 let qpath = match &ty.kind {
45 TyKind::Path(qpath) => qpath,
46 _ => return false,
47 };
48 let inner_span = match get_qpath_generic_tys(qpath).next() {
49 Some(ty) => ty.span,
50 None => return false,
51 };
52 let mut applicability = Applicability::MachineApplicable;
53 span_lint_and_sugg(
54 cx,
55 REDUNDANT_ALLOCATION,
56 hir_ty.span,
57 "usage of `Rc<Box<T>>`",
58 "try",
59 format!(
60 "Rc<{}>",
61 snippet_with_applicability(cx, inner_span, "..", &mut applicability)
62 ),
63 applicability,
64 );
65 true
66 } else {
67 utils::match_borrows_parameter(cx, qpath).map_or(false, |span| {
68 let mut applicability = Applicability::MachineApplicable;
69 span_lint_and_sugg(
70 cx,
71 REDUNDANT_ALLOCATION,
72 hir_ty.span,
73 "usage of `Rc<&T>`",
74 "try",
75 snippet_with_applicability(cx, span, "..", &mut applicability).to_string(),
76 applicability,
77 );
78 true
79 })
80 }
81 } else {
82 false
83 }
84}