Skip to content

Commit 8d0d89a

Browse files
committed
Auto merge of #5720 - bugadani:new-lint, r=flip1995,yaahc
Add unnecessary lazy evaluation lint changelog: Add [`unnecessary_lazy_evaluations`] lint that checks for usages of `unwrap_or_else` and similar functions that can be simplified. Closes #5715
2 parents 5d723d0 + fc1e07e commit 8d0d89a

File tree

8 files changed

+561
-5
lines changed

8 files changed

+561
-5
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -1754,6 +1754,7 @@ Released 2018-09-13
17541754
[`unnecessary_cast`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_cast
17551755
[`unnecessary_filter_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_filter_map
17561756
[`unnecessary_fold`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_fold
1757+
[`unnecessary_lazy_evaluations`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_lazy_evaluations
17571758
[`unnecessary_mut_passed`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_mut_passed
17581759
[`unnecessary_operation`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_operation
17591760
[`unnecessary_sort_by`]: https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_sort_by

clippy_lints/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -685,6 +685,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
685685
&methods::UNINIT_ASSUMED_INIT,
686686
&methods::UNNECESSARY_FILTER_MAP,
687687
&methods::UNNECESSARY_FOLD,
688+
&methods::UNNECESSARY_LAZY_EVALUATIONS,
688689
&methods::UNWRAP_USED,
689690
&methods::USELESS_ASREF,
690691
&methods::WRONG_PUB_SELF_CONVENTION,
@@ -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_EVALUATIONS),
13631365
LintId::of(&methods::USELESS_ASREF),
13641366
LintId::of(&methods::WRONG_SELF_CONVENTION),
13651367
LintId::of(&methods::ZST_OFFSET),
@@ -1540,6 +1542,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
15401542
LintId::of(&methods::SINGLE_CHAR_PUSH_STR),
15411543
LintId::of(&methods::STRING_EXTEND_CHARS),
15421544
LintId::of(&methods::UNNECESSARY_FOLD),
1545+
LintId::of(&methods::UNNECESSARY_LAZY_EVALUATIONS),
15431546
LintId::of(&methods::WRONG_SELF_CONVENTION),
15441547
LintId::of(&misc::TOPLEVEL_REF_ARG),
15451548
LintId::of(&misc::ZERO_PTR),

clippy_lints/src/methods/mod.rs

+57-5
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ mod inefficient_to_string;
33
mod manual_saturating_arithmetic;
44
mod option_map_unwrap_or;
55
mod unnecessary_filter_map;
6+
mod unnecessary_lazy_eval;
67

78
use std::borrow::Cow;
89
use std::fmt;
@@ -1329,6 +1330,42 @@ declare_clippy_lint! {
13291330
"`push_str()` used with a single-character string literal as parameter"
13301331
}
13311332

1333+
declare_clippy_lint! {
1334+
/// **What it does:** As the counterpart to `or_fun_call`, this lint looks for unnecessary
1335+
/// lazily evaluated closures on `Option` and `Result`.
1336+
///
1337+
/// This lint suggests changing the following functions, when eager evaluation results in
1338+
/// simpler code:
1339+
/// - `unwrap_or_else` to `unwrap_or`
1340+
/// - `and_then` to `and`
1341+
/// - `or_else` to `or`
1342+
/// - `get_or_insert_with` to `get_or_insert`
1343+
/// - `ok_or_else` to `ok_or`
1344+
///
1345+
/// **Why is this bad?** Using eager evaluation is shorter and simpler in some cases.
1346+
///
1347+
/// **Known problems:** It is possible, but not recommended for `Deref` and `Index` to have
1348+
/// side effects. Eagerly evaluating them can change the semantics of the program.
1349+
///
1350+
/// **Example:**
1351+
///
1352+
/// ```rust
1353+
/// // example code where clippy issues a warning
1354+
/// let opt: Option<u32> = None;
1355+
///
1356+
/// opt.unwrap_or_else(|| 42);
1357+
/// ```
1358+
/// Use instead:
1359+
/// ```rust
1360+
/// let opt: Option<u32> = None;
1361+
///
1362+
/// opt.unwrap_or(42);
1363+
/// ```
1364+
pub UNNECESSARY_LAZY_EVALUATIONS,
1365+
style,
1366+
"using unnecessary lazy evaluation, which can be replaced with simpler eager evaluation"
1367+
}
1368+
13321369
declare_lint_pass!(Methods => [
13331370
UNWRAP_USED,
13341371
EXPECT_USED,
@@ -1378,6 +1415,7 @@ declare_lint_pass!(Methods => [
13781415
ZST_OFFSET,
13791416
FILETYPE_IS_FILE,
13801417
OPTION_AS_REF_DEREF,
1418+
UNNECESSARY_LAZY_EVALUATIONS,
13811419
]);
13821420

13831421
impl<'tcx> LateLintPass<'tcx> for Methods {
@@ -1398,13 +1436,19 @@ impl<'tcx> LateLintPass<'tcx> for Methods {
13981436
["expect", "ok"] => lint_ok_expect(cx, expr, arg_lists[1]),
13991437
["expect", ..] => lint_expect(cx, expr, arg_lists[0]),
14001438
["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]),
1439+
["unwrap_or_else", "map"] => {
1440+
if !lint_map_unwrap_or_else(cx, expr, arg_lists[1], arg_lists[0]) {
1441+
unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], true, "unwrap_or");
1442+
}
1443+
},
14021444
["map_or", ..] => lint_map_or_none(cx, expr, arg_lists[0]),
14031445
["and_then", ..] => {
1446+
unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], false, "and");
14041447
bind_instead_of_map::OptionAndThenSome::lint(cx, expr, arg_lists[0]);
14051448
bind_instead_of_map::ResultAndThenOk::lint(cx, expr, arg_lists[0]);
14061449
},
14071450
["or_else", ..] => {
1451+
unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], false, "or");
14081452
bind_instead_of_map::ResultOrElseErrInfo::lint(cx, expr, arg_lists[0]);
14091453
},
14101454
["next", "filter"] => lint_filter_next(cx, expr, arg_lists[1]),
@@ -1448,6 +1492,9 @@ impl<'tcx> LateLintPass<'tcx> for Methods {
14481492
["is_file", ..] => lint_filetype_is_file(cx, expr, arg_lists[0]),
14491493
["map", "as_ref"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], false),
14501494
["map", "as_mut"] => lint_option_as_ref_deref(cx, expr, arg_lists[1], arg_lists[0], true),
1495+
["unwrap_or_else", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], true, "unwrap_or"),
1496+
["get_or_insert_with", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], true, "get_or_insert"),
1497+
["ok_or_else", ..] => unnecessary_lazy_eval::lint(cx, expr, arg_lists[0], true, "ok_or"),
14511498
_ => {},
14521499
}
14531500

