]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/unwrap_or_else_default.rs
Auto merge of #7546 - mgeier:patch-1, r=giraffate
[rust.git] / clippy_lints / src / methods / unwrap_or_else_default.rs
1 //! Lint for `some_result_or_option.unwrap_or_else(Default::default)`
2
3 use super::UNWRAP_OR_ELSE_DEFAULT;
4 use clippy_utils::{
5     diagnostics::span_lint_and_sugg, is_trait_item, source::snippet_with_applicability, ty::is_type_diagnostic_item,
6 };
7 use rustc_errors::Applicability;
8 use rustc_hir as hir;
9 use rustc_lint::LateContext;
10 use rustc_span::sym;
11
12 pub(super) fn check<'tcx>(
13     cx: &LateContext<'tcx>,
14     expr: &'tcx hir::Expr<'_>,
15     recv: &'tcx hir::Expr<'_>,
16     u_arg: &'tcx hir::Expr<'_>,
17 ) {
18     // something.unwrap_or_else(Default::default)
19     // ^^^^^^^^^- recv          ^^^^^^^^^^^^^^^^- u_arg
20     // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- expr
21     let recv_ty = cx.typeck_results().expr_ty(recv);
22     let is_option = is_type_diagnostic_item(cx, recv_ty, sym::option_type);
23     let is_result = is_type_diagnostic_item(cx, recv_ty, sym::result_type);
24
25     if_chain! {
26         if is_option || is_result;
27         if is_trait_item(cx, u_arg, sym::Default);
28         then {
29             let mut applicability = Applicability::MachineApplicable;
30
31             span_lint_and_sugg(
32                 cx,
33                 UNWRAP_OR_ELSE_DEFAULT,
34                 expr.span,
35                 "use of `.unwrap_or_else(..)` to construct default value",
36                 "try",
37                 format!(
38                     "{}.unwrap_or_default()",
39                     snippet_with_applicability(cx, recv.span, "..", &mut applicability)
40                 ),
41                 applicability,
42             );
43         }
44     }
45 }