Skip to content

Commit a3ea65c

Browse files
committed
Implement new lint
1 parent 3bd9889 commit a3ea65c

File tree

7 files changed

+494
-1
lines changed

7 files changed

+494
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1646,6 +1646,7 @@ Released 2018-09-13
16461646
[`option_map_or_none`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_map_or_none
16471647
[`option_map_unit_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_map_unit_fn
16481648
[`option_option`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_option
1649+
[`option_unwrap_or_else`]: https://rust-lang.github.io/rust-clippy/master/index.html#option_unwrap_or_else
16491650
[`or_fun_call`]: https://rust-lang.github.io/rust-clippy/master/index.html#or_fun_call
16501651
[`out_of_bounds_indexing`]: https://rust-lang.github.io/rust-clippy/master/index.html#out_of_bounds_indexing
16511652
[`overflow_check_conditional`]: https://rust-lang.github.io/rust-clippy/master/index.html#overflow_check_conditional

clippy_lints/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -672,6 +672,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
672672
&methods::OK_EXPECT,
673673
&methods::OPTION_AS_REF_DEREF,
674674
&methods::OPTION_MAP_OR_NONE,
675+
&methods::UNNECESSARY_LAZY_EVALUATION,
675676
&methods::OR_FUN_CALL,
676677
&methods::RESULT_MAP_OR_INTO_OPTION,
677678
&methods::SEARCH_IS_SOME,
@@ -1360,6 +1361,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
13601361
LintId::of(&methods::UNINIT_ASSUMED_INIT),
13611362
LintId::of(&methods::UNNECESSARY_FILTER_MAP),
13621363
LintId::of(&methods::UNNECESSARY_FOLD),
1364+
LintId::of(&methods::UNNECESSARY_LAZY_EVALUATION),
13631365
LintId::of(&methods::USELESS_ASREF),
13641366
LintId::of(&methods::WRONG_SELF_CONVENTION),
13651367
LintId::of(&methods::ZST_OFFSET),
@@ -1610,6 +1612,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
16101612
LintId::of(&methods::FILTER_NEXT),
16111613
LintId::of(&methods::FLAT_MAP_IDENTITY),
16121614
LintId::of(&methods::OPTION_AS_REF_DEREF),
1615+
LintId::of(&methods::UNNECESSARY_LAZY_EVALUATION),
16131616
LintId::of(&methods::SEARCH_IS_SOME),
16141617
LintId::of(&methods::SKIP_WHILE_NEXT),
16151618
LintId::of(&methods::SUSPICIOUS_MAP),

clippy_lints/src/methods/mod.rs

Lines changed: 129 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1329,6 +1329,32 @@ declare_clippy_lint! {
13291329
"`push_str()` used with a single-character string literal as parameter"
13301330
}
13311331

1332+
declare_clippy_lint! {
1333+
/// **What it does:** Looks for unnecessary lazily evaluated closures on `Option` and `Result`.
1334+
///
1335+
/// **Why is this bad?** Using eager evaluation is shorter and simpler in some cases.
1336+
///
1337+
/// **Known problems:** None.
1338+
///
1339+
/// **Example:**
1340+
///
1341+
/// ```rust
1342+
/// // example code where clippy issues a warning
1343+
/// let opt: Option<u32> = None;
1344+
///
1345+
/// opt.unwrap_or_else(|| 42);
1346+
/// ```
1347+
/// Use instead:
1348+
/// ```rust
1349+
/// let opt: Option<u32> = None;
1350+
///
1351+
/// opt.unwrap_or(42);
1352+
/// ```
1353+
pub UNNECESSARY_LAZY_EVALUATION,
1354+
style,
1355+
"using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1356+
}
1357+
13321358
declare_lint_pass!(Methods => [
13331359
UNWRAP_USED,
13341360
EXPECT_USED,
@@ -1378,6 +1404,7 @@ declare_lint_pass!(Methods => [
13781404
ZST_OFFSET,
13791405
FILETYPE_IS_FILE,
13801406
OPTION_AS_REF_DEREF,
1407+
UNNECESSARY_LAZY_EVALUATION,
13811408
]);
13821409

13831410
impl<'tcx> LateLintPass<'tcx> for Methods {
@@ -1398,13 +1425,18 @@ impl<'tcx> LateLintPass<'tcx> for Methods {
13981425
["expect", "ok"] => lint_ok_expect(cx, expr, arg_lists[1]),
13991426
["expect", ..] => lint_expect(cx, expr, arg_lists[0]),
14001427
["unwrap_or", "map"] => option_map_unwrap_or::lint(cx, expr, arg_lists[1], arg_lists[0], method_spans[1]),
1401-
["unwrap_or_else", "map"] => lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0]),
1428+
["unwrap_or_else", "map"] => {
1429+
lint_lazy_eval(cx, expr, arg_lists[0], true, "unwrap_or");
1430+
lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0]);
1431+
},
14021432
["map_or", ..] => lint_map_or_none(cx, expr, arg_lists[0]),
14031433
["and_then", ..] => {
1434+
lint_lazy_eval(cx, expr, arg_lists[0], false, "and");
14041435
bind_instead_of_map::OptionAndThenSome::lint(cx, expr, arg_lists[0]);
14051436
bind_instead_of_map::ResultAndThenOk::lint(cx, expr, arg_lists[0]);
14061437
},
14071438
["or_else", ..] => {
1439+
lint_lazy_eval(cx, expr, arg_lists[0], false, "or");
14081440
bind_instead_of_map::ResultOrElseErrInfo::lint(cx, expr, arg_lists[0]);
14091441
},
14101442
["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
@@ -1448,6 +1480,9 @@ impl<'tcx> LateLintPass<'tcx> for Methods {
14481480
["is_file", ..] => lint_filetype_is_file(cx, expr, arg_lists[0]),
14491481
["map", "as_ref"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], false),
14501482
["map", "as_mut"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], true),
1483+
["unwrap_or_else", ..] => lint_lazy_eval(cx, expr, arg_lists[0], true, "unwrap_or"),
1484+
["get_or_insert_with", ..] => lint_lazy_eval(cx, expr, arg_lists[0], true, "get_or_insert"),
1485+
["ok_or_else", ..] => lint_lazy_eval(cx, expr, arg_lists[0], true, "ok_or"),
14511486
_ => {},
14521487
}
14531488

