|
| 1 | +use crate::utils::{ |
| 2 | + is_type_diagnostic_item, match_def_path, paths, peel_hir_expr_refs, peel_mid_ty_refs_is_mutable, |
| 3 | + snippet_with_applicability, span_lint_and_sugg, |
| 4 | +}; |
| 5 | +use rustc_ast::util::parser::PREC_POSTFIX; |
| 6 | +use rustc_errors::Applicability; |
| 7 | +use rustc_hir::{Arm, BindingAnnotation, Block, Expr, ExprKind, Mutability, Pat, PatKind, Path, QPath}; |
| 8 | +use rustc_lint::{LateContext, LateLintPass, LintContext}; |
| 9 | +use rustc_middle::lint::in_external_macro; |
| 10 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 11 | +use rustc_span::symbol::{sym, Ident}; |
| 12 | + |
| 13 | +declare_clippy_lint! { |
| 14 | + /// **What it does:** Checks for usages of `match` which could be implemented using `map` |
| 15 | + /// |
| 16 | + /// **Why is this bad?** Using the `map` method is clearer and more concise. |
| 17 | + /// |
| 18 | + /// **Known problems:** None. |
| 19 | + /// |
| 20 | + /// **Example:** |
| 21 | + /// |
| 22 | + /// ```rust |
| 23 | + /// match Some(0) { |
| 24 | + /// Some(x) => Some(x + 1), |
| 25 | + /// None => None, |
| 26 | + /// }; |
| 27 | + /// ``` |
| 28 | + /// Use instead: |
| 29 | + /// ```rust |
| 30 | + /// Some(0).map(|x| x + 1); |
| 31 | + /// ``` |
| 32 | + pub MANUAL_MAP, |
| 33 | + style, |
| 34 | + "reimplementation of `map`" |
| 35 | +} |
| 36 | + |
| 37 | +declare_lint_pass!(ManualMap => [MANUAL_MAP]); |
| 38 | + |
| 39 | +impl LateLintPass<'_> for ManualMap { |
| 40 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { |
| 41 | + if in_external_macro(cx.sess(), expr.span) { |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + if let ExprKind::Match(scrutinee, [arm1 @ Arm { guard: None, .. }, arm2 @ Arm { guard: None, .. }], _) = |
| 46 | + expr.kind |
| 47 | + { |
| 48 | + let (scrutinee_ty, ty_ref_count, ty_mutability) = |
| 49 | + peel_mid_ty_refs_is_mutable(cx.typeck_results().expr_ty(scrutinee)); |
| 50 | + if !is_type_diagnostic_item(cx, scrutinee_ty, sym::option_type) |
| 51 | + || !is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::option_type) |
| 52 | + { |
| 53 | + return; |
| 54 | + } |
| 55 | + |
| 56 | + let (some_expr, some_pat, pat_ref_count, is_wild_none) = |
| 57 | + match (try_parse_pattern(cx, arm1.pat), try_parse_pattern(cx, arm2.pat)) { |
| 58 | + (Some(OptionPat::Wild), Some(OptionPat::Some { pattern, ref_count })) |
| 59 | + if is_none_expr(cx, arm1.body) => |
| 60 | + { |
| 61 | + (arm2.body, pattern, ref_count, true) |
| 62 | + }, |
| 63 | + (Some(OptionPat::None), Some(OptionPat::Some { pattern, ref_count })) |
| 64 | + if is_none_expr(cx, arm1.body) => |
| 65 | + { |
| 66 | + (arm2.body, pattern, ref_count, false) |
| 67 | + }, |
| 68 | + (Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::Wild)) |
| 69 | + if is_none_expr(cx, arm2.body) => |
| 70 | + { |
| 71 | + (arm1.body, pattern, ref_count, true) |
| 72 | + }, |
| 73 | + (Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::None)) |
| 74 | + if is_none_expr(cx, arm2.body) => |
| 75 | + { |
| 76 | + (arm1.body, pattern, ref_count, false) |
| 77 | + }, |
| 78 | + _ => return, |
| 79 | + }; |
| 80 | + |
| 81 | + // Top level or patterns aren't allowed in closures. |
| 82 | + if matches!(some_pat.kind, PatKind::Or(_)) { |
| 83 | + return; |
| 84 | + } |
| 85 | + |
| 86 | + let some_expr = match get_some_expr(cx, some_expr) { |
| 87 | + Some(expr) => expr, |
| 88 | + None => return, |
| 89 | + }; |
| 90 | + |
| 91 | + // Determine which binding mode to use. |
| 92 | + let explicit_ref = some_pat.contains_explicit_ref_binding(); |
| 93 | + let binding_mutability = explicit_ref.or(if ty_ref_count != pat_ref_count { |
| 94 | + Some(ty_mutability) |
| 95 | + } else { |
| 96 | + None |
| 97 | + }); |
| 98 | + let as_ref_str = match binding_mutability { |
| 99 | + Some(Mutability::Mut) => ".as_mut()", |
| 100 | + Some(Mutability::Not) => ".as_ref()", |
| 101 | + None => "", |
| 102 | + }; |
| 103 | + |
| 104 | + let mut app = Applicability::MachineApplicable; |
| 105 | + |
| 106 | + // Remove address-of expressions from the scrutinee. `as_ref` will be called, |
| 107 | + // the type is copyable, or the option is being passed by value. |
| 108 | + let scrutinee = peel_hir_expr_refs(scrutinee).0; |
| 109 | + let scrutinee_str = snippet_with_applicability(cx, scrutinee.span, "_", &mut app); |
| 110 | + let scrutinee_str = if expr.precedence().order() < PREC_POSTFIX { |
| 111 | + // Parens are needed to chain method calls. |
| 112 | + format!("({})", scrutinee_str) |
| 113 | + } else { |
| 114 | + scrutinee_str.into() |
| 115 | + }; |
| 116 | + |
| 117 | + let body_str = if let PatKind::Binding(annotation, _, some_binding, None) = some_pat.kind { |
| 118 | + if let Some(func) = can_pass_as_func(cx, some_binding, some_expr) { |
| 119 | + snippet_with_applicability(cx, func.span, "..", &mut app).into_owned() |
| 120 | + } else { |
| 121 | + // `ref` and `ref mut` annotations were handled earlier. |
| 122 | + let annotation = if matches!(annotation, BindingAnnotation::Mutable) { |
| 123 | + "mut " |
| 124 | + } else { |
| 125 | + "" |
| 126 | + }; |
| 127 | + format!( |
| 128 | + "|{}{}| {}", |
| 129 | + annotation, |
| 130 | + some_binding, |
| 131 | + snippet_with_applicability(cx, some_expr.span, "..", &mut app) |
| 132 | + ) |
| 133 | + } |
| 134 | + } else if !is_wild_none && explicit_ref.is_none() { |
| 135 | + // TODO: handle explicit reference annotations. |
| 136 | + format!( |
| 137 | + "|{}| {}", |
| 138 | + snippet_with_applicability(cx, some_pat.span, "..", &mut app), |
| 139 | + snippet_with_applicability(cx, some_expr.span, "..", &mut app) |
| 140 | + ) |
| 141 | + } else { |
| 142 | + // Refutable bindings and mixed reference annotations can't be handled by `map`. |
| 143 | + return; |
| 144 | + }; |
| 145 | + |
| 146 | + span_lint_and_sugg( |
| 147 | + cx, |
| 148 | + MANUAL_MAP, |
| 149 | + expr.span, |
| 150 | + "manual implementation of `Option::map`", |
| 151 | + "try this", |
| 152 | + format!("{}{}.map({})", scrutinee_str, as_ref_str, body_str), |
| 153 | + app, |
| 154 | + ); |
| 155 | + } |
| 156 | + } |
| 157 | +} |
| 158 | + |
| 159 | +// Checks whether the expression could be passed as a function, or whether a closure is needed. |
| 160 | +// Returns the function to be passed to `map` if it exists. |
| 161 | +fn can_pass_as_func(cx: &LateContext<'tcx>, binding: Ident, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> { |
| 162 | + match expr.kind { |
| 163 | + ExprKind::Call(func, [arg]) |
| 164 | + if matches!(arg.kind, |
| 165 | + ExprKind::Path(QPath::Resolved(None, Path { segments: [path], ..})) |
| 166 | + if path.ident == binding |
| 167 | + ) && cx.typeck_results().expr_adjustments(arg).is_empty() => |
| 168 | + { |
| 169 | + Some(func) |
| 170 | + }, |
| 171 | + _ => None, |
| 172 | + } |
| 173 | +} |
| 174 | + |
| 175 | +enum OptionPat<'a> { |
| 176 | + Wild, |
| 177 | + None, |
| 178 | + Some { |
| 179 | + // The pattern contained in the `Some` tuple. |
| 180 | + pattern: &'a Pat<'a>, |
| 181 | + // The number of references before the `Some` tuple. |
| 182 | + // e.g. `&&Some(_)` has a ref count of 2. |
| 183 | + ref_count: usize, |
| 184 | + }, |
| 185 | +} |
| 186 | + |
| 187 | +// Try to parse into a recognized `Option` pattern. |
| 188 | +// i.e. `_`, `None`, `Some(..)`, or a reference to any of those. |
| 189 | +fn try_parse_pattern(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) -> Option<OptionPat<'tcx>> { |
| 190 | + fn f(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ref_count: usize) -> Option<OptionPat<'tcx>> { |
| 191 | + match pat.kind { |
| 192 | + PatKind::Wild => Some(OptionPat::Wild), |
| 193 | + PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1), |
| 194 | + PatKind::Path(QPath::Resolved(None, path)) |
| 195 | + if path |
| 196 | + .res |
| 197 | + .opt_def_id() |
| 198 | + .map_or(false, |id| match_def_path(cx, id, &paths::OPTION_NONE)) => |
| 199 | + { |
| 200 | + Some(OptionPat::None) |
| 201 | + }, |
| 202 | + PatKind::TupleStruct(QPath::Resolved(None, path), [pattern], _) |
| 203 | + if path |
| 204 | + .res |
| 205 | + .opt_def_id() |
| 206 | + .map_or(false, |id| match_def_path(cx, id, &paths::OPTION_SOME)) => |
| 207 | + { |
| 208 | + Some(OptionPat::Some { pattern, ref_count }) |
| 209 | + }, |
| 210 | + _ => None, |
| 211 | + } |
| 212 | + } |
| 213 | + f(cx, pat, 0) |
| 214 | +} |
| 215 | + |
| 216 | +// Checks for an expression wrapped by the `Some` constructor. Returns the contained expression. |
| 217 | +fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> { |
| 218 | + // TODO: Allow more complex expressions. |
| 219 | + match expr.kind { |
| 220 | + ExprKind::Call( |
| 221 | + Expr { |
| 222 | + kind: ExprKind::Path(QPath::Resolved(None, path)), |
| 223 | + .. |
| 224 | + }, |
| 225 | + [arg], |
| 226 | + ) => { |
| 227 | + if match_def_path(cx, path.res.opt_def_id()?, &paths::OPTION_SOME) { |
| 228 | + Some(arg) |
| 229 | + } else { |
| 230 | + None |
| 231 | + } |
| 232 | + }, |
| 233 | + ExprKind::Block( |
| 234 | + Block { |
| 235 | + stmts: [], |
| 236 | + expr: Some(expr), |
| 237 | + .. |
| 238 | + }, |
| 239 | + _, |
| 240 | + ) => get_some_expr(cx, expr), |
| 241 | + _ => None, |
| 242 | + } |
| 243 | +} |
| 244 | + |
| 245 | +// Checks for the `None` value. |
| 246 | +fn is_none_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool { |
| 247 | + match expr.kind { |
| 248 | + ExprKind::Path(QPath::Resolved(None, path)) => path |
| 249 | + .res |
| 250 | + .opt_def_id() |
| 251 | + .map_or(false, |id| match_def_path(cx, id, &paths::OPTION_NONE)), |
| 252 | + ExprKind::Block( |
| 253 | + Block { |
| 254 | + stmts: [], |
| 255 | + expr: Some(expr), |
| 256 | + .. |
| 257 | + }, |
| 258 | + _, |
| 259 | + ) => is_none_expr(cx, expr), |
| 260 | + _ => false, |
| 261 | + } |
| 262 | +} |
0 commit comments