-
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
10
commits 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.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
35f25be
Add or_else_then_unwrap
illicitonion 6c280d2
Collapse nested `if`s
illicitonion c69f2eb
Switch to let-chain
illicitonion 0275d74
Make comment more concise
illicitonion b8bcd8d
Fix function name
illicitonion 5a9e173
Improve naming
illicitonion 48f6cd4
Make suggestion verbose
illicitonion 5dd81d7
Add example macro call
illicitonion c90a482
fmt
illicitonion 0f37275
Update calls since merge
illicitonion 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,66 @@ | ||
use crate::clippy_utils::res::{MaybeDef, MaybeQPath}; | ||
use clippy_utils::diagnostics::span_lint_and_then; | ||
use clippy_utils::source::snippet_with_applicability; | ||
use rustc_errors::Applicability; | ||
use rustc_hir::lang_items::LangItem; | ||
use rustc_hir::{Body, Expr, ExprKind}; | ||
use rustc_lint::LateContext; | ||
use rustc_middle::ty::AdtDef; | ||
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, or_else_arg_content) = match ty | ||
.ty_adt_def() | ||
.map(AdtDef::did) | ||
.and_then(|did| cx.tcx.get_diagnostic_name(did)) | ||
{ | ||
Some(sym::Option) | ||
if let Some(content) = get_content_if_ctor_matches_in_closure(cx, or_else_arg, LangItem::OptionSome) => | ||
{ | ||
("found `.or_else(|| Some(…)).unwrap()`", content) | ||
}, | ||
Some(sym::Result) | ||
if let Some(content) = get_content_if_ctor_matches_in_closure(cx, or_else_arg, LangItem::ResultOk) => | ||
{ | ||
("found `.or_else(|| Ok(…)).unwrap()`", content) | ||
}, | ||
// 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) | ||
); | ||
|
||
let span = unwrap_expr.span.with_lo(or_span.lo()); | ||
span_lint_and_then(cx, OR_ELSE_THEN_UNWRAP, span, title, |diag| { | ||
diag.span_suggestion_verbose(span, "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 | ||
&& let Body { | ||
params: [], | ||
value: body, | ||
} = cx.tcx.hir_body(closure.body) | ||
&& let ExprKind::Call(some_or_ok, [arg]) = body.kind | ||
&& some_or_ok.res(cx).ctor_parent(cx).is_lang_item(cx, item) | ||
{ | ||
Some(arg.span.source_callsite()) | ||
} 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,74 @@ | ||
//@aux-build:proc_macros.rs | ||
|
||
#![warn(clippy::or_then_unwrap)] | ||
#![allow(clippy::map_identity, clippy::let_unit_value, clippy::unnecessary_literal_unwrap)] | ||
|
||
extern crate proc_macros; | ||
|
||
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")); //~ 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_else` 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 | ||
|
||
// We don't lint external macros | ||
proc_macros::external! { | ||
let option: Option<Wrapper> = None; | ||
let _ = option.or_else(|| Some(Wrapper::new("fallback"))).unwrap(); | ||
}; | ||
} |
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,77 @@ | ||
//@aux-build:proc_macros.rs | ||
|
||
#![warn(clippy::or_then_unwrap)] | ||
#![allow(clippy::map_identity, clippy::let_unit_value, clippy::unnecessary_literal_unwrap)] | ||
|
||
extern crate proc_macros; | ||
|
||
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(); //~ 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_else` 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 | ||
|
||
// We don't lint external macros | ||
proc_macros::external! { | ||
let option: Option<Wrapper> = None; | ||
let _ = option.or_else(|| Some(Wrapper::new("fallback"))).unwrap(); | ||
}; | ||
} |
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,46 @@ | ||
error: found `.or_else(|| Some(…)).unwrap()` | ||
--> tests/ui/or_else_then_unwrap.rs:35:20 | ||
| | ||
LL | let _ = option.or_else(|| Some(Wrapper::new("fallback"))).unwrap(); | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ||
| | ||
= note: `-D clippy::or-else-then-unwrap` implied by `-D warnings` | ||
= help: to override `-D warnings` add `#[allow(clippy::or_else_then_unwrap)]` | ||
help: try | ||
| | ||
LL - let _ = option.or_else(|| Some(Wrapper::new("fallback"))).unwrap(); | ||
LL + let _ = option.unwrap_or_else(|| Wrapper::new("fallback")); | ||
| | ||
|
||
error: found `.or_else(|| Some(…)).unwrap()` | ||
--> tests/ui/or_else_then_unwrap.rs:41:10 | ||
| | ||
LL | .or_else(|| Some(Wrapper::new("fallback"))) // should trigger lint | ||
| __________^ | ||
... | | ||
LL | | .unwrap() | ||
| |_________________^ | ||
| | ||
help: try | ||
| | ||
LL - .or_else(|| Some(Wrapper::new("fallback"))) // should trigger lint | ||
LL - // | ||
LL - | ||
LL - .unwrap() | ||
LL + .unwrap_or_else(|| Wrapper::new("fallback")) | ||
| | ||
|
||
error: found `.or_else(|| Some(…)).unwrap()` | ||
--> tests/ui/or_else_then_unwrap.rs:51:20 | ||
| | ||
LL | let _ = option.or_else(|| Some(vec!["fallback"])).unwrap(); // should trigger lint | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ||
| | ||
help: try | ||
| | ||
LL - let _ = option.or_else(|| Some(vec!["fallback"])).unwrap(); // should trigger lint | ||
LL + let _ = option.unwrap_or_else(|| vec!["fallback"]); // should trigger lint | ||
| | ||
|
||
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.
No idea how likely this is, but you could add a check for the
Ok
/Some
coming from a macro expansion -- e.g., the user can't really do anything about a case like:See this section for more info: https://doc.rust-lang.org/clippy/development/macro_expansions.html#spanctxt-method
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.
I put in a test case for this with
proc_macros::external!{
and it doesn't appear to be triggering the lint without addingin_external_macro
check... I'd like to understand why that is before adding the code to intentionally avoid - any idea why this would be getting ignored already? Is that test the right approach, or is there e.g. something special to know aboutproc_macros::external
?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.
Ah, right, that's because
methods/mod.rs
mostly filters out any method calls coming from an expansion:rust-clippy/clippy_lints/src/methods/mod.rs
Lines 4970 to 4972 in 95dd88d
rust-clippy/clippy_lints/src/methods/mod.rs
Lines 4852 to 4864 in 95dd88d
This might change in the future, but for now, the check I was talking about is indeed unnecessary.