2 use if_chain::if_chain;
3 use rustc_errors::Applicability;
4 use rustc_hir::{Expr, ExprKind};
5 use rustc_lint::{LateContext, LateLintPass, LintContext};
6 use rustc_middle::lint::in_external_macro;
7 use rustc_semver::RustcVersion;
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
10 const IF_THEN_SOME_ELSE_NONE_MSRV: RustcVersion = RustcVersion::new(1, 50, 0);
12 declare_clippy_lint! {
13 /// **What it does:** Checks for if-else that could be written to `bool::then`.
15 /// **Why is this bad?** Looks a little redundant. Using `bool::then` helps it have less lines of code.
17 /// **Known problems:** None.
22 /// # let v = vec![0];
23 /// let a = if v.is_empty() {
24 /// println!("true!");
34 /// # let v = vec![0];
35 /// let a = v.is_empty().then(|| {
36 /// println!("true!");
40 pub IF_THEN_SOME_ELSE_NONE,
42 "Finds if-else that could be written using `bool::then`"
45 pub struct IfThenSomeElseNone {
46 msrv: Option<RustcVersion>,
49 impl IfThenSomeElseNone {
51 pub fn new(msrv: Option<RustcVersion>) -> Self {
56 impl_lint_pass!(IfThenSomeElseNone => [IF_THEN_SOME_ELSE_NONE]);
58 impl LateLintPass<'_> for IfThenSomeElseNone {
59 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'tcx Expr<'_>) {
60 if !utils::meets_msrv(self.msrv.as_ref(), &IF_THEN_SOME_ELSE_NONE_MSRV) {
64 if in_external_macro(cx.sess(), expr.span) {
68 // We only care about the top-most `if` in the chain
69 if utils::parent_node_is_if_expr(expr, cx) {
74 if let ExprKind::If(ref cond, ref then, Some(ref els)) = expr.kind;
75 if let ExprKind::Block(ref then_block, _) = then.kind;
76 if let Some(ref then_expr) = then_block.expr;
77 if let ExprKind::Call(ref then_call, [then_arg]) = then_expr.kind;
78 if let ExprKind::Path(ref then_call_qpath) = then_call.kind;
79 if utils::match_qpath(then_call_qpath, &utils::paths::OPTION_SOME);
80 if let ExprKind::Block(ref els_block, _) = els.kind;
81 if els_block.stmts.is_empty();
82 if let Some(ref els_expr) = els_block.expr;
83 if let ExprKind::Path(ref els_call_qpath) = els_expr.kind;
84 if utils::match_qpath(els_call_qpath, &utils::paths::OPTION_NONE);
86 let mut applicability = Applicability::MachineApplicable;
87 let cond_snip = utils::snippet_with_applicability(cx, cond.span, "[condition]", &mut applicability);
88 let arg_snip = utils::snippet_with_applicability(cx, then_arg.span, "", &mut applicability);
90 "{}.then(|| {{ /* snippet */ {} }})",
94 utils::span_lint_and_sugg(
96 IF_THEN_SOME_ELSE_NONE,
98 "this could be simplified with `bool::then`",
107 extract_msrv_attr!(LateContext);