1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::source::{snippet, snippet_with_applicability};
3 use clippy_utils::{path_def_id, qpath_generic_tys};
4 use rustc_errors::Applicability;
5 use rustc_hir::{self as hir, def_id::DefId, QPath, TyKind};
6 use rustc_lint::LateContext;
7 use rustc_span::symbol::sym;
9 use super::{utils, REDUNDANT_ALLOCATION};
11 pub(super) fn check(cx: &LateContext<'_>, hir_ty: &hir::Ty<'_>, qpath: &QPath<'_>, def_id: DefId) -> bool {
12 let outer_sym = if Some(def_id) == cx.tcx.lang_items().owned_box() {
14 } else if cx.tcx.is_diagnostic_item(sym::Rc, def_id) {
16 } else if cx.tcx.is_diagnostic_item(sym::Arc, def_id) {
22 if let Some(span) = utils::match_borrows_parameter(cx, qpath) {
23 let mut applicability = Applicability::MaybeIncorrect;
24 let generic_snippet = snippet_with_applicability(cx, span, "..", &mut applicability);
29 &format!("usage of `{}<{}>`", outer_sym, generic_snippet),
31 diag.span_suggestion(hir_ty.span, "try", format!("{}", generic_snippet), applicability);
33 "`{generic}` is already a pointer, `{outer}<{generic}>` allocates a pointer on the heap",
35 generic = generic_snippet
42 let Some(ty) = qpath_generic_tys(qpath).next() else { return false };
43 let Some(id) = path_def_id(cx, ty) else { return false };
44 let (inner_sym, ty) = match cx.tcx.get_diagnostic_name(id) {
45 Some(sym::Arc) => ("Arc", ty),
46 Some(sym::Rc) => ("Rc", ty),
47 _ if Some(id) == cx.tcx.lang_items().owned_box() => ("Box", ty),
51 let inner_qpath = match &ty.kind {
52 TyKind::Path(inner_qpath) => inner_qpath,
55 let inner_span = match qpath_generic_tys(inner_qpath).next() {
57 // Box<Box<dyn T>> is smaller than Box<dyn T> because of wide pointers
58 if matches!(ty.kind, TyKind::TraitObject(..)) {
65 if inner_sym == outer_sym {
66 let mut applicability = Applicability::MaybeIncorrect;
67 let generic_snippet = snippet_with_applicability(cx, inner_span, "..", &mut applicability);
72 &format!("usage of `{}<{}<{}>>`", outer_sym, inner_sym, generic_snippet),
77 format!("{}<{}>", outer_sym, generic_snippet),
81 "`{inner}<{generic}>` is already on the heap, `{outer}<{inner}<{generic}>>` makes an extra allocation",
84 generic = generic_snippet
89 let generic_snippet = snippet(cx, inner_span, "..");
94 &format!("usage of `{}<{}<{}>>`", outer_sym, inner_sym, generic_snippet),
97 "`{inner}<{generic}>` is already on the heap, `{outer}<{inner}<{generic}>>` makes an extra allocation",
100 generic = generic_snippet
103 "consider using just `{outer}<{generic}>` or `{inner}<{generic}>`",
106 generic = generic_snippet