Skip to content
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

Add single_option_map lint #14033

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6062,6 +6062,7 @@ Released 2018-09-13
[`single_element_loop`]: https://rust-lang.github.io/rust-clippy/master/index.html#single_element_loop
[`single_match`]: https://rust-lang.github.io/rust-clippy/master/index.html#single_match
[`single_match_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#single_match_else
[`single_option_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#single_option_map
[`single_range_in_vec_init`]: https://rust-lang.github.io/rust-clippy/master/index.html#single_range_in_vec_init
[`size_of_in_element_count`]: https://rust-lang.github.io/rust-clippy/master/index.html#size_of_in_element_count
[`size_of_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#size_of_ref
Expand Down
1 change: 1 addition & 0 deletions clippy_lints/src/declared_lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,7 @@ pub static LINTS: &[&crate::LintInfo] = &[
crate::single_call_fn::SINGLE_CALL_FN_INFO,
crate::single_char_lifetime_names::SINGLE_CHAR_LIFETIME_NAMES_INFO,
crate::single_component_path_imports::SINGLE_COMPONENT_PATH_IMPORTS_INFO,
crate::single_option_map::SINGLE_OPTION_MAP_INFO,
crate::single_range_in_vec_init::SINGLE_RANGE_IN_VEC_INIT_INFO,
crate::size_of_in_element_count::SIZE_OF_IN_ELEMENT_COUNT_INFO,
crate::size_of_ref::SIZE_OF_REF_INFO,
Expand Down
2 changes: 2 additions & 0 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,7 @@ mod significant_drop_tightening;
mod single_call_fn;
mod single_char_lifetime_names;
mod single_component_path_imports;
mod single_option_map;
mod single_range_in_vec_init;
mod size_of_in_element_count;
mod size_of_ref;
Expand Down Expand Up @@ -976,5 +977,6 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
store.register_late_pass(|_| Box::new(unneeded_struct_pattern::UnneededStructPattern));
store.register_late_pass(|_| Box::<unnecessary_semicolon::UnnecessarySemicolon>::default());
store.register_late_pass(move |_| Box::new(non_std_lazy_statics::NonStdLazyStatic::new(conf)));
store.register_late_pass(|_| Box::new(single_option_map::SingleOptionMap));
// add lints here, do not remove this comment, it's used in `new_lint`
}
74 changes: 74 additions & 0 deletions clippy_lints/src/single_option_map.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
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
yusufraji marked this conversation as resolved.
Show resolved Hide resolved
&& let Res::Local(_id) = path_res(cx, callee)
&& !matches!(args[0].kind, ExprKind::Path(_))
{
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",
);
}
}
}
}
34 changes: 34 additions & 0 deletions tests/ui/single_option_map.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#![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
arg.map(|x| x * 2)
}

fn j(arg: Option<u64>) -> Option<u64> {
yusufraji marked this conversation as resolved.
Show resolved Hide resolved
arg.map(|x| x * 2)
}

fn maps_static_option() -> Option<usize> {
yusufraji marked this conversation as resolved.
Show resolved Hide resolved
MAYBE_ATOMIC.map(|a| a.load(Ordering::Relaxed))
}

fn manipulate(i: i32) -> i32 {
yusufraji marked this conversation as resolved.
Show resolved Hide resolved
i + 1
}
fn manipulate_opt(opt_i: Option<i32>) -> Option<i32> {
yusufraji marked this conversation as resolved.
Show resolved Hide resolved
opt_i.map(manipulate)
}

fn main() {
let answer = Some(42u32);
let h_result = h(answer);

let answer = Some(42u64);
let j_result = j(answer);
maps_static_option();
}
24 changes: 24 additions & 0 deletions tests/ui/single_option_map.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
error: `fn` that only maps over argument
--> tests/ui/single_option_map.rs:8:1
|
LL | / fn h(arg: Option<u32>) -> Option<u32> {
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:12:1
|
LL | / fn j(arg: Option<u64>) -> Option<u64> {
LL | | arg.map(|x| x * 2)
LL | | }
| |_^
|
= help: move the `.map` to the caller or to an `_opt` function

error: aborting due to 2 previous errors

Loading