-
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
Open
illicitonion
wants to merge
1
commit into
rust-lang:master
Choose a base branch
from
illicitonion:or-else-then-unwrap
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+285
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
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 { | ||
if let Body { | ||
params: [], | ||
value: body, | ||
} = cx.tcx.hir_body(closure.body) | ||
{ | ||
if let ExprKind::Call(some_expr, [arg]) = body.kind | ||
&& is_res_lang_ctor(cx, path_res(cx, some_expr), item) | ||
{ | ||
Some(arg.span.source_callsite()) | ||
} else { | ||
None | ||
} | ||
} else { | ||
None | ||
} | ||
} else { | ||
None | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
||
// 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 | ||
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 | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"))` | ||
|
||
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 | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
These nested
if
s can be collapsed