2 map_unit_fn::OPTION_MAP_UNIT_FN,
5 can_partially_move_ty, is_allowed, is_type_diagnostic_item, match_def_path, match_var, paths,
6 peel_hir_expr_refs, peel_mid_ty_refs_is_mutable, snippet_with_applicability, span_lint_and_sugg,
9 use rustc_ast::util::parser::PREC_POSTFIX;
10 use rustc_errors::Applicability;
13 intravisit::{walk_expr, ErasedMap, NestedVisitorMap, Visitor},
14 Arm, BindingAnnotation, Block, Expr, ExprKind, Mutability, Pat, PatKind, Path, QPath,
16 use rustc_lint::{LateContext, LateLintPass, LintContext};
17 use rustc_middle::lint::in_external_macro;
18 use rustc_session::{declare_lint_pass, declare_tool_lint};
19 use rustc_span::symbol::{sym, Ident};
21 declare_clippy_lint! {
22 /// **What it does:** Checks for usages of `match` which could be implemented using `map`
24 /// **Why is this bad?** Using the `map` method is clearer and more concise.
26 /// **Known problems:** `map` is not capable of representing some control flow which works fine in `match`.
32 /// Some(x) => Some(x + 1),
38 /// Some(0).map(|x| x + 1);
42 "reimplementation of `map`"
45 declare_lint_pass!(ManualMap => [MANUAL_MAP]);
47 impl LateLintPass<'_> for ManualMap {
48 #[allow(clippy::too_many_lines)]
49 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
50 if in_external_macro(cx.sess(), expr.span) {
54 if let ExprKind::Match(scrutinee, [arm1 @ Arm { guard: None, .. }, arm2 @ Arm { guard: None, .. }], _) =
57 let (scrutinee_ty, ty_ref_count, ty_mutability) =
58 peel_mid_ty_refs_is_mutable(cx.typeck_results().expr_ty(scrutinee));
59 if !is_type_diagnostic_item(cx, scrutinee_ty, sym::option_type)
60 || !is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym::option_type)
65 let (some_expr, some_pat, pat_ref_count, is_wild_none) =
66 match (try_parse_pattern(cx, arm1.pat), try_parse_pattern(cx, arm2.pat)) {
67 (Some(OptionPat::Wild), Some(OptionPat::Some { pattern, ref_count }))
68 if is_none_expr(cx, arm1.body) =>
70 (arm2.body, pattern, ref_count, true)
72 (Some(OptionPat::None), Some(OptionPat::Some { pattern, ref_count }))
73 if is_none_expr(cx, arm1.body) =>
75 (arm2.body, pattern, ref_count, false)
77 (Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::Wild))
78 if is_none_expr(cx, arm2.body) =>
80 (arm1.body, pattern, ref_count, true)
82 (Some(OptionPat::Some { pattern, ref_count }), Some(OptionPat::None))
83 if is_none_expr(cx, arm2.body) =>
85 (arm1.body, pattern, ref_count, false)
90 // Top level or patterns aren't allowed in closures.
91 if matches!(some_pat.kind, PatKind::Or(_)) {
95 let some_expr = match get_some_expr(cx, some_expr) {
100 if cx.typeck_results().expr_ty(some_expr) == cx.tcx.types.unit
101 && !is_allowed(cx, OPTION_MAP_UNIT_FN, expr.hir_id)
106 if !can_move_expr_to_closure(cx, some_expr) {
110 // Determine which binding mode to use.
111 let explicit_ref = some_pat.contains_explicit_ref_binding();
112 let binding_ref = explicit_ref.or_else(|| (ty_ref_count != pat_ref_count).then(|| ty_mutability));
114 let as_ref_str = match binding_ref {
115 Some(Mutability::Mut) => ".as_mut()",
116 Some(Mutability::Not) => ".as_ref()",
120 let mut app = Applicability::MachineApplicable;
122 // Remove address-of expressions from the scrutinee. `as_ref` will be called,
123 // the type is copyable, or the option is being passed by value.
124 let scrutinee = peel_hir_expr_refs(scrutinee).0;
125 let scrutinee_str = snippet_with_applicability(cx, scrutinee.span, "_", &mut app);
126 let scrutinee_str = if expr.precedence().order() < PREC_POSTFIX {
127 // Parens are needed to chain method calls.
128 format!("({})", scrutinee_str)
133 let body_str = if let PatKind::Binding(annotation, _, some_binding, None) = some_pat.kind {
134 if let Some(func) = can_pass_as_func(cx, some_binding, some_expr) {
135 snippet_with_applicability(cx, func.span, "..", &mut app).into_owned()
137 if match_var(some_expr, some_binding.name)
138 && !is_allowed(cx, MATCH_AS_REF, expr.hir_id)
139 && binding_ref.is_some()
144 // `ref` and `ref mut` annotations were handled earlier.
145 let annotation = if matches!(annotation, BindingAnnotation::Mutable) {
154 snippet_with_applicability(cx, some_expr.span, "..", &mut app)
157 } else if !is_wild_none && explicit_ref.is_none() {
158 // TODO: handle explicit reference annotations.
161 snippet_with_applicability(cx, some_pat.span, "..", &mut app),
162 snippet_with_applicability(cx, some_expr.span, "..", &mut app)
165 // Refutable bindings and mixed reference annotations can't be handled by `map`.
173 "manual implementation of `Option::map`",
175 format!("{}{}.map({})", scrutinee_str, as_ref_str, body_str),
182 // Checks if the expression can be moved into a closure as is.
183 fn can_move_expr_to_closure(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
184 struct V<'cx, 'tcx> {
185 cx: &'cx LateContext<'tcx>,
188 impl Visitor<'tcx> for V<'_, 'tcx> {
189 type Map = ErasedMap<'tcx>;
190 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
191 NestedVisitorMap::None
194 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
196 ExprKind::Break(..) | ExprKind::Continue(_) | ExprKind::Ret(_) => {
197 self.make_closure = false;
199 // Accessing a field of a local value can only be done if the type isn't
201 ExprKind::Field(base_expr, _)
204 ExprKind::Path(QPath::Resolved(_, Path { res: Res::Local(_), .. }))
205 ) && can_partially_move_ty(self.cx, self.cx.typeck_results().expr_ty(base_expr)) =>
207 // TODO: check if the local has been partially moved. Assume it has for now.
208 self.make_closure = false;
217 let mut v = V { cx, make_closure: true };
222 // Checks whether the expression could be passed as a function, or whether a closure is needed.
223 // Returns the function to be passed to `map` if it exists.
224 fn can_pass_as_func(cx: &LateContext<'tcx>, binding: Ident, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
226 ExprKind::Call(func, [arg])
227 if match_var(arg, binding.name) && cx.typeck_results().expr_adjustments(arg).is_empty() =>
239 // The pattern contained in the `Some` tuple.
240 pattern: &'a Pat<'a>,
241 // The number of references before the `Some` tuple.
242 // e.g. `&&Some(_)` has a ref count of 2.
247 // Try to parse into a recognized `Option` pattern.
248 // i.e. `_`, `None`, `Some(..)`, or a reference to any of those.
249 fn try_parse_pattern(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>) -> Option<OptionPat<'tcx>> {
250 fn f(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, ref_count: usize) -> Option<OptionPat<'tcx>> {
252 PatKind::Wild => Some(OptionPat::Wild),
253 PatKind::Ref(pat, _) => f(cx, pat, ref_count + 1),
254 PatKind::Path(QPath::Resolved(None, path))
258 .map_or(false, |id| match_def_path(cx, id, &paths::OPTION_NONE)) =>
260 Some(OptionPat::None)
262 PatKind::TupleStruct(QPath::Resolved(None, path), [pattern], _)
266 .map_or(false, |id| match_def_path(cx, id, &paths::OPTION_SOME)) =>
268 Some(OptionPat::Some { pattern, ref_count })
276 // Checks for an expression wrapped by the `Some` constructor. Returns the contained expression.
277 fn get_some_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
278 // TODO: Allow more complex expressions.
282 kind: ExprKind::Path(QPath::Resolved(None, path)),
287 if match_def_path(cx, path.res.opt_def_id()?, &paths::OPTION_SOME) {
300 ) => get_some_expr(cx, expr),
305 // Checks for the `None` value.
306 fn is_none_expr(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
308 ExprKind::Path(QPath::Resolved(None, path)) => path
311 .map_or(false, |id| match_def_path(cx, id, &paths::OPTION_NONE)),
319 ) => is_none_expr(cx, expr),