-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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
unwrap_or_else_default
-> unwrap_or_default
and improve resulting lint
#10120
Changes from 2 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 | ||||
---|---|---|---|---|---|---|
@@ -1,16 +1,17 @@ | ||||||
use clippy_utils::diagnostics::span_lint_and_sugg; | ||||||
use clippy_utils::eager_or_lazy::switch_to_lazy_eval; | ||||||
use clippy_utils::source::snippet_with_context; | ||||||
use clippy_utils::ty::{implements_trait, is_type_diagnostic_item}; | ||||||
use clippy_utils::{contains_return, is_trait_item, last_path_segment}; | ||||||
use clippy_utils::ty::{expr_type_is_certain, implements_trait, is_type_diagnostic_item}; | ||||||
use clippy_utils::{contains_return, is_default_equivalent, is_default_equivalent_call, last_path_segment}; | ||||||
use if_chain::if_chain; | ||||||
use rustc_errors::Applicability; | ||||||
use rustc_hir as hir; | ||||||
use rustc_lint::LateContext; | ||||||
use rustc_middle::ty; | ||||||
use rustc_span::source_map::Span; | ||||||
use rustc_span::symbol::{kw, sym, Symbol}; | ||||||
use rustc_span::symbol::{self, sym, Symbol}; | ||||||
use {rustc_ast as ast, rustc_hir as hir}; | ||||||
|
||||||
use super::OR_FUN_CALL; | ||||||
use super::{OR_FUN_CALL, UNWRAP_OR_DEFAULT}; | ||||||
|
||||||
/// Checks for the `OR_FUN_CALL` lint. | ||||||
#[allow(clippy::too_many_lines)] | ||||||
|
@@ -24,44 +25,64 @@ pub(super) fn check<'tcx>( | |||||
) { | ||||||
/// Checks for `unwrap_or(T::new())`, `unwrap_or(T::default())`, | ||||||
/// `or_insert(T::new())` or `or_insert(T::default())`. | ||||||
/// Similarly checks for `unwrap_or_else(T::new)`, `unwrap_or_else(T::default)`, | ||||||
/// `or_insert_with(T::new)` or `or_insert_with(T::default)`. | ||||||
#[allow(clippy::too_many_arguments)] | ||||||
fn check_unwrap_or_default( | ||||||
cx: &LateContext<'_>, | ||||||
name: &str, | ||||||
receiver: &hir::Expr<'_>, | ||||||
fun: &hir::Expr<'_>, | ||||||
arg: &hir::Expr<'_>, | ||||||
or_has_args: bool, | ||||||
call_expr: Option<&hir::Expr<'_>>, | ||||||
span: Span, | ||||||
method_span: Span, | ||||||
) -> bool { | ||||||
let is_default_default = || is_trait_item(cx, fun, sym::Default); | ||||||
if !expr_type_is_certain(cx, receiver) { | ||||||
return false; | ||||||
} | ||||||
|
||||||
let is_new = |fun: &hir::Expr<'_>| { | ||||||
if let hir::ExprKind::Path(ref qpath) = fun.kind { | ||||||
let path = last_path_segment(qpath).ident.name; | ||||||
matches!(path, sym::new) | ||||||
} else { | ||||||
false | ||||||
} | ||||||
}; | ||||||
|
||||||
let implements_default = |arg, default_trait_id| { | ||||||
let arg_ty = cx.typeck_results().expr_ty(arg); | ||||||
implements_trait(cx, arg_ty, default_trait_id, &[]) | ||||||
let output_type_implements_default = |fun| { | ||||||
let fun_ty = cx.typeck_results().expr_ty(fun); | ||||||
if let ty::FnDef(def_id, substs) = fun_ty.kind() { | ||||||
let output_ty = cx.tcx.fn_sig(def_id).subst(cx.tcx, substs).skip_binder().output(); | ||||||
cx.tcx | ||||||
.get_diagnostic_item(sym::Default) | ||||||
.map_or(false, |default_trait_id| { | ||||||
implements_trait(cx, output_ty, default_trait_id, substs) | ||||||
}) | ||||||
} else { | ||||||
false | ||||||
} | ||||||
}; | ||||||
|
||||||
if_chain! { | ||||||
if !or_has_args; | ||||||
if let Some(sugg) = match name { | ||||||
"unwrap_or" => Some("unwrap_or_default"), | ||||||
"or_insert" => Some("or_default"), | ||||||
if let Some(sugg) = match (name, call_expr.is_some()) { | ||||||
("unwrap_or", true) | ("unwrap_or_else", false) => Some("unwrap_or_default"), | ||||||
("or_insert", true) | ("or_insert_with", false) => Some("or_default"), | ||||||
_ => None, | ||||||
}; | ||||||
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 if statement could be replaced by an early return (the compiler probably optimizes this, but just to be sure) 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. Is the change I made the one you had in mind? 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. Yes :) |
||||||
if let hir::ExprKind::Path(ref qpath) = fun.kind; | ||||||
if let Some(default_trait_id) = cx.tcx.get_diagnostic_item(sym::Default); | ||||||
let path = last_path_segment(qpath).ident.name; | ||||||
// needs to target Default::default in particular or be *::new and have a Default impl | ||||||
// available | ||||||
if (matches!(path, kw::Default) && is_default_default()) | ||||||
|| (matches!(path, sym::new) && implements_default(arg, default_trait_id)); | ||||||
|
||||||
if (is_new(fun) && output_type_implements_default(fun)) | ||||||
|| match call_expr { | ||||||
Some(call_expr) => is_default_equivalent(cx, call_expr), | ||||||
None => is_default_equivalent_call(cx, fun) || closure_body_returns_empty_to_string(cx, fun), | ||||||
}; | ||||||
then { | ||||||
span_lint_and_sugg( | ||||||
cx, | ||||||
OR_FUN_CALL, | ||||||
UNWRAP_OR_DEFAULT, | ||||||
method_span.with_hi(span.hi()), | ||||||
&format!("use of `{name}` followed by a call to `{path}`"), | ||||||
&format!("use of `{name}` to construct default value"), | ||||||
"try", | ||||||
format!("{sugg}()"), | ||||||
Applicability::MachineApplicable, | ||||||
|
@@ -168,11 +189,16 @@ pub(super) fn check<'tcx>( | |||||
match inner_arg.kind { | ||||||
hir::ExprKind::Call(fun, or_args) => { | ||||||
let or_has_args = !or_args.is_empty(); | ||||||
if !check_unwrap_or_default(cx, name, fun, arg, or_has_args, expr.span, method_span) { | ||||||
if or_has_args | ||||||
|| !check_unwrap_or_default(cx, name, receiver, fun, Some(inner_arg), expr.span, method_span) | ||||||
{ | ||||||
let fun_span = if or_has_args { None } else { Some(fun.span) }; | ||||||
check_general_case(cx, name, method_span, receiver, arg, None, expr.span, fun_span); | ||||||
} | ||||||
}, | ||||||
hir::ExprKind::Path(..) | hir::ExprKind::Closure(..) => { | ||||||
check_unwrap_or_default(cx, name, receiver, inner_arg, None, expr.span, method_span); | ||||||
}, | ||||||
hir::ExprKind::Index(..) | hir::ExprKind::MethodCall(..) => { | ||||||
check_general_case(cx, name, method_span, receiver, arg, None, expr.span, None); | ||||||
}, | ||||||
|
@@ -189,3 +215,22 @@ pub(super) fn check<'tcx>( | |||||
} | ||||||
} | ||||||
} | ||||||
|
||||||
fn closure_body_returns_empty_to_string(cx: &LateContext<'_>, e: &hir::Expr<'_>) -> bool { | ||||||
if let hir::ExprKind::Closure(&hir::Closure { body, .. }) = e.kind { | ||||||
let body = cx.tcx.hir().body(body); | ||||||
|
||||||
if body.params.is_empty() | ||||||
&& let hir::Expr{ kind, .. } = &body.value | ||||||
&& let hir::ExprKind::MethodCall(hir::PathSegment {ident, ..}, self_arg, _, _) = kind | ||||||
&& ident == &symbol::Ident::from_str("to_string") | ||||||
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. Unnecessary allocation here 🐄
Suggested change
|
||||||
&& let hir::Expr{ kind, .. } = self_arg | ||||||
&& let hir::ExprKind::Lit(lit) = kind | ||||||
&& let ast::LitKind::Str(symbol::kw::Empty, _) = lit.node | ||||||
{ | ||||||
return true; | ||||||
} | ||||||
} | ||||||
|
||||||
false | ||||||
} |
This file was deleted.
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.
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.
Both are correct and used a similar amount of times in rustc (512 without the comma vs 680 with the comma). The preferred spelling differs from place to place though.
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.
Just a personal preference, but I feel like it's weird to have 2 punctuation signs right next to each other and it kinda worsens readability.
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 personally find it easier to read as it keeps the punctuation mark only being used at the end of a sentence. That's subjective though ^^
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.
@blyxyas Personally, I agree with you 100%.
But literally every English writing guide I have consulted says to put a ',' after "e.g.".
So I think the question comes down to: should Clippy comments follow English writing guides?
(And, to state the obvious, this is a total bike shed. 😀)
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'm fine with either. It's bikeshedding and won't cause confusion anyway.
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.
Mmmm... Guess it doesn't matter. It just looks weird, I don't know and honestly, it isn't that big of a problem.
We can continue designing the power plant, do what you consider the best 🤠