|
| 1 | +use clippy_utils::{diagnostics::span_lint_and_help, is_from_proc_macro, last_path_segment, path_res}; |
| 2 | +use rustc_hir::{def::DefKind, def_id::DefId, Expr, ExprKind}; |
| 3 | +use rustc_hir_typeck::{FnCtxt, Inherited}; |
| 4 | +use rustc_lint::LateContext; |
| 5 | +use rustc_middle::ty::Ty; |
| 6 | +use rustc_span::{symbol::Ident, Span}; |
| 7 | + |
| 8 | +use super::UNNECESSARY_UNWRAP_UNCHECKED; |
| 9 | + |
| 10 | +#[derive(Clone, Copy, Debug)] |
| 11 | +struct VariantAndIdent { |
| 12 | + variant: Variant, |
| 13 | + ident: Ident, |
| 14 | +} |
| 15 | + |
| 16 | +impl<'tcx> VariantAndIdent { |
| 17 | + fn new(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, recv: &Expr<'_>, fcx: &FnCtxt<'_, 'tcx>) -> Option<Self> { |
| 18 | + let expected_ret_ty = cx.typeck_results().expr_ty(expr); |
| 19 | + match recv.kind { |
| 20 | + // Construct `Variant::Fn(_)`, if applicable. This is necessary for us to handle |
| 21 | + // functions like `std::str::from_utf8_unchecked`. |
| 22 | + ExprKind::Call(path, _) if let ExprKind::Path(qpath) = path.kind |
| 23 | + && let parent = cx.tcx.parent(path_res(cx, path).def_id()) |
| 24 | + // Don't use `parent_module`. We only want to lint if its first parent is a `Mod` |
| 25 | + && cx.tcx.def_kind(parent) == DefKind::Mod |
| 26 | + && let children = parent.as_local().map_or_else( |
| 27 | + || cx.tcx.module_children(parent), |
| 28 | + // We must use a !query for local modules to prevent an ICE. |
| 29 | + |parent| cx.tcx.module_children_local(parent), |
| 30 | + ) |
| 31 | + && !children.is_empty() |
| 32 | + && let Some(unchecked_ident) = unchecked_ident(&last_path_segment(&qpath).ident) |
| 33 | + && let Some(unchecked_def_id) = children |
| 34 | + .iter() |
| 35 | + .find(|child| child.ident == unchecked_ident) |
| 36 | + .map(|func| func.res.def_id()) |
| 37 | + && fn_ret_ty(cx, unchecked_def_id) == expected_ret_ty => |
| 38 | + { |
| 39 | + Some(Self { |
| 40 | + variant: Variant::Fn(unchecked_def_id), |
| 41 | + ident: unchecked_ident, |
| 42 | + }) |
| 43 | + }, |
| 44 | + // We unfortunately must handle `A::a(&a)` and `a.a()` separately, this handles the |
| 45 | + // former |
| 46 | + ExprKind::Call(path, _) if let ExprKind::Path(qpath) = path.kind |
| 47 | + && let parent = cx.tcx.parent(path_res(cx, path).def_id()) |
| 48 | + // Don't use `parent_impl`. We only want to lint if its first parent is an `Impl` |
| 49 | + && matches!(cx.tcx.def_kind(parent), DefKind::Impl { .. }) |
| 50 | + && let Some(unchecked_ident) = unchecked_ident(&last_path_segment(&qpath).ident) |
| 51 | + && let Some(unchecked) = fcx.associated_value(parent, unchecked_ident) |
| 52 | + && fn_ret_ty(cx, unchecked.def_id) == expected_ret_ty => |
| 53 | + { |
| 54 | + Some(Self { |
| 55 | + variant: Variant::Assoc(AssocKind::new(unchecked.fn_has_self_parameter), unchecked.def_id), |
| 56 | + ident: unchecked_ident, |
| 57 | + }) |
| 58 | + }, |
| 59 | + // ... And now the latter ^^ |
| 60 | + ExprKind::MethodCall(segment, _, _, _) |
| 61 | + if let Some(def_id) = cx.typeck_results().type_dependent_def_id(recv.hir_id) |
| 62 | + && let parent = cx.tcx.parent(def_id) |
| 63 | + // Don't use `parent_impl`. We only want to lint if its first parent is an `Impl` |
| 64 | + && matches!(cx.tcx.def_kind(parent), DefKind::Impl { .. }) |
| 65 | + && let ident = segment.ident.to_string() |
| 66 | + && let Some(unchecked_ident) = unchecked_ident(&ident) |
| 67 | + && let Some(unchecked) = fcx.associated_value(parent, unchecked_ident) |
| 68 | + && fn_ret_ty(cx, unchecked.def_id) == expected_ret_ty => |
| 69 | + { |
| 70 | + Some(Self { |
| 71 | + variant: Variant::Assoc(AssocKind::Method, unchecked.def_id), |
| 72 | + ident: unchecked_ident, |
| 73 | + }) |
| 74 | + }, |
| 75 | + _ => None, |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + fn msg(self) -> &'static str { |
| 80 | + // Don't use `format!` instead -- it won't be optimized out. |
| 81 | + match self.variant { |
| 82 | + Variant::Fn(_) => "usage of `unwrap_unchecked` when an `_unchecked` variant of the function exists", |
| 83 | + Variant::Assoc(kind, _) => { |
| 84 | + if kind.is_assoc_fn() { |
| 85 | + "usage of `unwrap_unchecked` when an `_unchecked` variant of the associated function exists" |
| 86 | + } else { |
| 87 | + "usage of `unwrap_unchecked` when an `_unchecked` variant of the method exists" |
| 88 | + } |
| 89 | + }, |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + fn as_str(self) -> &'static str { |
| 94 | + match self.variant { |
| 95 | + Variant::Fn(_) => "function", |
| 96 | + Variant::Assoc(kind, _) => { |
| 97 | + if kind.is_assoc_fn() { |
| 98 | + "associated function" |
| 99 | + } else { |
| 100 | + "method" |
| 101 | + } |
| 102 | + }, |
| 103 | + } |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +#[derive(Clone, Copy, Debug)] |
| 108 | +enum Variant { |
| 109 | + /// Free `fn` in a module. `DefId` is the `_unchecked` function. |
| 110 | + Fn(DefId), |
| 111 | + /// Associated item from an `impl`. `DefId` is the `_unchecked` associated item. |
| 112 | + Assoc(AssocKind, DefId), |
| 113 | +} |
| 114 | + |
| 115 | +fn unchecked_ident(checked_ident: &impl ToString) -> Option<Ident> { |
| 116 | + let checked_ident = checked_ident.to_string(); |
| 117 | + // Only add `_unchecked` if it doesn't already end with `_` |
| 118 | + (!checked_ident.ends_with('_')).then(|| Ident::from_str(&(checked_ident + "_unchecked"))) |
| 119 | +} |
| 120 | + |
| 121 | +fn fn_ret_ty<'tcx>(cx: &LateContext<'tcx>, def_id: DefId) -> Ty<'tcx> { |
| 122 | + cx.tcx.fn_sig(def_id).skip_binder().output().skip_binder() |
| 123 | +} |
| 124 | + |
| 125 | +/// This only exists so the help message shows `associated function` or `method`, depending on |
| 126 | +/// whether it has a `self` parameter. |
| 127 | +#[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 128 | +enum AssocKind { |
| 129 | + /// No `self`: `fn new() -> Self` |
| 130 | + Fn, |
| 131 | + /// Has `self`: `fn ty<'tcx>(&self) -> Ty<'tcx>` |
| 132 | + Method, |
| 133 | +} |
| 134 | + |
| 135 | +impl AssocKind { |
| 136 | + fn new(fn_has_self_parameter: bool) -> Self { |
| 137 | + if fn_has_self_parameter { |
| 138 | + AssocKind::Method |
| 139 | + } else { |
| 140 | + AssocKind::Fn |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + fn is_assoc_fn(self) -> bool { |
| 145 | + self == Self::Fn |
| 146 | + } |
| 147 | + |
| 148 | + #[expect(dead_code)] |
| 149 | + fn is_method(self) -> bool { |
| 150 | + self == Self::Method |
| 151 | + } |
| 152 | +} |
| 153 | + |
| 154 | +pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, recv: &Expr<'_>, span: Span) { |
| 155 | + if !expr.span.from_expansion() |
| 156 | + && let Some(variant) = VariantAndIdent::new( |
| 157 | + cx, |
| 158 | + expr, |
| 159 | + recv, |
| 160 | + &FnCtxt::new( |
| 161 | + &Inherited::new(cx.tcx, expr.hir_id.owner.def_id), |
| 162 | + cx.param_env, |
| 163 | + expr.hir_id.owner.def_id, |
| 164 | + ), |
| 165 | + ) |
| 166 | + && !is_from_proc_macro(cx, expr) |
| 167 | + { |
| 168 | + span_lint_and_help( |
| 169 | + cx, |
| 170 | + UNNECESSARY_UNWRAP_UNCHECKED, |
| 171 | + span, |
| 172 | + variant.msg(), |
| 173 | + None, |
| 174 | + &format!( |
| 175 | + "call the {} `{}` instead, and remove the `unwrap_unchecked` call", |
| 176 | + variant.as_str(), |
| 177 | + variant.ident, |
| 178 | + ), |
| 179 | + ); |
| 180 | + } |
| 181 | +} |
0 commit comments