@@ -2664,12 +2711,13 @@ fn lint_map_flatten<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, map
26642711
}
26652712

26662713
/// lint use of `map().unwrap_or_else()` for `Option`s and `Result`s
2714+
/// Return true if lint triggered
26672715
fn lint_map_unwrap_or_else<'tcx>(
26682716
cx: &LateContext<'tcx>,
26692717
expr: &'tcx hir::Expr<'_>,
26702718
map_args: &'tcx [hir::Expr<'_>],
26712719
unwrap_args: &'tcx [hir::Expr<'_>],
2672-
) {
2720+
) -> bool {
26732721
// lint if the caller of `map()` is an `Option`
26742722
let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym!(option_type));
26752723
let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym!(result_type));
@@ -2681,10 +2729,10 @@ fn lint_map_unwrap_or_else<'tcx>(
26812729
let unwrap_mutated_vars = mutated_variables(&unwrap_args[1], cx);
26822730
if let (Some(map_mutated_vars), Some(unwrap_mutated_vars)) = (map_mutated_vars, unwrap_mutated_vars) {
26832731
if map_mutated_vars.intersection(&unwrap_mutated_vars).next().is_some() {
2684-
return;
2732+
return false;
26852733
}
26862734
} else {
2687-
return;
2735+
return false;
26882736
}
26892737

26902738
// lint message
@@ -2714,10 +2762,14 @@ fn lint_map_unwrap_or_else<'tcx>(
27142762
map_snippet, unwrap_snippet,
27152763
),
27162764
);
2765+
return true;
27172766
} else if same_span && multiline {
27182767
span_lint(cx, MAP_UNWRAP_OR, expr.span, msg);
2719-
};
2768+
return true;
2769+
}
27202770
}
2771+
2772+
false
27212773
}
27222774

