-
Notifications
You must be signed in to change notification settings - Fork 1.8k
new lint: [or_else_then_unwrap
]
#15734
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
@@ -0,0 +1,74 @@ | ||||||||||
use clippy_utils::diagnostics::span_lint_and_sugg; | ||||||||||
use clippy_utils::source::snippet_with_applicability; | ||||||||||
use clippy_utils::ty::is_type_diagnostic_item; | ||||||||||
use clippy_utils::{is_res_lang_ctor, path_res}; | ||||||||||
use rustc_errors::Applicability; | ||||||||||
use rustc_hir::lang_items::LangItem; | ||||||||||
use rustc_hir::{Body, Expr, ExprKind}; | ||||||||||
use rustc_lint::LateContext; | ||||||||||
use rustc_span::{Span, sym}; | ||||||||||
|
||||||||||
use super::OR_ELSE_THEN_UNWRAP; | ||||||||||
|
||||||||||
pub(super) fn check<'tcx>( | ||||||||||
cx: &LateContext<'tcx>, | ||||||||||
unwrap_expr: &Expr<'_>, | ||||||||||
recv: &'tcx Expr<'tcx>, | ||||||||||
or_else_arg: &'tcx Expr<'_>, | ||||||||||
or_span: Span, | ||||||||||
) { | ||||||||||
let ty = cx.typeck_results().expr_ty(recv); // get type of x (we later check if it's Option or Result) | ||||||||||
let title; | ||||||||||
let or_else_arg_content: Span; | ||||||||||
|
||||||||||
if is_type_diagnostic_item(cx, ty, sym::Option) { | ||||||||||
title = "found `.or_else(|| Some(…)).unwrap()`"; | ||||||||||
if let Some(content) = get_content_if_ctor_matches_in_closure(cx, or_else_arg, LangItem::OptionSome) { | ||||||||||
or_else_arg_content = content; | ||||||||||
} else { | ||||||||||
return; | ||||||||||
} | ||||||||||
} else if is_type_diagnostic_item(cx, ty, sym::Result) { | ||||||||||
title = "found `.or_else(|| Ok(…)).unwrap()`"; | ||||||||||
if let Some(content) = get_content_if_ctor_matches_in_closure(cx, or_else_arg, LangItem::ResultOk) { | ||||||||||
or_else_arg_content = content; | ||||||||||
} else { | ||||||||||
return; | ||||||||||
} | ||||||||||
} else { | ||||||||||
// Someone has implemented a struct with .or(...).unwrap() chaining, | ||||||||||
// but it's not an Option or a Result, so bail | ||||||||||
return; | ||||||||||
} | ||||||||||
|
||||||||||
let mut applicability = Applicability::MachineApplicable; | ||||||||||
let suggestion = format!( | ||||||||||
"unwrap_or_else(|| {})", | ||||||||||
snippet_with_applicability(cx, or_else_arg_content, "..", &mut applicability) | ||||||||||
); | ||||||||||
|
||||||||||
span_lint_and_sugg( | ||||||||||
cx, | ||||||||||
OR_ELSE_THEN_UNWRAP, | ||||||||||
unwrap_expr.span.with_lo(or_span.lo()), | ||||||||||
title, | ||||||||||
"try", | ||||||||||
suggestion, | ||||||||||
applicability, | ||||||||||
); | ||||||||||
} | ||||||||||
|
||||||||||
fn get_content_if_ctor_matches_in_closure(cx: &LateContext<'_>, expr: &Expr<'_>, item: LangItem) -> Option<Span> { | ||||||||||
if let ExprKind::Closure(closure) = expr.kind | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No idea how likely this is, but you could add a check for the fn main() {
macro_rules! some { () => { Some(5) } };
None.or_else(|| some!()).unwrap(); See this section for more info: https://doc.rust-lang.org/clippy/development/macro_expansions.html#spanctxt-method |
||||||||||
&& let Body { | ||||||||||
params: [], | ||||||||||
value: body, | ||||||||||
} = cx.tcx.hir_body(closure.body) | ||||||||||
&& let ExprKind::Call(some_expr, [arg]) = body.kind | ||||||||||
&& is_res_lang_ctor(cx, path_res(cx, some_expr), item) | ||||||||||
Comment on lines
+67
to
+68
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
{ | ||||||||||
Some(arg.span.source_callsite()) | ||||||||||
} else { | ||||||||||
None | ||||||||||
} | ||||||||||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
#![warn(clippy::or_then_unwrap)] | ||
#![allow(clippy::map_identity, clippy::let_unit_value, clippy::unnecessary_literal_unwrap)] | ||
|
||
struct SomeStruct; | ||
impl SomeStruct { | ||
fn or_else<F: FnOnce() -> Option<Self>>(self, _: F) -> Self { | ||
self | ||
} | ||
fn unwrap(&self) {} | ||
} | ||
|
||
struct SomeOtherStruct; | ||
impl SomeOtherStruct { | ||
fn or_else(self) -> Self { | ||
self | ||
} | ||
fn unwrap(&self) {} | ||
} | ||
|
||
struct Wrapper { | ||
inner: &'static str, | ||
} | ||
impl Wrapper { | ||
fn new(inner: &'static str) -> Self { | ||
Self { inner } | ||
} | ||
} | ||
|
||
fn main() { | ||
let option: Option<Wrapper> = None; | ||
let _ = option.unwrap_or_else(|| Wrapper::new("fallback")); // should trigger lint | ||
// | ||
//~^^ or_else_then_unwrap | ||
|
||
// as part of a method chain | ||
let option: Option<Wrapper> = None; | ||
let _ = option | ||
.map(|v| v) | ||
.unwrap_or_else(|| Wrapper::new("fallback")) | ||
.inner | ||
.to_string() | ||
.chars(); | ||
|
||
// Call with macro should preserve the macro call rather than expand it | ||
let option: Option<Vec<&'static str>> = None; | ||
let _ = option.unwrap_or_else(|| vec!["fallback"]); // should trigger lint | ||
// | ||
//~^^ or_else_then_unwrap | ||
|
||
// Not Option/Result | ||
let instance = SomeStruct {}; | ||
let _ = instance.or_else(|| Some(SomeStruct {})).unwrap(); // should not trigger lint | ||
|
||
// or takes no argument | ||
let instance = SomeOtherStruct {}; | ||
let _ = instance.or_else().unwrap(); // should not trigger lint and should not panic | ||
|
||
// None in or | ||
let option: Option<Wrapper> = None; | ||
#[allow(clippy::unnecessary_lazy_evaluations)] | ||
let _ = option.or_else(|| None).unwrap(); // should not trigger lint | ||
|
||
// other function between | ||
let option: Option<Wrapper> = None; | ||
let _ = option.or_else(|| Some(Wrapper::new("fallback"))).map(|v| v).unwrap(); // should not trigger lint | ||
} |
Original file line number | Diff line number | Diff line change | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
@@ -0,0 +1,69 @@ | ||||||||||
#![warn(clippy::or_then_unwrap)] | ||||||||||
#![allow(clippy::map_identity, clippy::let_unit_value, clippy::unnecessary_literal_unwrap)] | ||||||||||
|
||||||||||
struct SomeStruct; | ||||||||||
impl SomeStruct { | ||||||||||
fn or_else<F: FnOnce() -> Option<Self>>(self, _: F) -> Self { | ||||||||||
self | ||||||||||
} | ||||||||||
fn unwrap(&self) {} | ||||||||||
} | ||||||||||
|
||||||||||
struct SomeOtherStruct; | ||||||||||
impl SomeOtherStruct { | ||||||||||
fn or_else(self) -> Self { | ||||||||||
self | ||||||||||
} | ||||||||||
fn unwrap(&self) {} | ||||||||||
} | ||||||||||
|
||||||||||
struct Wrapper { | ||||||||||
inner: &'static str, | ||||||||||
} | ||||||||||
impl Wrapper { | ||||||||||
fn new(inner: &'static str) -> Self { | ||||||||||
Self { inner } | ||||||||||
} | ||||||||||
} | ||||||||||
|
||||||||||
fn main() { | ||||||||||
let option: Option<Wrapper> = None; | ||||||||||
let _ = option.or_else(|| Some(Wrapper::new("fallback"))).unwrap(); // should trigger lint | ||||||||||
// | ||||||||||
//~^^ or_else_then_unwrap | ||||||||||
Comment on lines
+31
to
+33
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. having both of these comments is a bit redundant imo.. If you want to have a comment by the side, you could do something like:
Suggested change
Which is not very common across the test suite, but pretty clean imo |
||||||||||
|
||||||||||
// as part of a method chain | ||||||||||
let option: Option<Wrapper> = None; | ||||||||||
let _ = option | ||||||||||
.map(|v| v) | ||||||||||
.or_else(|| Some(Wrapper::new("fallback"))) // should trigger lint | ||||||||||
// | ||||||||||
//~^^ or_else_then_unwrap | ||||||||||
.unwrap() | ||||||||||
.inner | ||||||||||
.to_string() | ||||||||||
.chars(); | ||||||||||
|
||||||||||
// Call with macro should preserve the macro call rather than expand it | ||||||||||
let option: Option<Vec<&'static str>> = None; | ||||||||||
let _ = option.or_else(|| Some(vec!["fallback"])).unwrap(); // should trigger lint | ||||||||||
// | ||||||||||
//~^^ or_else_then_unwrap | ||||||||||
|
||||||||||
// Not Option/Result | ||||||||||
let instance = SomeStruct {}; | ||||||||||
let _ = instance.or_else(|| Some(SomeStruct {})).unwrap(); // should not trigger lint | ||||||||||
|
||||||||||
// or takes no argument | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It took me a bit to parse this 😅 Could you please add backticks, and specify the whole name while we're at it?
Suggested change
|
||||||||||
let instance = SomeOtherStruct {}; | ||||||||||
let _ = instance.or_else().unwrap(); // should not trigger lint and should not panic | ||||||||||
|
||||||||||
// None in or | ||||||||||
let option: Option<Wrapper> = None; | ||||||||||
#[allow(clippy::unnecessary_lazy_evaluations)] | ||||||||||
let _ = option.or_else(|| None).unwrap(); // should not trigger lint | ||||||||||
|
||||||||||
// other function between | ||||||||||
let option: Option<Wrapper> = None; | ||||||||||
let _ = option.or_else(|| Some(Wrapper::new("fallback"))).map(|v| v).unwrap(); // should not trigger lint | ||||||||||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
error: found `.or_else(|| Some(…)).unwrap()` | ||
--> tests/ui/or_else_then_unwrap.rs:31:20 | ||
| | ||
LL | let _ = option.or_else(|| Some(Wrapper::new("fallback"))).unwrap(); // should trigger lint | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| Wrapper::new("fallback"))` | ||
| | ||
= note: `-D clippy::or-else-then-unwrap` implied by `-D warnings` | ||
= help: to override `-D warnings` add `#[allow(clippy::or_else_then_unwrap)]` | ||
|
||
error: found `.or_else(|| Some(…)).unwrap()` | ||
--> tests/ui/or_else_then_unwrap.rs:39:10 | ||
| | ||
LL | .or_else(|| Some(Wrapper::new("fallback"))) // should trigger lint | ||
| __________^ | ||
... | | ||
LL | | .unwrap() | ||
| |_________________^ help: try: `unwrap_or_else(|| Wrapper::new("fallback"))` | ||
Comment on lines
+11
to
+17
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This diagnostic/suggestion looks a bit crowded -- could you try replacing this: span_lint_and_sugg(
cx,
OR_ELSE_THEN_UNWRAP,
unwrap_expr.span.with_lo(or_span.lo()),
title,
"try",
suggestion,
applicability,
); with |
||
|
||
error: found `.or_else(|| Some(…)).unwrap()` | ||
--> tests/ui/or_else_then_unwrap.rs:49:20 | ||
| | ||
LL | let _ = option.or_else(|| Some(vec!["fallback"])).unwrap(); // should trigger lint | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `unwrap_or_else(|| vec!["fallback"])` | ||
|
||
error: aborting due to 3 previous errors | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
is_type_diagnostic_item
contains a call tocx.tcx.is_diagnostic_item
, which is a bit expensive. A more efficient way to do this would be to first get theDefId
ofty
, and then callcx.tcx.get_diagnostic_name
on that.Also, by pulling the
get_content_if_ctor_matches_in_closure
call into the match arm pattern, you can avoid the need to late-initalizetitle
andor_else_arg_content
To avoid the rather verbose scrutinee, you could pull it into a let-chain, something like: