Skip to content

Commit 11ef047

Browse files
committed
Add unwrap_or_else_default lint
This will catch `unwrap_or_else(Default::default)` on Result and Option and suggest `unwrap_or_default()` instead.
1 parent f6a5889 commit 11ef047

13 files changed

+356
-31
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2999,6 +2999,7 @@ Released 2018-09-13
29992999
[`unused_unit`]: https://rust-lang.github.io/rust-clippy/master/index.html#unused_unit
30003000
[`unusual_byte_groupings`]: https://rust-lang.github.io/rust-clippy/master/index.html#unusual_byte_groupings
30013001
[`unwrap_in_result`]: https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_in_result
3002+
[`unwrap_or_else_default`]: https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_or_else_default
30023003
[`unwrap_used`]: https://rust-lang.github.io/rust-clippy/master/index.html#unwrap_used
30033004
[`upper_case_acronyms`]: https://rust-lang.github.io/rust-clippy/master/index.html#upper_case_acronyms
30043005
[`use_debug`]: https://rust-lang.github.io/rust-clippy/master/index.html#use_debug

clippy_lints/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -797,6 +797,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
797797
methods::UNNECESSARY_FILTER_MAP,
798798
methods::UNNECESSARY_FOLD,
799799
methods::UNNECESSARY_LAZY_EVALUATIONS,
800+
methods::UNWRAP_OR_ELSE_DEFAULT,
800801
methods::UNWRAP_USED,
801802
methods::USELESS_ASREF,
802803
methods::WRONG_SELF_CONVENTION,
@@ -1341,6 +1342,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
13411342
LintId::of(methods::UNNECESSARY_FILTER_MAP),
13421343
LintId::of(methods::UNNECESSARY_FOLD),
13431344
LintId::of(methods::UNNECESSARY_LAZY_EVALUATIONS),
1345+
LintId::of(methods::UNWRAP_OR_ELSE_DEFAULT),
13441346
LintId::of(methods::USELESS_ASREF),
13451347
LintId::of(methods::WRONG_SELF_CONVENTION),
13461348
LintId::of(methods::ZST_OFFSET),
@@ -1535,6 +1537,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
15351537
LintId::of(methods::STRING_EXTEND_CHARS),
15361538
LintId::of(methods::UNNECESSARY_FOLD),
15371539
LintId::of(methods::UNNECESSARY_LAZY_EVALUATIONS),
1540+
LintId::of(methods::UNWRAP_OR_ELSE_DEFAULT),
15381541
LintId::of(methods::WRONG_SELF_CONVENTION),
15391542
LintId::of(misc::TOPLEVEL_REF_ARG),
15401543
LintId::of(misc::ZERO_PTR),

clippy_lints/src/methods/mod.rs

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ mod uninit_assumed_init;
5656
mod unnecessary_filter_map;
5757
mod unnecessary_fold;
5858
mod unnecessary_lazy_eval;
59+
mod unwrap_or_else_default;
5960
mod unwrap_used;
6061
mod useless_asref;
6162
mod utils;
@@ -310,6 +311,31 @@ declare_clippy_lint! {
310311
"using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result"
311312
}
312313

