|
| 1 | +use clippy_utils::diagnostics::span_lint; |
| 2 | +use clippy_utils::peel_blocks; |
| 3 | +use clippy_utils::ty::is_type_diagnostic_item; |
| 4 | +use rustc_hir::def_id::LocalDefId; |
| 5 | +use rustc_hir::intravisit::FnKind; |
| 6 | +use rustc_hir::{Body, ExprKind, FnDecl, FnRetTy}; |
| 7 | +use rustc_lint::{LateContext, LateLintPass}; |
| 8 | +use rustc_session::declare_lint_pass; |
| 9 | +use rustc_span::{Span, sym}; |
| 10 | + |
| 11 | +declare_clippy_lint! { |
| 12 | + /// ### What it does |
| 13 | + /// Checks for functions with method calls to `.map(_)` on an arg |
| 14 | + /// of type `Option` as the outermost expression. |
| 15 | + /// |
| 16 | + /// ### Why is this bad? |
| 17 | + /// Taking and returning an `Option<T>` may require additional |
| 18 | + /// `Some(_)` and `unwrap` if all you have is a `T` |
| 19 | + /// |
| 20 | + /// ### Example |
| 21 | + /// ```no_run |
| 22 | + /// fn double(param: Option<u32>) -> Option<u32> { |
| 23 | + /// param.map(|x| x * 2) |
| 24 | + /// } |
| 25 | + /// ``` |
| 26 | + /// Use instead: |
| 27 | + /// ```no_run |
| 28 | + /// fn double(param: u32) -> u32 { |
| 29 | + /// param * 2 |
| 30 | + /// } |
| 31 | + /// ``` |
| 32 | + #[clippy::version = "1.86.0"] |
| 33 | + pub SINGLE_OPTION_MAP, |
| 34 | + nursery, |
| 35 | + "Checks for functions with method calls to `.map(_)` on an arg of type `Option` as the outermost expression." |
| 36 | +} |
| 37 | + |
| 38 | +declare_lint_pass!(SingleOptionMap => [SINGLE_OPTION_MAP]); |
| 39 | + |
| 40 | +impl<'tcx> LateLintPass<'tcx> for SingleOptionMap { |
| 41 | + fn check_fn( |
| 42 | + &mut self, |
| 43 | + cx: &LateContext<'tcx>, |
| 44 | + kind: FnKind<'tcx>, |
| 45 | + decl: &'tcx FnDecl<'tcx>, |
| 46 | + body: &'tcx Body<'tcx>, |
| 47 | + span: Span, |
| 48 | + _fn_def: LocalDefId, |
| 49 | + ) { |
| 50 | + if let FnRetTy::Return(_ret) = decl.output |
| 51 | + && matches!(kind, FnKind::ItemFn(_, _, _) | FnKind::Method(_, _)) |
| 52 | + { |
| 53 | + let func_body = peel_blocks(body.value); |
| 54 | + if let ExprKind::MethodCall(method_name, callee, _args, _span) = func_body.kind |
| 55 | + && method_name.ident.name == sym::map |
| 56 | + && let callee_type = cx.typeck_results().expr_ty(callee) |
| 57 | + && is_type_diagnostic_item(cx, callee_type, sym::Option) |
| 58 | + { |
| 59 | + span_lint( |
| 60 | + cx, |
| 61 | + SINGLE_OPTION_MAP, |
| 62 | + span, |
| 63 | + "mapping over single function argument of `Option<T>`, to return `Option<T>`, can be best expressed by applying the map outside of the function.", |
| 64 | + ); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments