Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 17 additions & 15 deletions clippy_lints/src/if_then_some_else_none.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ use clippy_config::Conf;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::eager_or_lazy::switch_to_eager_eval;
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::source::snippet_with_context;
use clippy_utils::source::{snippet_with_applicability, snippet_with_context, walk_span_to_context};
use clippy_utils::sugg::Sugg;
use clippy_utils::{
contains_return, expr_adjustment_requires_coercion, higher, is_else_clause, is_in_const_context, is_res_lang_ctor,
path_res, peel_blocks,
path_res, peel_blocks, sym,
};
use rustc_errors::Applicability;
use rustc_hir::LangItem::{OptionNone, OptionSome};
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::impl_lint_pass;

declare_clippy_lint! {
Expand Down Expand Up @@ -71,21 +71,21 @@ impl<'tcx> LateLintPass<'tcx> for IfThenSomeElseNone {
&& let ExprKind::Block(then_block, _) = then.kind
&& let Some(then_expr) = then_block.expr
&& let ExprKind::Call(then_call, [then_arg]) = then_expr.kind
&& let ctxt = expr.span.ctxt()
&& then_expr.span.ctxt() == ctxt
&& !expr.span.from_expansion()
&& !then_expr.span.from_expansion()
&& is_res_lang_ctor(cx, path_res(cx, then_call), OptionSome)
&& is_res_lang_ctor(cx, path_res(cx, peel_blocks(els)), OptionNone)
&& !is_else_clause(cx.tcx, expr)
&& !is_in_const_context(cx)
&& !expr.span.in_external_macro(cx.sess().source_map())
Comment on lines -74 to -80
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason for why we don't want to lint code from within local macros anymore?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good question. Is there a context in which I can get the non-expanded code? If the if … { Some(…) } else { None } is in the macro, using the context of the if expression is not enough to get non-expanded code for the condition or the content of the Some. How can I retrieve it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another reason would be that we sometimes suggest .then(|| …) and sometimes .then_some(). Here, in a macro, we would have to suggest .then(|| …) because we won't check every call for the absence of side effects.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, those are fair points.

&& self.msrv.meets(cx, msrvs::BOOL_THEN)
&& !contains_return(then_block.stmts)
{
let method_name = if switch_to_eager_eval(cx, expr) && self.msrv.meets(cx, msrvs::BOOL_THEN_SOME) {
"then_some"
sym::then_some
} else {
"then"
sym::then
};
let ctxt = expr.span.ctxt();

span_lint_and_then(
cx,
Expand All @@ -98,16 +98,18 @@ impl<'tcx> LateLintPass<'tcx> for IfThenSomeElseNone {
}

let mut app = Applicability::MachineApplicable;
let cond_snip = Sugg::hir_with_context(cx, cond, expr.span.ctxt(), "[condition]", &mut app)
let cond_snip = Sugg::hir_with_context(cx, cond, ctxt, "[condition]", &mut app)
.maybe_paren()
.to_string();
let arg_snip = snippet_with_context(cx, then_arg.span, ctxt, "[body]", &mut app).0;
let method_body = if let Some(first_stmt) = then_block.stmts.first() {
let (block_snippet, _) =
snippet_with_context(cx, first_stmt.span.until(then_arg.span), ctxt, "..", &mut app);
let closure = if method_name == "then" { "|| " } else { "" };
format!("{closure} {{ {block_snippet}; {arg_snip} }}")
} else if method_name == "then" {
let method_body = if let Some(first_stmt) = then_block.stmts.first()
&& let Some(first_stmt_span) = walk_span_to_context(first_stmt.span, ctxt)
{
let block_snippet =
snippet_with_applicability(cx, first_stmt_span.until(then_expr.span), "..", &mut app);
let closure = if method_name == sym::then { "|| " } else { "" };
format!("{closure} {{ {} {arg_snip} }}", block_snippet.trim_end())
} else if method_name == sym::then {
(std::borrow::Cow::Borrowed("|| ") + arg_snip).into_owned()
} else {
arg_snip.into_owned()
Expand Down
41 changes: 41 additions & 0 deletions tests/ui/if_then_some_else_none.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,44 @@ mod issue15257 {
do_something((i % 2 == 0).then_some(closure_fn));
}
}

fn issue15005() {
struct Counter {
count: u32,
}

impl Counter {
fn new() -> Counter {
Counter { count: 0 }
}
}

impl Iterator for Counter {
type Item = u32;

fn next(&mut self) -> Option<Self::Item> {
//~v if_then_some_else_none
(self.count < 5).then(|| { self.count += 1; self.count })
}
}
}

fn statements_from_macro() {
macro_rules! mac {
() => {
println!("foo");
println!("bar");
};
}
//~v if_then_some_else_none
let _ = true.then(|| { mac!(); 42 });
}

fn dont_lint_inside_macros() {
macro_rules! mac {
($cond:expr, $res:expr) => {
if $cond { Some($res) } else { None }
};
}
let _: Option<u32> = mac!(true, 42);
}
51 changes: 51 additions & 0 deletions tests/ui/if_then_some_else_none.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,54 @@ mod issue15257 {
});
}
}

fn issue15005() {
struct Counter {
count: u32,
}

impl Counter {
fn new() -> Counter {
Counter { count: 0 }
}
}

impl Iterator for Counter {
type Item = u32;

fn next(&mut self) -> Option<Self::Item> {
//~v if_then_some_else_none
if self.count < 5 {
self.count += 1;
Some(self.count)
} else {
None
}
}
}
}

fn statements_from_macro() {
macro_rules! mac {
() => {
println!("foo");
println!("bar");
};
}
//~v if_then_some_else_none
let _ = if true {
mac!();
Some(42)
} else {
None
};
}

fn dont_lint_inside_macros() {
macro_rules! mac {
($cond:expr, $res:expr) => {
if $cond { Some($res) } else { None }
};
}
let _: Option<u32> = mac!(true, 42);
}
25 changes: 24 additions & 1 deletion tests/ui/if_then_some_else_none.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -116,5 +116,28 @@ LL | | None
LL | | });
| |_________^ help: try: `(i % 2 == 0).then_some(closure_fn)`

error: aborting due to 11 previous errors
error: this could be simplified with `bool::then`
--> tests/ui/if_then_some_else_none.rs:231:13
|
LL | / if self.count < 5 {
LL | | self.count += 1;
LL | | Some(self.count)
LL | | } else {
LL | | None
LL | | }
| |_____________^ help: try: `(self.count < 5).then(|| { self.count += 1; self.count })`

error: this could be simplified with `bool::then`
--> tests/ui/if_then_some_else_none.rs:249:13
|
LL | let _ = if true {
| _____________^
LL | | mac!();
LL | | Some(42)
LL | | } else {
LL | | None
LL | | };
| |_____^ help: try: `true.then(|| { mac!(); 42 })`

error: aborting due to 13 previous errors