|
| 1 | +use clippy_config::Conf; |
| 2 | +use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg}; |
| 3 | +use clippy_utils::{is_none_arm, msrvs, peel_hir_expr_refs}; |
| 4 | +use rustc_errors::Applicability; |
| 5 | +use rustc_hir::def::{DefKind, Res}; |
| 6 | +use rustc_hir::{Arm, Expr, ExprKind, LangItem, Pat, PatKind, QPath, is_range_literal}; |
| 7 | +use rustc_lint::{LateContext, LateLintPass}; |
| 8 | +use rustc_middle::ty; |
| 9 | +use rustc_session::impl_lint_pass; |
| 10 | +use rustc_span::{Span, Symbol, sym}; |
| 11 | + |
| 12 | +declare_clippy_lint! { |
| 13 | + /// ### What it does |
| 14 | + /// This detects various manual reimplementations of `Option::as_slice`. |
| 15 | + /// |
| 16 | + /// ### Why is this bad? |
| 17 | + /// Those implementations are both more complex than calling `as_slice` |
| 18 | + /// and unlike that incur a branch, pessimizing performance and leading |
| 19 | + /// to more generated code. |
| 20 | + /// |
| 21 | + /// ### Example |
| 22 | + /// ```no_run |
| 23 | + ///# let opt = Some(1); |
| 24 | + /// _ = opt.as_ref().map_or(&[][..], std::slice::from_ref); |
| 25 | + /// _ = match opt.as_ref() { |
| 26 | + /// Some(f) => std::slice::from_ref(f), |
| 27 | + /// None => &[], |
| 28 | + /// }; |
| 29 | + /// ``` |
| 30 | + /// Use instead: |
| 31 | + /// ```no_run |
| 32 | + ///# let opt = Some(1); |
| 33 | + /// _ = opt.as_slice(); |
| 34 | + /// _ = opt.as_slice(); |
| 35 | + /// ``` |
| 36 | + #[clippy::version = "1.85.0"] |
| 37 | + pub MANUAL_OPTION_AS_SLICE, |
| 38 | + complexity, |
| 39 | + "manual `Option::as_slice`" |
| 40 | +} |
| 41 | + |
| 42 | +pub struct ManualOptionAsSlice { |
| 43 | + msrv: msrvs::Msrv, |
| 44 | +} |
| 45 | + |
| 46 | +impl ManualOptionAsSlice { |
| 47 | + pub fn new(conf: &Conf) -> Self { |
| 48 | + Self { |
| 49 | + msrv: conf.msrv.clone(), |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +impl_lint_pass!(ManualOptionAsSlice => [MANUAL_OPTION_AS_SLICE]); |
| 55 | + |
| 56 | +impl LateLintPass<'_> for ManualOptionAsSlice { |
| 57 | + extract_msrv_attr!(LateContext); |
| 58 | + |
| 59 | + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { |
| 60 | + let span = expr.span; |
| 61 | + if span.from_expansion() |
| 62 | + || !self.msrv.meets(if clippy_utils::is_in_const_context(cx) { |
| 63 | + msrvs::CONST_OPTION_AS_SLICE |
| 64 | + } else { |
| 65 | + msrvs::OPTION_AS_SLICE |
| 66 | + }) |
| 67 | + { |
| 68 | + return; |
| 69 | + } |
| 70 | + match expr.kind { |
| 71 | + ExprKind::Match(scrutinee, [arm1, arm2], _) => { |
| 72 | + if is_none_arm(cx, arm2) && check_arms(cx, arm2, arm1) |
| 73 | + || is_none_arm(cx, arm1) && check_arms(cx, arm1, arm2) |
| 74 | + { |
| 75 | + check_as_ref(cx, scrutinee, span); |
| 76 | + } |
| 77 | + }, |
| 78 | + ExprKind::If(cond, then, Some(other)) => { |
| 79 | + if let ExprKind::Let(let_expr) = cond.kind |
| 80 | + && let Some(binding) = extract_ident_from_some_pat(cx, let_expr.pat) |
| 81 | + && check_some_body(cx, binding, then) |
| 82 | + && is_empty_slice(cx, other.peel_blocks()) |
| 83 | + { |
| 84 | + check_as_ref(cx, let_expr.init, span); |
| 85 | + } |
| 86 | + }, |
| 87 | + ExprKind::MethodCall(seg, callee, [], _) => { |
| 88 | + if seg.ident.name.as_str() == "unwrap_or_default" { |
| 89 | + check_map(cx, callee, span); |
| 90 | + } |
| 91 | + }, |
| 92 | + ExprKind::MethodCall(seg, callee, [or], _) => match seg.ident.name.as_str() { |
| 93 | + "unwrap_or" => { |
| 94 | + if is_empty_slice(cx, or) { |
| 95 | + check_map(cx, callee, span); |
| 96 | + } |
| 97 | + }, |
| 98 | + "unwrap_or_else" => { |
| 99 | + if returns_empty_slice(cx, or) { |
| 100 | + check_map(cx, callee, span); |
| 101 | + } |
| 102 | + }, |
| 103 | + _ => {}, |
| 104 | + }, |
| 105 | + ExprKind::MethodCall(seg, callee, [or_else, map], _) => match seg.ident.name.as_str() { |
| 106 | + "map_or" => { |
| 107 | + if is_empty_slice(cx, or_else) && is_slice_from_ref(cx, map) { |
| 108 | + check_as_ref(cx, callee, span); |
| 109 | + } |
| 110 | + }, |
| 111 | + "map_or_else" => { |
| 112 | + if returns_empty_slice(cx, or_else) && is_slice_from_ref(cx, map) { |
| 113 | + check_as_ref(cx, callee, span); |
| 114 | + } |
| 115 | + }, |
| 116 | + _ => {}, |
| 117 | + }, |
| 118 | + _ => {}, |
| 119 | + } |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +fn check_map(cx: &LateContext<'_>, map: &Expr<'_>, span: Span) { |
| 124 | + if let ExprKind::MethodCall(seg, callee, [mapping], _) = map.kind |
| 125 | + && seg.ident.name == sym::map |
| 126 | + && is_slice_from_ref(cx, mapping) |
| 127 | + { |
| 128 | + check_as_ref(cx, callee, span); |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +fn check_as_ref(cx: &LateContext<'_>, expr: &Expr<'_>, span: Span) { |
| 133 | + if let ExprKind::MethodCall(seg, callee, [], _) = expr.kind |
| 134 | + && seg.ident.name == sym::as_ref |
| 135 | + && let ty::Adt(adtdef, ..) = cx.typeck_results().expr_ty(callee).kind() |
| 136 | + && cx.tcx.is_diagnostic_item(sym::Option, adtdef.did()) |
| 137 | + { |
| 138 | + if let Some(snippet) = clippy_utils::source::snippet_opt(cx, callee.span) { |
| 139 | + span_lint_and_sugg( |
| 140 | + cx, |
| 141 | + MANUAL_OPTION_AS_SLICE, |
| 142 | + span, |
| 143 | + "use `Option::as_slice`", |
| 144 | + "use", |
| 145 | + format!("{snippet}.as_slice()"), |
| 146 | + Applicability::MachineApplicable, |
| 147 | + ); |
| 148 | + } else { |
| 149 | + span_lint(cx, MANUAL_OPTION_AS_SLICE, span, "use `Option_as_slice`"); |
| 150 | + } |
| 151 | + } |
| 152 | +} |
| 153 | + |
| 154 | +fn extract_ident_from_some_pat(cx: &LateContext<'_>, pat: &Pat<'_>) -> Option<Symbol> { |
| 155 | + if let PatKind::TupleStruct(QPath::Resolved(None, path), [binding], _) = pat.kind |
| 156 | + && let Res::Def(DefKind::Ctor(..), def_id) = path.res |
| 157 | + && let PatKind::Binding(_mode, _hir_id, ident, _inner_pat) = binding.kind |
| 158 | + && clippy_utils::is_lang_item_or_ctor(cx, def_id, LangItem::OptionSome) |
| 159 | + { |
| 160 | + Some(ident.name) |
| 161 | + } else { |
| 162 | + None |
| 163 | + } |
| 164 | +} |
| 165 | + |
| 166 | +/// Returns true if `expr` is `std::slice::from_ref(<name>)`. Used in `if let`s. |
| 167 | +fn check_some_body(cx: &LateContext<'_>, name: Symbol, expr: &Expr<'_>) -> bool { |
| 168 | + if let ExprKind::Call(slice_from_ref, [arg]) = expr.peel_blocks().kind |
| 169 | + && is_slice_from_ref(cx, slice_from_ref) |
| 170 | + && let ExprKind::Path(QPath::Resolved(None, path)) = arg.kind |
| 171 | + && let [seg] = path.segments |
| 172 | + { |
| 173 | + seg.ident.name == name |
| 174 | + } else { |
| 175 | + false |
| 176 | + } |
| 177 | +} |
| 178 | + |
| 179 | +fn check_arms(cx: &LateContext<'_>, none_arm: &Arm<'_>, some_arm: &Arm<'_>) -> bool { |
| 180 | + if none_arm.guard.is_none() |
| 181 | + && some_arm.guard.is_none() |
| 182 | + && is_empty_slice(cx, none_arm.body) |
| 183 | + && let Some(name) = extract_ident_from_some_pat(cx, some_arm.pat) |
| 184 | + { |
| 185 | + check_some_body(cx, name, some_arm.body) |
| 186 | + } else { |
| 187 | + false |
| 188 | + } |
| 189 | +} |
| 190 | + |
| 191 | +fn returns_empty_slice(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { |
| 192 | + match expr.kind { |
| 193 | + ExprKind::Path(_) => clippy_utils::is_path_diagnostic_item(cx, expr, sym::default_fn), |
| 194 | + ExprKind::Closure(cl) => is_empty_slice(cx, cx.tcx.hir().body(cl.body).value), |
| 195 | + _ => false, |
| 196 | + } |
| 197 | +} |
| 198 | + |
| 199 | +/// Returns if expr returns an empty slice. If: |
| 200 | +/// - An indexing operation to an empty array with a built-in range. `[][..]` |
| 201 | +/// - An indexing operation with a zero-ended range. `expr[..0]` |
| 202 | +/// - A reference to an empty array. `&[]` |
| 203 | +/// - Or a call to `Default::default`. |
| 204 | +fn is_empty_slice(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { |
| 205 | + let expr = peel_hir_expr_refs(expr.peel_blocks()).0; |
| 206 | + match expr.kind { |
| 207 | + ExprKind::Index(arr, range, _) => match arr.kind { |
| 208 | + ExprKind::Array([]) => is_range_literal(range), |
| 209 | + ExprKind::Array(_) => { |
| 210 | + let Some(range) = clippy_utils::higher::Range::hir(range) else { |
| 211 | + return false; |
| 212 | + }; |
| 213 | + range.end.is_some_and(|e| clippy_utils::is_integer_const(cx, e, 0)) |
| 214 | + }, |
| 215 | + _ => false, |
| 216 | + }, |
| 217 | + ExprKind::Array([]) => true, |
| 218 | + ExprKind::Call(def, []) => clippy_utils::is_path_diagnostic_item(cx, def, sym::default_fn), |
| 219 | + _ => false, |
| 220 | + } |
| 221 | +} |
| 222 | + |
| 223 | +fn is_slice_from_ref(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { |
| 224 | + clippy_utils::is_expr_path_def_path(cx, expr, &["core", "slice", "raw", "from_ref"]) |
| 225 | +} |
0 commit comments