27232775
/// lint use of `_.map_or(None, _)` for `Option`s and `Result`s
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
use crate::utils::{is_type_diagnostic_item, match_qpath, snippet, span_lint_and_sugg};
2+
use if_chain::if_chain;
3+
use rustc_errors::Applicability;
4+
use rustc_hir as hir;
5+
use rustc_lint::LateContext;
6+
7+
use super::UNNECESSARY_LAZY_EVALUATIONS;
8+
9+
// Return true if the expression is an accessor of any of the arguments
10+
fn expr_uses_argument(expr: &hir::Expr<'_>, params: &[hir::Param<'_>]) -> bool {
11+
params.iter().any(|arg| {
12+
if_chain! {
13+
if let hir::PatKind::Binding(_, _, ident, _) = arg.pat.kind;
14+
if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = expr.kind;
15+
if let [p, ..] = path.segments;
16+
then {
17+
ident.name == p.ident.name
18+
} else {
19+
false
20+
}
21+
}
22+
})
23+
}
24+
25+
fn match_any_qpath(path: &hir::QPath<'_>, paths: &[&[&str]]) -> bool {
26+
paths.iter().any(|candidate| match_qpath(path, candidate))
27+
}
28+
29+
fn can_simplify(expr: &hir::Expr<'_>, params: &[hir::Param<'_>], variant_calls: bool) -> bool {
30+
match expr.kind {
31+
// Closures returning literals can be unconditionally simplified
32+
hir::ExprKind::Lit(_) => true,
33+
34+
hir::ExprKind::Index(ref object, ref index) => {
35+
// arguments are not being indexed into
36+
if expr_uses_argument(object, params) {
37+
false
38+
} else {
39+
// arguments are not used as index
40+
!expr_uses_argument(index, params)
41+
}
42+
},
43+
44+
// Reading fields can be simplified if the object is not an argument of the closure
45+
hir::ExprKind::Field(ref object, _) => !expr_uses_argument(object, params),
46+
47+
// Paths can be simplified if the root is not the argument, this also covers None
48+
hir::ExprKind::Path(_) => !expr_uses_argument(expr, params),
49+
50+
// Calls to Some, Ok, Err can be considered literals if they don't derive an argument
51+
hir::ExprKind::Call(ref func, ref args) => if_chain! {
52+
if variant_calls; // Disable lint when rules conflict with bind_instead_of_map
53+
if let hir::ExprKind::Path(ref path) = func.kind;
54+
if match_any_qpath(path, &[&["Some"], &["Ok"], &["Err"]]);
55+
then {
56+
// Recursively check all arguments
57+
args.iter().all(|arg| can_simplify(arg, params, variant_calls))
58+
} else {
59+
false
60+
}
61+
},
62+
63+
// For anything more complex than the above, a closure is probably the right solution,
64+
// or the case is handled by an other lint
65+
_ => false,
66+
}
67+
}
68+
69+
/// lint use of `<fn>_else(simple closure)` for `Option`s and `Result`s that can be
70+
/// replaced with `<fn>(return value of simple closure)`
71+
pub(super) fn lint<'tcx>(
72+
cx: &LateContext<'tcx>,
73+
expr: &'tcx hir::Expr<'_>,
74+
args: &'tcx [hir::Expr<'_>],
75+
allow_variant_calls: bool,
76+
simplify_using: &str,
77+
) {
78+
let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&args[0]), sym!(option_type));
79+
let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&args[0]), sym!(result_type));
80+
81+
if is_option || is_result {
82+
if let hir::ExprKind::Closure(_, _, eid, _, _) = args[1].kind {
83+
let body = cx.tcx.hir().body(eid);
84+
let ex = &body.value;
85+
let params = &body.params;
86+
87+
if can_simplify(ex, params, allow_variant_calls) {
88+
let msg = if is_option {
89+
"unnecessary closure used to substitute value for `Option::None`"
90+
} else {
91+
"unnecessary closure used to substitute value for `Result::Err`"
92+
};
93+
94+
span_lint_and_sugg(
95+
cx,
96+
UNNECESSARY_LAZY_EVALUATIONS,
97+
expr.span,
98+
msg,
99+
&format!("Use `{}` instead", simplify_using),
100+
format!(
101+
"{0}.{1}({2})",
102+
snippet(cx, args[0].span, ".."),
103+
simplify_using,
104+
snippet(cx, ex.span, ".."),
105+
),
106+
Applicability::MachineApplicable,
107+
);
108+
}
109+
}
110+
}
111+
}

src/lintlist/mod.rs

+7
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_evaluations",
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",

0 commit comments

Comments
 (0)