1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::source::snippet_with_macro_callsite;
3 use clippy_utils::{higher, is_else_clause, is_lang_ctor, meets_msrv, msrvs};
4 use if_chain::if_chain;
5 use rustc_hir::LangItem::{OptionNone, OptionSome};
6 use rustc_hir::{Expr, ExprKind};
7 use rustc_lint::{LateContext, LateLintPass, LintContext};
8 use rustc_middle::lint::in_external_macro;
9 use rustc_semver::RustcVersion;
10 use rustc_session::{declare_tool_lint, impl_lint_pass};
12 declare_clippy_lint! {
14 /// Checks for if-else that could be written to `bool::then`.
16 /// ### Why is this bad?
17 /// Looks a little redundant. Using `bool::then` helps it have less lines of code.
21 /// # let v = vec![0];
22 /// let a = if v.is_empty() {
23 /// println!("true!");
33 /// # let v = vec![0];
34 /// let a = v.is_empty().then(|| {
35 /// println!("true!");
39 pub IF_THEN_SOME_ELSE_NONE,
41 "Finds if-else that could be written using `bool::then`"
44 pub struct IfThenSomeElseNone {
45 msrv: Option<RustcVersion>,
48 impl IfThenSomeElseNone {
50 pub fn new(msrv: Option<RustcVersion>) -> Self {
55 impl_lint_pass!(IfThenSomeElseNone => [IF_THEN_SOME_ELSE_NONE]);
57 impl LateLintPass<'_> for IfThenSomeElseNone {
58 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'tcx Expr<'_>) {
59 if !meets_msrv(self.msrv.as_ref(), &msrvs::BOOL_THEN) {
63 if in_external_macro(cx.sess(), expr.span) {
67 // We only care about the top-most `if` in the chain
68 if is_else_clause(cx.tcx, expr) {
73 if let Some(higher::If { cond, then, r#else: Some(els) }) = higher::If::hir(expr);
74 if let ExprKind::Block(then_block, _) = then.kind;
75 if let Some(then_expr) = then_block.expr;
76 if let ExprKind::Call(then_call, [then_arg]) = then_expr.kind;
77 if let ExprKind::Path(ref then_call_qpath) = then_call.kind;
78 if is_lang_ctor(cx, then_call_qpath, OptionSome);
79 if let ExprKind::Block(els_block, _) = els.kind;
80 if els_block.stmts.is_empty();
81 if let Some(els_expr) = els_block.expr;
82 if let ExprKind::Path(ref qpath) = els_expr.kind;
83 if is_lang_ctor(cx, qpath, OptionNone);
85 let cond_snip = snippet_with_macro_callsite(cx, cond.span, "[condition]");
86 let cond_snip = if matches!(cond.kind, ExprKind::Unary(_, _) | ExprKind::Binary(_, _, _)) {
87 format!("({})", cond_snip)
89 cond_snip.into_owned()
91 let arg_snip = snippet_with_macro_callsite(cx, then_arg.span, "");
92 let closure_body = if then_block.stmts.is_empty() {
95 format!("{{ /* snippet */ {} }}", arg_snip)
98 "consider using `bool::then` like: `{}.then(|| {})`",
104 IF_THEN_SOME_ELSE_NONE,
106 "this could be simplified with `bool::then`",
114 extract_msrv_attr!(LateContext);