Skip to content

fix: manual_unwrap_or_default suggests error when expression is a None variant #12688

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

Closed
Closed
Show file tree
Hide file tree
Changes from 2 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
38 changes: 37 additions & 1 deletion clippy_lints/src/manual_unwrap_or_default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use rustc_errors::Applicability;
use rustc_hir::def::Res;
use rustc_hir::{Arm, Expr, ExprKind, HirId, LangItem, MatchSource, Pat, PatKind, QPath};
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::ty::GenericArgKind;
use rustc_middle::ty::{self, GenericArgKind};
use rustc_session::declare_lint_pass;
use rustc_span::sym;

Expand Down Expand Up @@ -148,6 +148,42 @@ fn handle<'tcx>(cx: &LateContext<'tcx>, if_let_or_match: IfLetOrMatch<'tcx>, exp
&& is_default_equivalent(cx, body_none)
&& let Some(receiver) = Sugg::hir_opt(cx, condition).map(Sugg::maybe_par)
{
// We check if the expression is not a None variant
if let Some(none_def_id) = cx.tcx.lang_items().option_none_variant() {
if let ExprKind::Path(QPath::Resolved(_, path)) = &condition.kind {
if let Some(def_id) = path.res.opt_def_id() {
if cx.tcx.parent(def_id) == none_def_id {
Comment on lines +152 to +155
Copy link
Contributor

Choose a reason for hiding this comment

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

This is equivalent to path_res(cx, condition).opt_def_id().is_some_and(|id| Some(cx.tcx.parent(id)) == cx.tcx.lang_items().option_none_variant())

return span_lint_and_sugg(
cx,
MANUAL_UNWRAP_OR_DEFAULT,
expr.span,
format!("{expr_name} can be simplified with `.unwrap_or_default()`"),
"replace it with",
format!("{receiver}::</* Type */>.unwrap_or_default()"),
Copy link
Contributor

Choose a reason for hiding this comment

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

You can print any Ty which will print the type's full name. The following should work:

if let ty::Adt(_, args) = cx.typeck_results().expr_ty(expr).kind()
  && let Some(arg) = args.first()
  && let Some(arg_ty) = arg.as_type()
{
  format!("{receiver}::<{}>.unwrap_or_default()", arg_ty)
}

Applicability::HasPlaceholders,
);
}
}
}
}

// We check if the expression is not a method or function with a unspecified return type
if let ExprKind::MethodCall(_, expr, _, _) = &condition.kind {
if let ty::Adt(_, substs) = cx.typeck_results().expr_ty(expr).kind() {
if let Some(ok_type) = substs.first() {
return span_lint_and_sugg(
cx,
MANUAL_UNWRAP_OR_DEFAULT,
expr.span,
format!("{expr_name} can be simplified with `.unwrap_or_default()`"),
format!("explicit the type {ok_type} and replace your expression with"),
format!("{receiver}.unwrap_or_default()"),
Applicability::Unspecified,
);
}
}
}
Comment on lines +170 to +185
Copy link
Contributor

Choose a reason for hiding this comment

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

What are you trying to catch with this? This looks like it will just catch any scrutinee that happens to be a method call.

Copy link
Author

Choose a reason for hiding this comment

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

I catch all methods and functions that return a generic type that can't be inferred from it's arguments (e.g. "1".parse()) ?

Copy link
Contributor

Choose a reason for hiding this comment

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

We have clippy_utils::ty::expr_type_is_certain for that.


// Machine applicable only if there are no comments present
let applicability = if span_contains_comment(cx.sess().source_map(), expr.span) {
Applicability::MaybeIncorrect
Expand Down
74 changes: 0 additions & 74 deletions tests/ui/manual_unwrap_or_default.fixed

This file was deleted.

16 changes: 16 additions & 0 deletions tests/ui/manual_unwrap_or_default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,19 @@ fn issue_12569() {
0
};
}

//@no-rustfix
fn issue_12670() {
// no auto: type not found
#[allow(clippy::match_result_ok)]
let _ = if let Some(x) = "1".parse().ok() {
x
} else {
i32::default()
};
let _ = if let Some(x) = None { x } else { i32::default() };
// auto fix with unwrap_or_default
let a: Option<i32> = None;
let _ = if let Some(x) = a { x } else { i32::default() };
let _ = if let Some(x) = Some(99) { x } else { i32::default() };
}
26 changes: 25 additions & 1 deletion tests/ui/manual_unwrap_or_default.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -62,5 +62,29 @@ LL | | _ => 0,
LL | | },
| |_________^ help: replace it with: `(*b).unwrap_or_default()`

error: aborting due to 6 previous errors
error: if let can be simplified with `.unwrap_or_default()`
--> tests/ui/manual_unwrap_or_default.rs:104:30
|
LL | let _ = if let Some(x) = "1".parse().ok() {
| ^^^^^^^^^^^ help: explicit the type i32 and replace your expression with: `"1".parse().ok().unwrap_or_default()`

error: if let can be simplified with `.unwrap_or_default()`
--> tests/ui/manual_unwrap_or_default.rs:109:13
|
LL | let _ = if let Some(x) = None { x } else { i32::default() };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `None::</* Type */>.unwrap_or_default()`

error: if let can be simplified with `.unwrap_or_default()`
--> tests/ui/manual_unwrap_or_default.rs:112:13
|
LL | let _ = if let Some(x) = a { x } else { i32::default() };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `a.unwrap_or_default()`

error: if let can be simplified with `.unwrap_or_default()`
--> tests/ui/manual_unwrap_or_default.rs:113:13
|
LL | let _ = if let Some(x) = Some(99) { x } else { i32::default() };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace it with: `Some(99).unwrap_or_default()`

error: aborting due to 10 previous errors