@@ -2663,6 +2698,99 @@ fn lint_map_flatten<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map
26632698
}
26642699
}
26652700

2701+
/// lint use of `<fn>_else(simple closure)` for `Option`s and `Result`s that can be
2702+
/// replaced with `<fn>(return value of simple closure)`
2703+
fn lint_lazy_eval<'a, 'tcx>(
2704+
cx: &LateContext<'a, 'tcx>,
2705+
expr: &'tcx hir::Expr<'_>,
2706+
args: &'tcx [hir::Expr<'_>],
2707+
allow_variant_calls: bool,
2708+
simplify_using: &str,
2709+
) {
2710+
let is_option = is_type_diagnostic_item(cx, cx.tables.expr_ty(&args[0]), sym!(option_type));
2711+
let is_result = is_type_diagnostic_item(cx, cx.tables.expr_ty(&args[0]), sym!(result_type));
2712+
2713+
if !is_option && !is_result {
2714+
return;
2715+
}
2716+
2717+
// Return true if the expression is an accessor of any of the arguments
2718+
fn expr_uses_argument(expr: &hir::Expr<'_>, params: &[hir::Param<'_>]) -> bool {
2719+
params.iter().any(|arg| {
2720+
if_chain! {
2721+
if let hir::PatKind::Binding(_, _, ident, _) = arg.pat.kind;
2722+
if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = expr.kind;
2723+
if let [p, ..] = path.segments;
2724+
then {
2725+
ident.name == p.ident.name
2726+
} else {
2727+
false
2728+
}
2729+
}
2730+
})
2731+
}
2732+
2733+
fn match_any_qpath(path: &hir::QPath<'_>, paths: &[&[&str]]) -> bool {
2734+
paths.iter().any(|candidate| match_qpath(path, candidate))
2735+
}
2736+
2737+
if let hir::ExprKind::Closure(_, _, eid, _, _) = args[1].kind {
2738+
let body = cx.tcx.hir().body(eid);
2739+
let ex = &body.value;
2740+
let params = &body.params;
2741+
2742+
let simplify = match ex.kind {
2743+
// Closures returning literals can be unconditionally simplified
2744+
hir::ExprKind::Lit(_) => true,
2745+
2746+
// Reading fields can be simplified if the object is not an argument of the closure
2747+
hir::ExprKind::Field(ref object, _) => !expr_uses_argument(object, params),
2748+
2749+
// Paths can be simplified if the root is not the argument, this also covers None
2750+
hir::ExprKind::Path(_) => !expr_uses_argument(ex, params),
2751+
2752+
// Calls to Some, Ok, Err can be considered literals if they don't derive an argument
2753+
hir::ExprKind::Call(ref func, ref args) => if_chain! {
2754+
if allow_variant_calls; // Disable lint when rules conflict with bind_instead_of_map
2755+
if let hir::ExprKind::Path(ref path) = func.kind;
2756+
if match_any_qpath(path, &[&["Some"], &["Ok"], &["Err"]]);
2757+
then {
2758+
!args.iter().any(|arg| expr_uses_argument(arg, params))
2759+
} else {
2760+
false
2761+
}
2762+
},
2763+
2764+
// For anything more complex than the above, a closure is probably the right solution,
2765+
// or the case is handled by an other lint
2766+
_ => false,
2767+
};
2768+
2769+
if simplify {
2770+
let msg = if is_option {
2771+
"unnecessary closure used to substitute value for `Option::None`"
2772+
} else {
2773+
"unnecessary closure used to substitute value for `Result::Err`"
2774+
};
2775+
2776+
span_lint_and_sugg(
2777+
cx,
2778+
UNNECESSARY_LAZY_EVALUATION,
2779+
expr.span,
2780+
msg,
2781+
&format!("Use `{}` instead", simplify_using),
2782+
format!(
2783+
"{0}.{1}({2})",
2784+
snippet(cx, args[0].span, ".."),
2785+
simplify_using,
2786+
snippet(cx, ex.span, ".."),
2787+
),
2788+
Applicability::MachineApplicable,
2789+
);
2790+
}
2791+
}
2792+
}
2793+
26662794
/// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
26672795
fn lint_map_unwrap_or_else<'tcx>(
26682796
cx: &LateContext<'tcx>,