314+
declare_clippy_lint! {
315+
/// ### What it does
316+
/// Checks for usages of `_.unwrap_or_else(Default::default)` on Option and
317+
/// Result values.
318+
///
319+
/// ### Why is this bad?
320+
/// Readability, these can be written as `option.unwrap_or_default` or
321+
/// `result.unwrap_or_default`.
322+
///
323+
/// ### Examples
324+
/// ```rust
325+
/// # let x = Some(1);
326+
///
327+
/// // Bad
328+
/// x.unwrap_or_else(Default::default);
329+
/// x.unwrap_or_else(u32::default);
330+
///
331+
/// // Good
332+
/// x.unwrap_or_default();
333+
/// ```
334+
pub UNWRAP_OR_ELSE_DEFAULT,
335+
style,
336+
"using `.unwrap_or_else(Default::default)`, which is more succinctly expressed as `.unwrap_or_default()`"
337+
}
338+
313339
declare_clippy_lint! {
314340
/// ### What it does
315341
/// Checks for usage of `option.map(_).unwrap_or(_)` or `option.map(_).unwrap_or_else(_)` or
@@ -1766,6 +1792,7 @@ impl_lint_pass!(Methods => [
17661792
SHOULD_IMPLEMENT_TRAIT,
17671793
WRONG_SELF_CONVENTION,
17681794
OK_EXPECT,
1795+
UNWRAP_OR_ELSE_DEFAULT,
17691796
MAP_UNWRAP_OR,
17701797
RESULT_MAP_OR_INTO_OPTION,
17711798
OPTION_MAP_OR_NONE,
@@ -2172,7 +2199,10 @@ fn check_methods<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, msrv: Optio
21722199
},
21732200
("unwrap_or_else", [u_arg]) => match method_call!(recv) {
21742201
Some(("map", [recv, map_arg], _)) if map_unwrap_or::check(cx, expr, recv, map_arg, u_arg, msrv) => {},
2175-
_ => unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or"),
2202+
_ => {
2203+
unwrap_or_else_default::check(cx, expr, recv, u_arg);
2204+
unnecessary_lazy_eval::check(cx, expr, recv, u_arg, "unwrap_or");
2205+
},
21762206
},
21772207
_ => {},
21782208
}

clippy_lints/src/methods/or_fun_call.rs

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
use clippy_utils::diagnostics::span_lint_and_sugg;
22
use clippy_utils::eager_or_lazy::is_lazyness_candidate;
33
use clippy_utils::source::{snippet, snippet_with_applicability, snippet_with_macro_callsite};
4-
use clippy_utils::ty::{implements_trait, is_type_diagnostic_item, match_type};
4+
use clippy_utils::ty::{implements_trait, qpath_target_trait};
5+
use clippy_utils::ty::{is_type_diagnostic_item, match_type};
56
use clippy_utils::{contains_return, last_path_segment, paths};
67
use if_chain::if_chain;
78
use rustc_errors::Applicability;
@@ -34,15 +35,25 @@ pub(super) fn check<'tcx>(
3435
or_has_args: bool,
3536
span: Span,
3637
) -> bool {
38+
let is_default_default = |qpath, default_trait_id| {
39+
qpath_target_trait(cx, qpath, fun.hir_id).map_or(false, |target_trait| target_trait == default_trait_id)
40+
};
41+
42+
let implements_default = |arg, default_trait_id| {
43+
let arg_ty = cx.typeck_results().expr_ty(arg);
44+
implements_trait(cx, arg_ty, default_trait_id, &[])
45+
};
46+
3747
if_chain! {
3848
if !or_has_args;
3949
if name == "unwrap_or";
4050
if let hir::ExprKind::Path(ref qpath) = fun.kind;
41-
let path = last_path_segment(qpath).ident.name;
42-
if matches!(path, kw::Default | sym::new);
43-
let arg_ty = cx.typeck_results().expr_ty(arg);
4451
if let Some(default_trait_id) = cx.tcx.get_diagnostic_item(sym::Default);
45-
if implements_trait(cx, arg_ty, default_trait_id, &[]);
52+
let path = last_path_segment(qpath).ident.name;
53+
// needs to target Default::default in particular or be *::new and have a Default impl
54+
// available
55+
if (matches!(path, kw::Default) && is_default_default(qpath, default_trait_id))
56+
|| (matches!(path, sym::new) && implements_default(arg, default_trait_id));
4657

4758
then {
4859
let mut applicability = Applicability::MachineApplicable;
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
//! Lint for `some_result_or_option.unwrap_or_else(Default::default)`
2+
3+
use super::UNWRAP_OR_ELSE_DEFAULT;
4+
use clippy_utils::{
5+
diagnostics::span_lint_and_sugg,
6+
source::snippet_with_applicability,
7+
ty::{is_type_diagnostic_item, qpath_target_trait},
8+
};
9+
use rustc_errors::Applicability;
10+
use rustc_hir as hir;
11+
use rustc_lint::LateContext;
12+
use rustc_span::sym;
13+
14+
pub(super) fn check<'tcx>(
15+
cx: &LateContext<'tcx>,
16+
expr: &'tcx hir::Expr<'_>,
17+
recv: &'tcx hir::Expr<'_>,
18+
u_arg: &'tcx hir::Expr<'_>,
19+
) {
20+
// something.unwrap_or_else(Default::default)
21+
// ^^^^^^^^^- recv ^^^^^^^^^^^^^^^^- u_arg
22+
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- expr
23+
let recv_ty = cx.typeck_results().expr_ty(recv);
24+
let is_option = is_type_diagnostic_item(cx, recv_ty, sym::option_type);
25+
let is_result = is_type_diagnostic_item(cx, recv_ty, sym::result_type);
26+
27+
if_chain! {
28+
if is_option || is_result;
29+
if let hir::ExprKind::Path(ref qpath) = u_arg.kind;
30+
if let Some(default_trait_id) = cx.tcx.get_diagnostic_item(sym::Default);
31+
if let Some(target_trait) = qpath_target_trait(cx, qpath, u_arg.hir_id);
32+
if target_trait == default_trait_id;
33+
then {
34+
let mut applicability = Applicability::MachineApplicable;
35+
36+
span_lint_and_sugg(
37+
cx,
38+
UNWRAP_OR_ELSE_DEFAULT,
39+
expr.span,
40+
"use of `.unwrap_or_else(..)` to construct default value",
41+
"try",
42+
format!(
43+
"{}.unwrap_or_default()",
44+
snippet_with_applicability(cx, recv.span, "..", &mut applicability)
45+
),
46+
applicability,
47+
);
48+
}
49+
}
50+
}

clippy_utils/src/source.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<
168168
snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
169169
}
170170

171-
/// Same as `snippet`, but it adapts the applicability level by following rules:
171+
/// Same as [`snippet`], but it adapts the applicability level by following rules:
172172
///
173173
/// - Applicability level `Unspecified` will never be changed.
174174
/// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.

clippy_utils/src/ty.rs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
33
#![allow(clippy::module_name_repetitions)]
44

5+
use hir::{HirId, QPath};
56
use rustc_ast::ast::Mutability;
67
use rustc_data_structures::fx::FxHashMap;
78
use rustc_hir as hir;
@@ -114,7 +115,7 @@ pub fn has_iter_method(cx: &LateContext<'_>, probably_ref_ty: Ty<'_>) -> Option<
114115

115116
/// Checks whether a type implements a trait.
116117
/// The function returns false in case the type contains an inference variable.
117-
/// See also `get_trait_def_id`.
118+
/// See also [`get_trait_def_id`].
118119
pub fn implements_trait<'tcx>(
119120
cx: &LateContext<'tcx>,
120121
ty: Ty<'tcx>,
@@ -136,6 +137,21 @@ pub fn implements_trait<'tcx>(
136137
})
137138
}
138139

