1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::source::snippet_with_macro_callsite;
3 use clippy_utils::{match_qpath, meets_msrv, parent_node_is_if_expr};
4 use if_chain::if_chain;
5 use rustc_hir::{Expr, ExprKind};
6 use rustc_lint::{LateContext, LateLintPass, LintContext};
7 use rustc_middle::lint::in_external_macro;
8 use rustc_semver::RustcVersion;
9 use rustc_session::{declare_tool_lint, impl_lint_pass};
11 const IF_THEN_SOME_ELSE_NONE_MSRV: RustcVersion = RustcVersion::new(1, 50, 0);
13 declare_clippy_lint! {
14 /// **What it does:** Checks for if-else that could be written to `bool::then`.
16 /// **Why is this bad?** Looks a little redundant. Using `bool::then` helps it have less lines of code.
18 /// **Known problems:** None.
23 /// # let v = vec![0];
24 /// let a = if v.is_empty() {
25 /// println!("true!");
35 /// # let v = vec![0];
36 /// let a = v.is_empty().then(|| {
37 /// println!("true!");
41 pub IF_THEN_SOME_ELSE_NONE,
43 "Finds if-else that could be written using `bool::then`"
46 pub struct IfThenSomeElseNone {
47 msrv: Option<RustcVersion>,
50 impl IfThenSomeElseNone {
52 pub fn new(msrv: Option<RustcVersion>) -> Self {
57 impl_lint_pass!(IfThenSomeElseNone => [IF_THEN_SOME_ELSE_NONE]);
59 impl LateLintPass<'_> for IfThenSomeElseNone {
60 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'tcx Expr<'_>) {
61 if !meets_msrv(self.msrv.as_ref(), &IF_THEN_SOME_ELSE_NONE_MSRV) {
65 if in_external_macro(cx.sess(), expr.span) {
69 // We only care about the top-most `if` in the chain
70 if parent_node_is_if_expr(expr, cx) {
75 if let ExprKind::If(cond, then, Some(els)) = expr.kind;
76 if let ExprKind::Block(then_block, _) = then.kind;
77 if let Some(then_expr) = then_block.expr;
78 if let ExprKind::Call(then_call, [then_arg]) = then_expr.kind;
79 if let ExprKind::Path(ref then_call_qpath) = then_call.kind;
80 if match_qpath(then_call_qpath, &clippy_utils::paths::OPTION_SOME);
81 if let ExprKind::Block(els_block, _) = els.kind;
82 if els_block.stmts.is_empty();
83 if let Some(els_expr) = els_block.expr;
84 if let ExprKind::Path(ref els_call_qpath) = els_expr.kind;
85 if match_qpath(els_call_qpath, &clippy_utils::paths::OPTION_NONE);
87 let cond_snip = snippet_with_macro_callsite(cx, cond.span, "[condition]");
88 let cond_snip = if matches!(cond.kind, ExprKind::Unary(_, _) | ExprKind::Binary(_, _, _)) {
89 format!("({})", cond_snip)
91 cond_snip.into_owned()
93 let arg_snip = snippet_with_macro_callsite(cx, then_arg.span, "");
94 let closure_body = if then_block.stmts.is_empty() {
97 format!("{{ /* snippet */ {} }}", arg_snip)
100 "consider using `bool::then` like: `{}.then(|| {})`",
106 IF_THEN_SOME_ELSE_NONE,
108 "this could be simplified with `bool::then`",
116 extract_msrv_attr!(LateContext);