-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Add single_option_map
lint
#14033
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add single_option_map
lint
#14033
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
use clippy_utils::diagnostics::span_lint_and_help; | ||
use clippy_utils::ty::is_type_diagnostic_item; | ||
use clippy_utils::{path_res, peel_blocks}; | ||
use rustc_hir::def::Res; | ||
use rustc_hir::def_id::LocalDefId; | ||
use rustc_hir::intravisit::FnKind; | ||
use rustc_hir::{Body, ExprKind, FnDecl, FnRetTy}; | ||
use rustc_lint::{LateContext, LateLintPass}; | ||
use rustc_session::declare_lint_pass; | ||
use rustc_span::{Span, sym}; | ||
|
||
declare_clippy_lint! { | ||
/// ### What it does | ||
/// Checks for functions with method calls to `.map(_)` on an arg | ||
/// of type `Option` as the outermost expression. | ||
/// | ||
/// ### Why is this bad? | ||
/// Taking and returning an `Option<T>` may require additional | ||
/// `Some(_)` and `unwrap` if all you have is a `T`. | ||
/// | ||
/// ### Example | ||
/// ```no_run | ||
/// fn double(param: Option<u32>) -> Option<u32> { | ||
/// param.map(|x| x * 2) | ||
/// } | ||
/// ``` | ||
/// Use instead: | ||
/// ```no_run | ||
/// fn double(param: u32) -> u32 { | ||
/// param * 2 | ||
/// } | ||
/// ``` | ||
#[clippy::version = "1.86.0"] | ||
pub SINGLE_OPTION_MAP, | ||
nursery, | ||
"Checks for functions with method calls to `.map(_)` on an arg of type `Option` as the outermost expression." | ||
} | ||
|
||
declare_lint_pass!(SingleOptionMap => [SINGLE_OPTION_MAP]); | ||
|
||
impl<'tcx> LateLintPass<'tcx> for SingleOptionMap { | ||
fn check_fn( | ||
&mut self, | ||
cx: &LateContext<'tcx>, | ||
kind: FnKind<'tcx>, | ||
decl: &'tcx FnDecl<'tcx>, | ||
body: &'tcx Body<'tcx>, | ||
span: Span, | ||
_fn_def: LocalDefId, | ||
) { | ||
if let FnRetTy::Return(_ret) = decl.output | ||
&& matches!(kind, FnKind::ItemFn(_, _, _) | FnKind::Method(_, _)) | ||
{ | ||
let func_body = peel_blocks(body.value); | ||
if let ExprKind::MethodCall(method_name, callee, args, _span) = func_body.kind | ||
&& method_name.ident.name == sym::map | ||
&& let callee_type = cx.typeck_results().expr_ty(callee) | ||
&& is_type_diagnostic_item(cx, callee_type, sym::Option) | ||
&& let ExprKind::Path(_path) = callee.kind | ||
&& let Res::Local(_id) = path_res(cx, callee) | ||
&& matches!(path_res(cx, callee), Res::Local(_id)) | ||
&& !matches!(args[0].kind, ExprKind::Path(_)) | ||
{ | ||
if let ExprKind::Closure(closure) = args[0].kind { | ||
let Body { params: [..], value } = cx.tcx.hir().body(closure.body); | ||
if let ExprKind::Call(func, f_args) = value.kind | ||
&& matches!(func.kind, ExprKind::Path(_)) | ||
&& f_args.iter().all(|arg| matches!(arg.kind, ExprKind::Path(_))) | ||
{ | ||
return; | ||
} else if let ExprKind::MethodCall(_segment, receiver, method_args, _span) = value.kind | ||
&& matches!(receiver.kind, ExprKind::Path(_)) | ||
&& method_args.iter().all(|arg| matches!(arg.kind, ExprKind::Path(_))) | ||
&& method_args.iter().all(|arg| matches!(path_res(cx, arg), Res::Local(_))) | ||
{ | ||
return; | ||
} | ||
} | ||
|
||
span_lint_and_help( | ||
cx, | ||
SINGLE_OPTION_MAP, | ||
span, | ||
"`fn` that only maps over argument", | ||
None, | ||
"move the `.map` to the caller or to an `_opt` function", | ||
); | ||
} | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
#![warn(clippy::single_option_map)] | ||
|
||
yusufraji marked this conversation as resolved.
Show resolved
Hide resolved
|
||
use std::sync::atomic::{AtomicUsize, Ordering}; | ||
|
||
static ATOM: AtomicUsize = AtomicUsize::new(42); | ||
static MAYBE_ATOMIC: Option<&AtomicUsize> = Some(&ATOM); | ||
|
||
fn h(arg: Option<u32>) -> Option<u32> { | ||
yusufraji marked this conversation as resolved.
Show resolved
Hide resolved
|
||
//~^ ERROR: `fn` that only maps over argument | ||
arg.map(|x| x * 2) | ||
llogiq marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
fn j(arg: Option<u64>) -> Option<u64> { | ||
yusufraji marked this conversation as resolved.
Show resolved
Hide resolved
|
||
//~^ ERROR: `fn` that only maps over argument | ||
arg.map(|x| x * 2) | ||
} | ||
|
||
fn mul_args(a: String, b: u64) -> String { | ||
a | ||
} | ||
|
||
fn mul_args_opt(a: Option<String>, b: u64) -> Option<String> { | ||
//~^ ERROR: `fn` that only maps over argument | ||
a.map(|val| mul_args(val, b + 1)) | ||
} | ||
|
||
// No lint: no `Option` argument argument | ||
fn maps_static_option() -> Option<usize> { | ||
yusufraji marked this conversation as resolved.
Show resolved
Hide resolved
|
||
MAYBE_ATOMIC.map(|a| a.load(Ordering::Relaxed)) | ||
} | ||
|
||
// No lint: wrapped by another function | ||
fn manipulate(i: i32) -> i32 { | ||
yusufraji marked this conversation as resolved.
Show resolved
Hide resolved
|
||
i + 1 | ||
} | ||
// No lint: wraps another function to do the optional thing | ||
fn manipulate_opt(opt_i: Option<i32>) -> Option<i32> { | ||
yusufraji marked this conversation as resolved.
Show resolved
Hide resolved
|
||
opt_i.map(manipulate) | ||
} | ||
|
||
// No lint: maps other than the receiver | ||
fn map_not_arg(arg: Option<u32>) -> Option<u32> { | ||
maps_static_option().map(|_| arg.unwrap()) | ||
} | ||
|
||
// No lint: wrapper function with η-expanded form | ||
llogiq marked this conversation as resolved.
Show resolved
Hide resolved
|
||
#[allow(clippy::redundant_closure)] | ||
fn manipulate_opt_explicit(opt_i: Option<i32>) -> Option<i32> { | ||
opt_i.map(|x| manipulate(x)) | ||
} | ||
|
||
// No lint | ||
fn multi_args(a: String, b: bool, c: u64) -> String { | ||
a | ||
} | ||
|
||
// No lint: contains only map of a closure that binds other arguments | ||
fn multi_args_opt(a: Option<String>, b: bool, c: u64) -> Option<String> { | ||
a.map(|a| multi_args(a, b, c)) | ||
} | ||
|
||
fn main() { | ||
let answer = Some(42u32); | ||
let h_result = h(answer); | ||
|
||
let answer = Some(42u64); | ||
let j_result = j(answer); | ||
maps_static_option(); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
error: `fn` that only maps over argument | ||
--> tests/ui/single_option_map.rs:8:1 | ||
| | ||
LL | / fn h(arg: Option<u32>) -> Option<u32> { | ||
LL | | | ||
LL | | arg.map(|x| x * 2) | ||
LL | | } | ||
| |_^ | ||
| | ||
= help: move the `.map` to the caller or to an `_opt` function | ||
= note: `-D clippy::single-option-map` implied by `-D warnings` | ||
= help: to override `-D warnings` add `#[allow(clippy::single_option_map)]` | ||
|
||
error: `fn` that only maps over argument | ||
--> tests/ui/single_option_map.rs:13:1 | ||
| | ||
LL | / fn j(arg: Option<u64>) -> Option<u64> { | ||
LL | | | ||
LL | | arg.map(|x| x * 2) | ||
LL | | } | ||
| |_^ | ||
| | ||
= help: move the `.map` to the caller or to an `_opt` function | ||
|
||
error: `fn` that only maps over argument | ||
--> tests/ui/single_option_map.rs:22:1 | ||
| | ||
LL | / fn mul_args_opt(a: Option<String>, b: u64) -> Option<String> { | ||
LL | | | ||
LL | | a.map(|val| mul_args(val, b + 1)) | ||
LL | | } | ||
| |_^ | ||
| | ||
= help: move the `.map` to the caller or to an `_opt` function | ||
|
||
error: aborting due to 3 previous errors | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.