Skip to content

Commit 90bc8ff

Browse files
committed
add option_as_ref_deref lint
1 parent c092068 commit 90bc8ff

File tree

9 files changed

+287
-2
lines changed

9 files changed

+287
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1226,6 +1226,7 @@ Released 2018-09-13
12261226
[`ok_expect`]: https://rust-lang.github.io/rust-clippy/master/index.html#ok_expect
12271227
[`op_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#op_ref
12281228
[`option_and_then_some`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_and_then_some
1229+
[`option_as_ref_deref`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_as_ref_deref
12291230
[`option_expect_used`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_expect_used
12301231
[`option_map_or_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_map_or_none
12311232
[`option_map_unit_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_map_unit_fn

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.
88

9-
[There are 345 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
9+
[There are 346 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
1010

1111
We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:
1212

clippy_lints/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -629,6 +629,7 @@ pub fn register_plugins(store: &mut lint::LintStore, sess: &Session, conf: &Conf
629629
&methods::NEW_RET_NO_SELF,
630630
&methods::OK_EXPECT,
631631
&methods::OPTION_AND_THEN_SOME,
632+
&methods::OPTION_AS_REF_DEREF,
632633
&methods::OPTION_EXPECT_USED,
633634
&methods::OPTION_MAP_OR_NONE,
634635
&methods::OPTION_MAP_UNWRAP_OR,
@@ -1210,6 +1211,7 @@ pub fn register_plugins(store: &mut lint::LintStore, sess: &Session, conf: &Conf
12101211
LintId::of(&methods::NEW_RET_NO_SELF),
12111212
LintId::of(&methods::OK_EXPECT),
12121213
LintId::of(&methods::OPTION_AND_THEN_SOME),
1214+
LintId::of(&methods::OPTION_AS_REF_DEREF),
12131215
LintId::of(&methods::OPTION_MAP_OR_NONE),
12141216
LintId::of(&methods::OR_FUN_CALL),
12151217
LintId::of(&methods::SEARCH_IS_SOME),
@@ -1466,6 +1468,7 @@ pub fn register_plugins(store: &mut lint::LintStore, sess: &Session, conf: &Conf
14661468
LintId::of(&methods::FILTER_NEXT),
14671469
LintId::of(&methods::FLAT_MAP_IDENTITY),
14681470
LintId::of(&methods::OPTION_AND_THEN_SOME),
1471+
LintId::of(&methods::OPTION_AS_REF_DEREF),
14691472
LintId::of(&methods::SEARCH_IS_SOME),
14701473
LintId::of(&methods::SUSPICIOUS_MAP),
14711474
LintId::of(&methods::UNNECESSARY_FILTER_MAP),

clippy_lints/src/methods/mod.rs

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1130,6 +1130,27 @@ declare_clippy_lint! {
11301130
"Check for offset calculations on raw pointers to zero-sized types"
11311131
}
11321132

1133+
declare_clippy_lint! {
1134+
/// **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1135+
///
1136+
/// **Why is this bad?** Readability, this can be written more concisely as a
1137+
/// single method call.
1138+
///
1139+
/// **Known problems:** None.
1140+
///
1141+
/// **Example:**
1142+
/// ```rust,ignore
1143+
/// opt.as_ref().map(String::as_str)
1144+
/// ```
1145+
/// Can be written as
1146+
/// ```rust,ignore
1147+
/// opt.as_deref()
1148+
/// ```
1149+
pub OPTION_AS_REF_DEREF,
1150+
complexity,
1151+
"using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1152+
}
1153+
11331154
declare_lint_pass!(Methods => [
11341155
OPTION_UNWRAP_USED,
11351156
RESULT_UNWRAP_USED,
@@ -1177,6 +1198,7 @@ declare_lint_pass!(Methods => [
11771198
UNINIT_ASSUMED_INIT,
11781199
MANUAL_SATURATING_ARITHMETIC,
11791200
ZST_OFFSET,
1201+
OPTION_AS_REF_DEREF,
11801202
]);
11811203

11821204
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods {
@@ -1240,6 +1262,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods {
12401262
["add"] | ["offset"] | ["sub"] | ["wrapping_offset"] | ["wrapping_add"] | ["wrapping_sub"] => {
12411263
check_pointer_offset(cx, expr, arg_lists[0])
12421264
},
1265+
["map", "as_ref"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], false),
1266+
["map", "as_mut"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], true),
12431267
_ => {},
12441268
}
12451269

@@ -2979,6 +3003,77 @@ fn lint_suspicious_map(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
29793003
);
29803004
}
29813005

3006+
/// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
3007+
fn lint_option_as_ref_deref<'a, 'tcx>(
3008+
cx: &LateContext<'a, 'tcx>,
3009+
expr: &hir::Expr<'_>,
3010+
as_ref_args: &[hir::Expr<'_>],
3011+
map_args: &[hir::Expr<'_>],
3012+
is_mut: bool,
3013+
) {
3014+
let option_ty = cx.tables.expr_ty(&as_ref_args[0]);
3015+
if !match_type(cx, option_ty, &paths::OPTION) {
3016+
return;
3017+
}
3018+
3019+
let deref_aliases: [&[&str]; 9] = [
3020+
&paths::DEREF_TRAIT_METHOD,
3021+
&paths::DEREF_MUT_TRAIT_METHOD,
3022+
&paths::CSTRING_AS_C_STR,
3023+
&paths::OS_STRING_AS_OS_STR,
3024+
&paths::PATH_BUF_AS_PATH,
3025+
&paths::STRING_AS_STR,
3026+
&paths::STRING_AS_MUT_STR,
3027+
&paths::VEC_AS_SLICE,
3028+
&paths::VEC_AS_MUT_SLICE,
3029+
];
3030+
3031+
let is_deref = match map_args[1].kind {
3032+
hir::ExprKind::Path(ref expr_qpath) => deref_aliases.iter().any(|path| match_qpath(expr_qpath, path)),
3033+
hir::ExprKind::Closure(_, _, body_id, _, _) => {
3034+
let closure_body = cx.tcx.hir().body(body_id);
3035+
let closure_expr = remove_blocks(&closure_body.value);
3036+
if_chain! {
3037+
if let hir::ExprKind::MethodCall(_, _, args) = &closure_expr.kind;
3038+
if args.len() == 1;
3039+
if let hir::ExprKind::Path(qpath) = &args[0].kind;
3040+
if let hir::def::Res::Local(local_id) = cx.tables.qpath_res(qpath, args[0].hir_id);
3041+
if closure_body.params[0].pat.hir_id == local_id;
3042+
let adj = cx.tables.expr_adjustments(&args[0]).iter().map(|x| &x.kind).collect::<Box<[_]>>();
3043+
if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
3044+
then {
3045+
let method_did = cx.tables.type_dependent_def_id(closure_expr.hir_id).unwrap();
3046+
deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
3047+
} else {
3048+
false
3049+
}
3050+
}
3051+
},
3052+
3053+
_ => false,
3054+
};
3055+
3056+
if is_deref {
3057+
let current_method = if is_mut {
3058+
".as_mut().map(DerefMut::deref_mut)"
3059+
} else {
3060+
".as_ref().map(Deref::deref)"
3061+
};
3062+
let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
3063+
let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint);
3064+
let suggestion = format!("try using {} instead", method_hint);
3065+
3066+
let msg = format!(
3067+
"called `{0}` (or with one of deref aliases) on an Option value. \
3068+
This can be done more directly by calling `{1}` instead",
3069+
current_method, hint
3070+
);
3071+
span_lint_and_then(cx, OPTION_AS_REF_DEREF, expr.span, &msg, |db| {
3072+
db.span_suggestion(expr.span, &suggestion, hint, Applicability::MachineApplicable);
3073+
});
3074+
}
3075+
}
3076+
29823077
/// Given a `Result<T, E>` type, return its error type (`E`).
29833078
fn get_error_type<'a>(cx: &LateContext<'_, '_>, ty: Ty<'a>) -> Option<Ty<'a>> {
29843079
match ty.kind {

clippy_lints/src/utils/paths.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@ pub const CMP_MAX: [&str; 3] = ["core", "cmp", "max"];
1818
pub const CMP_MIN: [&str; 3] = ["core", "cmp", "min"];
1919
pub const COW: [&str; 3] = ["alloc", "borrow", "Cow"];
2020
pub const CSTRING: [&str; 4] = ["std", "ffi", "c_str", "CString"];
21+
pub const CSTRING_AS_C_STR: [&str; 5] = ["std", "ffi", "c_str", "CString", "as_c_str"];
2122
pub const DEFAULT_TRAIT: [&str; 3] = ["core", "default", "Default"];
2223
pub const DEFAULT_TRAIT_METHOD: [&str; 4] = ["core", "default", "Default", "default"];
24+
pub const DEREF_MUT_TRAIT_METHOD: [&str; 5] = ["core", "ops", "deref", "DerefMut", "deref_mut"];
2325
pub const DEREF_TRAIT_METHOD: [&str; 5] = ["core", "ops", "deref", "Deref", "deref"];
2426
pub const DISPLAY_FMT_METHOD: [&str; 4] = ["core", "fmt", "Display", "fmt"];
2527
pub const DOUBLE_ENDED_ITERATOR: [&str; 4] = ["core", "iter", "traits", "DoubleEndedIterator"];
@@ -62,10 +64,12 @@ pub const OPTION_NONE: [&str; 4] = ["core", "option", "Option", "None"];
6264
pub const OPTION_SOME: [&str; 4] = ["core", "option", "Option", "Some"];
6365
pub const ORD: [&str; 3] = ["core", "cmp", "Ord"];
6466
pub const OS_STRING: [&str; 4] = ["std", "ffi", "os_str", "OsString"];
67+
pub const OS_STRING_AS_OS_STR: [&str; 5] = ["std", "ffi", "os_str", "OsString", "as_os_str"];
6568
pub const OS_STR_TO_OS_STRING: [&str; 5] = ["std", "ffi", "os_str", "OsStr", "to_os_string"];
6669
pub const PARTIAL_ORD: [&str; 3] = ["core", "cmp", "PartialOrd"];
6770
pub const PATH: [&str; 3] = ["std", "path", "Path"];
6871
pub const PATH_BUF: [&str; 3] = ["std", "path", "PathBuf"];
72+
pub const PATH_BUF_AS_PATH: [&str; 4] = ["std", "path", "PathBuf", "as_path"];
6973
pub const PATH_TO_PATH_BUF: [&str; 4] = ["std", "path", "Path", "to_path_buf"];
7074
pub const PTR_NULL: [&str; 2] = ["ptr", "null"];
7175
pub const PTR_NULL_MUT: [&str; 2] = ["ptr", "null_mut"];
@@ -104,6 +108,8 @@ pub const STD_CONVERT_IDENTITY: [&str; 3] = ["std", "convert", "identity"];
104108
pub const STD_MEM_TRANSMUTE: [&str; 3] = ["std", "mem", "transmute"];
105109
pub const STD_PTR_NULL: [&str; 3] = ["std", "ptr", "null"];
106110
pub const STRING: [&str; 3] = ["alloc", "string", "String"];
111+
pub const STRING_AS_MUT_STR: [&str; 4] = ["alloc", "string", "String", "as_mut_str"];
112+
pub const STRING_AS_STR: [&str; 4] = ["alloc", "string", "String", "as_str"];
107113
pub const SYNTAX_CONTEXT: [&str; 3] = ["rustc_span", "hygiene", "SyntaxContext"];
108114
pub const TO_OWNED: [&str; 3] = ["alloc", "borrow", "ToOwned"];
109115
pub const TO_OWNED_METHOD: [&str; 4] = ["alloc", "borrow", "ToOwned", "to_owned"];
@@ -113,6 +119,8 @@ pub const TRANSMUTE: [&str; 4] = ["core", "intrinsics", "", "transmute"];
113119
pub const TRY_FROM_ERROR: [&str; 4] = ["std", "ops", "Try", "from_error"];
114120
pub const TRY_INTO_RESULT: [&str; 4] = ["std", "ops", "Try", "into_result"];
115121
pub const VEC: [&str; 3] = ["alloc", "vec", "Vec"];
122+
pub const VEC_AS_MUT_SLICE: [&str; 4] = ["alloc", "vec", "Vec", "as_mut_slice"];
123+
pub const VEC_AS_SLICE: [&str; 4] = ["alloc", "vec", "Vec", "as_slice"];
116124
pub const VEC_DEQUE: [&str; 4] = ["alloc", "collections", "vec_deque", "VecDeque"];
117125
pub const VEC_FROM_ELEM: [&str; 3] = ["alloc", "vec", "from_elem"];
118126
pub const WEAK_ARC: [&str; 3] = ["alloc", "sync", "Weak"];

src/lintlist/mod.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ pub use lint::Lint;
66
pub use lint::LINT_LEVELS;
77

88
// begin lint list, do not remove this comment, it’s used in `update_lints`
9-
pub const ALL_LINTS: [Lint; 345] = [
9+
pub const ALL_LINTS: [Lint; 346] = [
1010
Lint {
1111
name: "absurd_extreme_comparisons",
1212
group: "correctness",
@@ -1463,6 +1463,13 @@ pub const ALL_LINTS: [Lint; 345] = [
14631463
deprecation: None,
14641464
module: "methods",
14651465
},
1466+
Lint {
1467+
name: "option_as_ref_deref",
1468+
group: "complexity",
1469+
desc: "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`",
1470+
deprecation: None,
1471+
module: "methods",
1472+
},
14661473
Lint {
14671474
name: "option_expect_used",
14681475
group: "restriction",

tests/ui/option_as_ref_deref.fixed

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// run-rustfix
2+
3+
#![allow(unused_imports, clippy::redundant_clone)]
4+
#![warn(clippy::option_as_ref_deref)]
5+
6+
use std::ffi::{CString, OsString};
7+
use std::ops::{Deref, DerefMut};
8+
use std::path::PathBuf;
9+
10+
fn main() {
11+
let mut opt = Some(String::from("123"));
12+
13+
let _ = opt.clone().as_deref().map(str::len);
14+
15+
#[rustfmt::skip]
16+
let _ = opt.clone().as_deref()
17+
.map(str::len);
18+
19+
let _ = opt.as_deref_mut();
20+
21+
let _ = opt.as_deref();
22+
let _ = opt.as_deref();
23+
let _ = opt.as_deref_mut();
24+
let _ = opt.as_deref_mut();
25+
let _ = Some(CString::new(vec![]).unwrap()).as_deref();
26+
let _ = Some(OsString::new()).as_deref();
27+
let _ = Some(PathBuf::new()).as_deref();
28+
let _ = Some(Vec::<()>::new()).as_deref();
29+
let _ = Some(Vec::<()>::new()).as_deref_mut();
30+
31+
let _ = opt.as_deref();
32+
let _ = opt.clone().as_deref_mut().map(|x| x.len());
33+
34+
let vc = vec![String::new()];
35+
let _ = Some(1_usize).as_ref().map(|x| vc[*x].as_str()); // should not be linted
36+
37+
let _: Option<&str> = Some(&String::new()).as_ref().map(|x| x.as_str()); // should not be linted
38+
}

tests/ui/option_as_ref_deref.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// run-rustfix
2+
3+
#![allow(unused_imports, clippy::redundant_clone)]
4+
#![warn(clippy::option_as_ref_deref)]
5+
6+
use std::ffi::{CString, OsString};
7+
use std::ops::{Deref, DerefMut};
8+
use std::path::PathBuf;
9+
10+
fn main() {
11+
let mut opt = Some(String::from("123"));
12+
13+
let _ = opt.clone().as_ref().map(Deref::deref).map(str::len);
14+
15+
#[rustfmt::skip]
16+
let _ = opt.clone()
17+
.as_ref().map(
18+
Deref::deref
19+
)
20+
.map(str::len);
21+
22+
let _ = opt.as_mut().map(DerefMut::deref_mut);
23+
24+
let _ = opt.as_ref().map(String::as_str);
25+
let _ = opt.as_ref().map(|x| x.as_str());
26+
let _ = opt.as_mut().map(String::as_mut_str);
27+
let _ = opt.as_mut().map(|x| x.as_mut_str());
28+
let _ = Some(CString::new(vec![]).unwrap()).as_ref().map(CString::as_c_str);
29+
let _ = Some(OsString::new()).as_ref().map(OsString::as_os_str);
30+
let _ = Some(PathBuf::new()).as_ref().map(PathBuf::as_path);
31+
let _ = Some(Vec::<()>::new()).as_ref().map(Vec::as_slice);
32+
let _ = Some(Vec::<()>::new()).as_mut().map(Vec::as_mut_slice);
33+
34+
let _ = opt.as_ref().map(|x| x.deref());
35+
let _ = opt.clone().as_mut().map(|x| x.deref_mut()).map(|x| x.len());
36+
37+
let vc = vec![String::new()];
38+
let _ = Some(1_usize).as_ref().map(|x| vc[*x].as_str()); // should not be linted
39+
40+
let _: Option<&str> = Some(&String::new()).as_ref().map(|x| x.as_str()); // should not be linted
41+
}

0 commit comments

Comments
 (0)