Skip to content

Commit 6763447

Browse files
committed
Auto merge of rust-lang#4945 - Areredify:as_deref, r=flip1995
add `option_as_ref_deref` lint changelog: add a new lint that lints `option.as_ref().map(Deref::deref)` (and similar calls), which could be expressed more succinctly as `option.as_deref[_mut]()`. Closes rust-lang#4918.
2 parents eff3bc5 + 796958c commit 6763447

File tree

9 files changed

+294
-3
lines changed

9 files changed

+294
-3
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1227,6 +1227,7 @@ Released 2018-09-13
12271227
[`ok_expect`]: https://rust-lang.github.io/rust-clippy/master/index.html#ok_expect
12281228
[`op_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#op_ref
12291229
[`option_and_then_some`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_and_then_some
1230+
[`option_as_ref_deref`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_as_ref_deref
12301231
[`option_expect_used`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_expect_used
12311232
[`option_map_or_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_map_or_none
12321233
[`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 348 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
9+
[There are 349 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
@@ -633,6 +633,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
633633
&methods::NEW_RET_NO_SELF,
634634
&methods::OK_EXPECT,
635635
&methods::OPTION_AND_THEN_SOME,
636+
&methods::OPTION_AS_REF_DEREF,
636637
&methods::OPTION_EXPECT_USED,
637638
&methods::OPTION_MAP_OR_NONE,
638639
&methods::OPTION_MAP_UNWRAP_OR,
@@ -1219,6 +1220,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
12191220
LintId::of(&methods::NEW_RET_NO_SELF),
12201221
LintId::of(&methods::OK_EXPECT),
12211222
LintId::of(&methods::OPTION_AND_THEN_SOME),
1223+
LintId::of(&methods::OPTION_AS_REF_DEREF),
12221224
LintId::of(&methods::OPTION_MAP_OR_NONE),
12231225
LintId::of(&methods::OR_FUN_CALL),
12241226
LintId::of(&methods::SEARCH_IS_SOME),
@@ -1476,6 +1478,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
14761478
LintId::of(&methods::FILTER_NEXT),
14771479
LintId::of(&methods::FLAT_MAP_IDENTITY),
14781480
LintId::of(&methods::OPTION_AND_THEN_SOME),
1481+
LintId::of(&methods::OPTION_AS_REF_DEREF),
14791482
LintId::of(&methods::SEARCH_IS_SOME),
14801483
LintId::of(&methods::SKIP_WHILE_NEXT),
14811484
LintId::of(&methods::SUSPICIOUS_MAP),

clippy_lints/src/methods/mod.rs

Lines changed: 102 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1189,6 +1189,27 @@ declare_clippy_lint! {
11891189
"`FileType::is_file` is not recommended to test for readable file type"
11901190
}
11911191

1192+
declare_clippy_lint! {
1193+
/// **What it does:** Checks for usage of `_.as_ref().map(Deref::deref)` or it's aliases (such as String::as_str).
1194+
///
1195+
/// **Why is this bad?** Readability, this can be written more concisely as a
1196+
/// single method call.
1197+
///
1198+
/// **Known problems:** None.
1199+
///
1200+
/// **Example:**
1201+
/// ```rust,ignore
1202+
/// opt.as_ref().map(String::as_str)
1203+
/// ```
1204+
/// Can be written as
1205+
/// ```rust,ignore
1206+
/// opt.as_deref()
1207+
/// ```
1208+
pub OPTION_AS_REF_DEREF,
1209+
complexity,
1210+
"using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`"
1211+
}
1212+
11921213
declare_lint_pass!(Methods => [
11931214
OPTION_UNWRAP_USED,
11941215
RESULT_UNWRAP_USED,
@@ -1238,10 +1259,11 @@ declare_lint_pass!(Methods => [
12381259
MANUAL_SATURATING_ARITHMETIC,
12391260
ZST_OFFSET,
12401261
FILETYPE_IS_FILE,
1262+
OPTION_AS_REF_DEREF,
12411263
]);
12421264

12431265
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods {
1244-
#[allow(clippy::cognitive_complexity)]
1266+
#[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
12451267
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) {
12461268
if in_macro(expr.span) {
12471269
return;
@@ -1303,6 +1325,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods {
13031325
check_pointer_offset(cx, expr, arg_lists[0])
13041326
},
13051327
["is_file", ..] => lint_filetype_is_file(cx, expr, arg_lists[0]),
1328+
["map", "as_ref"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], false),
1329+
["map", "as_mut"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], true),
13061330
_ => {},
13071331
}
13081332

@@ -3062,6 +3086,83 @@ fn lint_suspicious_map(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) {
30623086
);
30633087
}
30643088

3089+
/// lint use of `_.as_ref().map(Deref::deref)` for `Option`s
3090+
fn lint_option_as_ref_deref<'a, 'tcx>(
3091+
cx: &LateContext<'a, 'tcx>,
3092+
expr: &hir::Expr<'_>,
3093+
as_ref_args: &[hir::Expr<'_>],
3094+
map_args: &[hir::Expr<'_>],
3095+
is_mut: bool,
3096+
) {
3097+
let option_ty = cx.tables.expr_ty(&as_ref_args[0]);
3098+
if !match_type(cx, option_ty, &paths::OPTION) {
3099+
return;
3100+
}
3101+
3102+
let deref_aliases: [&[&str]; 9] = [
3103+
&paths::DEREF_TRAIT_METHOD,
3104+
&paths::DEREF_MUT_TRAIT_METHOD,
3105+
&paths::CSTRING_AS_C_STR,
3106+
&paths::OS_STRING_AS_OS_STR,
3107+
&paths::PATH_BUF_AS_PATH,
3108+
&paths::STRING_AS_STR,
3109+
&paths::STRING_AS_MUT_STR,
3110+
&paths::VEC_AS_SLICE,
3111+
&paths::VEC_AS_MUT_SLICE,
3112+
];
3113+
3114+
let is_deref = match map_args[1].kind {
3115+
hir::ExprKind::Path(ref expr_qpath) => deref_aliases.iter().any(|path| match_qpath(expr_qpath, path)),
3116+
hir::ExprKind::Closure(_, _, body_id, _, _) => {
3117+
let closure_body = cx.tcx.hir().body(body_id);
3118+
let closure_expr = remove_blocks(&closure_body.value);
3119+
if_chain! {
3120+
if let hir::ExprKind::MethodCall(_, _, args) = &closure_expr.kind;
3121+
if args.len() == 1;
3122+
if let hir::ExprKind::Path(qpath) = &args[0].kind;
3123+
if let hir::def::Res::Local(local_id) = cx.tables.qpath_res(qpath, args[0].hir_id);
3124+
if closure_body.params[0].pat.hir_id == local_id;
3125+
let adj = cx.tables.expr_adjustments(&args[0]).iter().map(|x| &x.kind).collect::<Box<[_]>>();
3126+
if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj;
3127+
then {
3128+
let method_did = cx.tables.type_dependent_def_id(closure_expr.hir_id).unwrap();
3129+
deref_aliases.iter().any(|path| match_def_path(cx, method_did, path))
3130+
} else {
3131+
false
3132+
}
3133+
}
3134+
},
3135+
3136+
_ => false,
3137+
};
3138+
3139+
if is_deref {
3140+
let current_method = if is_mut {
3141+
".as_mut().map(DerefMut::deref_mut)"
3142+
} else {
3143+
".as_ref().map(Deref::deref)"
3144+
};
3145+
let method_hint = if is_mut { "as_deref_mut" } else { "as_deref" };
3146+
let hint = format!("{}.{}()", snippet(cx, as_ref_args[0].span, ".."), method_hint);
3147+
let suggestion = format!("try using {} instead", method_hint);
3148+
3149+
let msg = format!(
3150+
"called `{0}` (or with one of deref aliases) on an Option value. \
3151+
This can be done more directly by calling `{1}` instead",
3152+
current_method, hint
3153+
);
3154+
span_lint_and_sugg(
3155+
cx,
3156+
OPTION_AS_REF_DEREF,
3157+
expr.span,
3158+
&msg,
3159+
&suggestion,
3160+
hint,
3161+
Applicability::MachineApplicable,
3162+
);
3163+
}
3164+
}
3165+
30653166
/// Given a `Result<T, E>` type, return its error type (`E`).
30663167
fn get_error_type<'a>(cx: &LateContext<'_, '_>, ty: Ty<'a>) -> Option<Ty<'a>> {
30673168
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"];
@@ -63,10 +65,12 @@ pub const OPTION_NONE: [&str; 4] = ["core", "option", "Option", "None"];
6365
pub const OPTION_SOME: [&str; 4] = ["core", "option", "Option", "Some"];
6466
pub const ORD: [&str; 3] = ["core", "cmp", "Ord"];
6567
pub const OS_STRING: [&str; 4] = ["std", "ffi", "os_str", "OsString"];
68+
pub const OS_STRING_AS_OS_STR: [&str; 5] = ["std", "ffi", "os_str", "OsString", "as_os_str"];
6669
pub const OS_STR_TO_OS_STRING: [&str; 5] = ["std", "ffi", "os_str", "OsStr", "to_os_string"];
6770
pub const PARTIAL_ORD: [&str; 3] = ["core", "cmp", "PartialOrd"];
6871
pub const PATH: [&str; 3] = ["std", "path", "Path"];
6972
pub const PATH_BUF: [&str; 3] = ["std", "path", "PathBuf"];
73+
pub const PATH_BUF_AS_PATH: [&str; 4] = ["std", "path", "PathBuf", "as_path"];
7074
pub const PATH_TO_PATH_BUF: [&str; 4] = ["std", "path", "Path", "to_path_buf"];
7175
pub const PTR_NULL: [&str; 2] = ["ptr", "null"];
7276
pub const PTR_NULL_MUT: [&str; 2] = ["ptr", "null_mut"];
@@ -105,6 +109,8 @@ pub const STD_CONVERT_IDENTITY: [&str; 3] = ["std", "convert", "identity"];
105109
pub const STD_MEM_TRANSMUTE: [&str; 3] = ["std", "mem", "transmute"];
106110
pub const STD_PTR_NULL: [&str; 3] = ["std", "ptr", "null"];
107111
pub const STRING: [&str; 3] = ["alloc", "string", "String"];
112+
pub const STRING_AS_MUT_STR: [&str; 4] = ["alloc", "string", "String", "as_mut_str"];
113+
pub const STRING_AS_STR: [&str; 4] = ["alloc", "string", "String", "as_str"];
108114
pub const SYNTAX_CONTEXT: [&str; 3] = ["rustc_span", "hygiene", "SyntaxContext"];
109115
pub const TO_OWNED: [&str; 3] = ["alloc", "borrow", "ToOwned"];
110116
pub const TO_OWNED_METHOD: [&str; 4] = ["alloc", "borrow", "ToOwned", "to_owned"];
@@ -114,6 +120,8 @@ pub const TRANSMUTE: [&str; 4] = ["core", "intrinsics", "", "transmute"];
114120
pub const TRY_FROM_ERROR: [&str; 4] = ["std", "ops", "Try", "from_error"];
115121
pub const TRY_INTO_RESULT: [&str; 4] = ["std", "ops", "Try", "into_result"];
116122
pub const VEC: [&str; 3] = ["alloc", "vec", "Vec"];
123+
pub const VEC_AS_MUT_SLICE: [&str; 4] = ["alloc", "vec", "Vec", "as_mut_slice"];
124+
pub const VEC_AS_SLICE: [&str; 4] = ["alloc", "vec", "Vec", "as_slice"];
117125
pub const VEC_DEQUE: [&str; 4] = ["alloc", "collections", "vec_deque", "VecDeque"];
118126
pub const VEC_FROM_ELEM: [&str; 3] = ["alloc", "vec", "from_elem"];
119127
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; 348] = [
9+
pub const ALL_LINTS: [Lint; 349] = [
1010
Lint {
1111
name: "absurd_extreme_comparisons",
1212
group: "correctness",
@@ -1470,6 +1470,13 @@ pub const ALL_LINTS: [Lint; 348] = [
14701470
deprecation: None,
14711471
module: "methods",
14721472
},
1473+
Lint {
1474+
name: "option_as_ref_deref",
1475+
group: "complexity",
1476+
desc: "using `as_ref().map(Deref::deref)`, which is more succinctly expressed as `as_deref()`",
1477+
deprecation: None,
1478+
module: "methods",
1479+
},
14731480
Lint {
14741481
name: "option_expect_used",
14751482
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)