1 use crate::{map_unit_fn::OPTION_MAP_UNIT_FN, matches::MATCH_AS_REF};
2 use clippy_utils::diagnostics::span_lint_and_sugg;
3 use clippy_utils::source::{snippet_with_applicability, snippet_with_context};
4 use clippy_utils::ty::{can_partially_move_ty, is_type_diagnostic_item, peel_mid_ty_refs_is_mutable};
5 use clippy_utils::{in_constant, is_allowed, is_else_clause, is_lang_ctor, match_var, peel_hir_expr_refs};
6 use rustc_ast::util::parser::PREC_POSTFIX;
7 use rustc_errors::Applicability;
8 use rustc_hir::LangItem::{OptionNone, OptionSome};
11 intravisit::{walk_expr, ErasedMap, NestedVisitorMap, Visitor},
12 Arm, BindingAnnotation, Block, Expr, ExprKind, MatchSource, Mutability, Pat, PatKind, Path, QPath,
14 use rustc_lint::{LateContext, LateLintPass, LintContext};
15 use rustc_middle::lint::in_external_macro;
16 use rustc_session::{declare_lint_pass, declare_tool_lint};
22 declare_clippy_lint! {
23 /// **What it does:** Checks for usages of `match` which could be implemented using `map`
25 /// **Why is this bad?** Using the `map` method is clearer and more concise.
27 /// **Known problems:** None.
33 /// Some(x) => Some(x + 1),
39 /// Some(0).map(|x| x + 1);
43 "reimplementation of `map`"
46 declare_lint_pass!(ManualMap => [MANUAL_MAP]);
48 impl LateLintPass<'_> for ManualMap {
49 #[allow(clippy::too_many_lines)]
50 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
51 if let ExprKind::Match(
53 [arm1 @ Arm { guard: None, .. }, arm2 @ Arm { guard: None, .. }],
57 if in_external_macro(cx.sess(), expr.span) || in_constant(cx, expr.hir_id) {
61 let (scrutinee_ty, ty_ref_count, ty_mutability) =
62 peel_mid_ty_refs_is_mutable(cx.typeck_results().expr_ty(scrutinee));
63 if !(is_type_diagnostic_item(cx, scrutinee_ty, sym::option_type)
64 && is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::option_type))
69 let expr_ctxt = expr.span.ctxt();
70 let (some_expr, some_pat, pat_ref_count, is_wild_none) = match (
71 try_parse_pattern(cx, arm1.pat, expr_ctxt),
72 try_parse_pattern(cx, arm2.pat, expr_ctxt),
74 (Some(OptionPat::Wild), Some(OptionPat::Some { pattern, ref_count }))
75 if is_none_expr(cx, arm1.body) =>
77 (arm2.body, pattern, ref_count, true)
79 (Some(OptionPat::None), Some(OptionPat::Some { pattern, ref_count }))
80 if is_none_expr(cx, arm1.body) =>
82 (arm2.body, pattern, ref_count, false)
84 (Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::Wild))
85 if is_none_expr(cx, arm2.body) =>
87 (arm1.body, pattern, ref_count, true)
89 (Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::None))
90 if is_none_expr(cx, arm2.body) =>
92 (arm1.body, pattern, ref_count, false)
97 // Top level or patterns aren't allowed in closures.
98 if matches!(some_pat.kind, PatKind::Or(_)) {
102 let some_expr = match get_some_expr(cx, some_expr, expr_ctxt) {
107 if cx.typeck_results().expr_ty(some_expr) == cx.tcx.types.unit
108 && !is_allowed(cx, OPTION_MAP_UNIT_FN, expr.hir_id)
113 if !can_move_expr_to_closure(cx, some_expr) {
117 // Determine which binding mode to use.
118 let explicit_ref = some_pat.contains_explicit_ref_binding();
119 let binding_ref = explicit_ref.or_else(|| (ty_ref_count != pat_ref_count).then(|| ty_mutability));
121 let as_ref_str = match binding_ref {
122 Some(Mutability::Mut) => ".as_mut()",
123 Some(Mutability::Not) => ".as_ref()",
127 let mut app = Applicability::MachineApplicable;
129 // Remove address-of expressions from the scrutinee. Either `as_ref` will be called, or
130 // it's being passed by value.
131 let scrutinee = peel_hir_expr_refs(scrutinee).0;
132 let (scrutinee_str, _) = snippet_with_context(cx, scrutinee.span, expr_ctxt, "..", &mut app);
134 if scrutinee.span.ctxt() == expr.span.ctxt() && scrutinee.precedence().order() < PREC_POSTFIX {
135 format!("({})", scrutinee_str)
140 let body_str = if let PatKind::Binding(annotation, _, some_binding, None) = some_pat.kind {
141 match can_pass_as_func(cx, some_binding, some_expr) {
142 Some(func) if func.span.ctxt() == some_expr.span.ctxt() => {
143 snippet_with_applicability(cx, func.span, "..", &mut app).into_owned()
146 if match_var(some_expr, some_binding.name)
147 && !is_allowed(cx, MATCH_AS_REF, expr.hir_id)
148 && binding_ref.is_some()
153 // `ref` and `ref mut` annotations were handled earlier.
154 let annotation = if matches!(annotation, BindingAnnotation::Mutable) {
163 snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app).0
167 } else if !is_wild_none && explicit_ref.is_none() {
168 // TODO: handle explicit reference annotations.
171 snippet_with_context(cx, some_pat.span, expr_ctxt, "..", &mut app).0,
172 snippet_with_context(cx, some_expr.span, expr_ctxt, "..", &mut app).0
175 // Refutable bindings and mixed reference annotations can't be handled by `map`.
183 "manual implementation of `Option::map`",
185 if matches!(match_kind, MatchSource::IfLetDesugar { .. }) && is_else_clause(cx.tcx, expr) {
186 format!("{{ {}{}.map({}) }}", scrutinee_str, as_ref_str, body_str)
188 format!("{}{}.map({})", scrutinee_str, as_ref_str, body_str)
196 // Checks if the expression can be moved into a closure as is.
197 fn can_move_expr_to_closure(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
198 struct V<'cx, 'tcx> {
199 cx: &'cx LateContext<'tcx>,
202 impl Visitor<'tcx> for V<'_, 'tcx> {
203 type Map = ErasedMap<'tcx>;
204 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
205 NestedVisitorMap::None
208 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
211 | ExprKind::Continue(_)
213 | ExprKind::Yield(..)
214 | ExprKind::InlineAsm(_)
215 | ExprKind::LlvmInlineAsm(_) => {
216 self.make_closure = false;
218 // Accessing a field of a local value can only be done if the type isn't
220 ExprKind::Field(base_expr, _)
223 ExprKind::Path(QPath::Resolved(_, Path { res: Res::Local(_), .. }))
224 ) && can_partially_move_ty(self.cx, self.cx.typeck_results().expr_ty(base_expr)) =>
226 // TODO: check if the local has been partially moved. Assume it has for now.
227 self.make_closure = false;
236 let mut v = V { cx, make_closure: true };
241 // Checks whether the expression could be passed as a function, or whether a closure is needed.
242 // Returns the function to be passed to `map` if it exists.
243 fn can_pass_as_func(cx: &LateContext<'tcx>, binding: Ident, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
245 ExprKind::Call(func, [arg])
246 if match_var(arg, binding.name) && cx.typeck_results().expr_adjustments(arg).is_empty() =>
258 // The pattern contained in the `Some` tuple.
259 pattern: &'a Pat<'a>,
260 // The number of references before the `Some` tuple.
261 // e.g. `&&Some(_)` has a ref count of 2.
266 // Try to parse into a recognized `Option` pattern.
267 // i.e. `_`, `None`, `Some(..)`, or a reference to any of those.
268 fn try_parse_pattern(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
269 fn f(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ref_count: usize, ctxt: SyntaxContext) -> Option<OptionPat<'tcx>> {
271 PatKind::Wild => Some(OptionPat::Wild),
272 PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1, ctxt),
273 PatKind::Path(ref qpath) if is_lang_ctor(cx, qpath, OptionNone) => Some(OptionPat::None),
274 PatKind::TupleStruct(ref qpath, [pattern], _)
275 if is_lang_ctor(cx, qpath, OptionSome) && pat.span.ctxt() == ctxt =>
277 Some(OptionPat::Some { pattern, ref_count })
285 // Checks for an expression wrapped by the `Some` constructor. Returns the contained expression.
286 fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, ctxt: SyntaxContext) -> Option<&'tcx Expr<'tcx>> {
287 // TODO: Allow more complex expressions.
291 kind: ExprKind::Path(ref qpath),
295 ) if ctxt == expr.span.ctxt() && is_lang_ctor(cx, qpath, OptionSome) => Some(arg),
303 ) => get_some_expr(cx, expr, ctxt),
308 // Checks for the `None` value.
309 fn is_none_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
311 ExprKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
319 ) => is_none_expr(cx, expr),