140+
/// Gets the trait that a path targets. For example `<SomeTy as Trait>::a` would return the
141+
/// [`DefId`] for `Trait`.
142+
///
143+
/// `cx` must be in a body.
144+
pub fn qpath_target_trait<'tcx>(cx: &LateContext<'tcx>, qpath: &QPath<'_>, expr_id: HirId) -> Option<DefId> {
145+
let method_res = cx.typeck_results().qpath_res(qpath, expr_id);
146+
let method_id = match method_res {
147+
hir::def::Res::Def(_kind, id) => Some(id),
148+
_ => None,
149+
};
150+
let method_id = method_id?;
151+
152+
cx.tcx.trait_of_item(method_id)
153+
}
154+
139155
/// Checks whether this type implements `Drop`.
140156
pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
141157
match ty.ty_adt_def() {

tests/ui/or_fun_call.fixed

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,19 @@ fn or_fun_call() {
1818
}
1919
}
2020

21+
struct FakeDefault;
22+
impl FakeDefault {
23+
fn default() -> Self {
24+
FakeDefault
25+
}
26+
}
27+
28+
impl Default for FakeDefault {
29+
fn default() -> Self {
30+
FakeDefault
31+
}
32+
}
33+
2134
enum Enum {
2235
A(i32),
2336
}
@@ -53,6 +66,12 @@ fn or_fun_call() {
5366
let with_default_type = Some(1);
5467
with_default_type.unwrap_or_default();
5568

69+
let self_default = None::<FakeDefault>;
70+
self_default.unwrap_or_else(<FakeDefault>::default);
71+
72+
let real_default = None::<FakeDefault>;
73+
real_default.unwrap_or_default();
74+
5675
let with_vec = Some(vec![1]);
5776
with_vec.unwrap_or_default();
5877

tests/ui/or_fun_call.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,19 @@ fn or_fun_call() {
1818
}
1919
}
2020

21+
struct FakeDefault;
22+
impl FakeDefault {
23+
fn default() -> Self {
24+
FakeDefault
25+
}
26+
}
27+
28+
impl Default for FakeDefault {
29+
fn default() -> Self {
30+
FakeDefault
31+
}
32+
}
33+
2134
enum Enum {
2235
A(i32),
2336
}
@@ -53,6 +66,12 @@ fn or_fun_call() {
5366
let with_default_type = Some(1);
5467
with_default_type.unwrap_or(u64::default());
5568

69+
let self_default = None::<FakeDefault>;
70+
self_default.unwrap_or(<FakeDefault>::default());
71+
72+
let real_default = None::<FakeDefault>;
73+
real_default.unwrap_or(<FakeDefault as Default>::default());
74+
5675
let with_vec = Some(vec![1]);
5776
with_vec.unwrap_or(vec![]);
5877

0 commit comments

Comments
 (0)