src/lintlist/mod.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2383,6 +2383,13 @@ pub static ref ALL_LINTS: Vec<Lint> = vec![
23832383
deprecation: None,
23842384
module: "methods",
23852385
},
2386+
Lint {
2387+
name: "unnecessary_lazy_eval",
2388+
group: "style",
2389+
desc: "using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation",
2390+
deprecation: None,
2391+
module: "methods",
2392+
},
23862393
Lint {
23872394
name: "unnecessary_mut_passed",
23882395
group: "style",

tests/ui/unnecessary_lazy_eval.fixed

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
// run-rustfix
2+
#![warn(clippy::unnecessary_lazy_evaluation)]
3+
#![allow(clippy::redundant_closure)]
4+
#![allow(clippy::bind_instead_of_map)]
5+
6+
struct Deep(Option<u32>);
7+
8+
#[derive(Copy, Clone)]
9+
struct SomeStruct {
10+
some_field: u32,
11+
}
12+
13+
impl SomeStruct {
14+
fn return_some_field(&self) -> u32 {
15+
self.some_field
16+
}
17+
}
18+
19+
fn some_call<T: Default>() -> T {
20+
T::default()
21+
}
22+
23+
fn main() {
24+
let astronomers_pi = 10;
25+
let ext_str = SomeStruct { some_field: 10 };
26+
27+
// Should lint - Option
28+
let mut opt = Some(42);
29+
let ext_opt = Some(42);
30+
let _ = opt.unwrap_or(2);
31+
let _ = opt.unwrap_or(astronomers_pi);
32+
let _ = opt.unwrap_or(ext_str.some_field);
33+
let _ = opt.and(ext_opt);
34+
let _ = opt.or(ext_opt);
35+
let _ = opt.or(None);
36+
let _ = opt.get_or_insert(2);
37+
let _ = opt.ok_or(2);
38+
39+
// Cases when unwrap is not called on a simple variable
40+
let _ = Some(10).unwrap_or(2);
41+
let _ = Some(10).and(ext_opt);
42+
let _: Option<u32> = None.or(ext_opt);
43+
let _ = None.get_or_insert(2);
44+
let _: Result<u32, u32> = None.ok_or(2);
45+
let _: Option<u32> = None.or(None);
46+
47+
let mut deep = Deep(Some(42));
48+
let _ = deep.0.unwrap_or(2);
49+
let _ = deep.0.and(ext_opt);
50+
let _ = deep.0.or(None);
51+
let _ = deep.0.get_or_insert(2);
52+
let _ = deep.0.ok_or(2);
53+
54+
// Should not lint - Option
55+
let _ = opt.unwrap_or_else(|| ext_str.return_some_field());
56+
let _ = opt.or_else(some_call);
57+
let _ = opt.or_else(|| some_call());
58+
let _: Result<u32, u32> = opt.ok_or_else(|| some_call());
59+
let _: Result<u32, u32> = opt.ok_or_else(some_call);
60+
let _ = deep.0.get_or_insert_with(|| some_call());
61+
let _ = deep.0.or_else(some_call);
62+
let _ = deep.0.or_else(|| some_call());
63+
64+
// These are handled by bind_instead_of_map
65+
let _: Option<u32> = None.or_else(|| Some(3));
66+
let _ = deep.0.or_else(|| Some(3));
67+
let _ = opt.or_else(|| Some(3));
68+
69+
// Should lint - Result
70+
let res: Result<u32, u32> = Err(5);
71+
let res2: Result<u32, SomeStruct> = Err(SomeStruct { some_field: 5 });
72+
73+
let _ = res2.unwrap_or(2);
74+
let _ = res2.unwrap_or(astronomers_pi);
75+
let _ = res2.unwrap_or(ext_str.some_field);
76+
77+
// Should not lint - Result
78+
let _ = res.unwrap_or_else(|err| err);
79+
let _ = res2.unwrap_or_else(|err| err.some_field);
80+
let _ = res2.unwrap_or_else(|err| err.return_some_field());
81+
let _ = res2.unwrap_or_else(|_| ext_str.return_some_field());
82+
83+
let _: Result<u32, u32> = res.and_then(|x| Ok(x));
84+
let _: Result<u32, u32> = res.and_then(|x| Err(x));
85+
86+
let _: Result<u32, u32> = res.or_else(|err| Ok(err));
87+
let _: Result<u32, u32> = res.or_else(|err| Err(err));
88+
89+
// These are handled by bind_instead_of_map
90+
let _: Result<u32, u32> = res.and_then(|_| Ok(2));
91+
let _: Result<u32, u32> = res.and_then(|_| Ok(astronomers_pi));
92+
let _: Result<u32, u32> = res.and_then(|_| Ok(ext_str.some_field));
93+
94+
let _: Result<u32, u32> = res.and_then(|_| Err(2));
95+
let _: Result<u32, u32> = res.and_then(|_| Err(astronomers_pi));
96+
let _: Result<u32, u32> = res.and_then(|_| Err(ext_str.some_field));
97+
98+
let _: Result<u32, u32> = res.or_else(|_| Ok(2));
99+
let _: Result<u32, u32> = res.or_else(|_| Ok(astronomers_pi));
100+
let _: Result<u32, u32> = res.or_else(|_| Ok(ext_str.some_field));
101+
102+
let _: Result<u32, u32> = res.or_else(|_| Err(2));
103+
let _: Result<u32, u32> = res.or_else(|_| Err(astronomers_pi));
104+
let _: Result<u32, u32> = res.or_else(|_| Err(ext_str.some_field));
105+
}

0 commit comments

Comments
 (0)