]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/methods/unwrap_used.rs
Rollup merge of #105623 - compiler-errors:generator-type-size-fix, r=Nilstrieb
[rust.git] / src / tools / clippy / clippy_lints / src / methods / unwrap_used.rs
1 use clippy_utils::diagnostics::span_lint_and_help;
2 use clippy_utils::ty::is_type_diagnostic_item;
3 use clippy_utils::{is_in_cfg_test, is_lint_allowed};
4 use rustc_hir as hir;
5 use rustc_lint::LateContext;
6 use rustc_span::sym;
7
8 use super::{EXPECT_USED, UNWRAP_USED};
9
10 /// lint use of `unwrap()` or `unwrap_err` for `Result` and `unwrap()` for `Option`.
11 pub(super) fn check(
12     cx: &LateContext<'_>,
13     expr: &hir::Expr<'_>,
14     recv: &hir::Expr<'_>,
15     is_err: bool,
16     allow_unwrap_in_tests: bool,
17 ) {
18     let obj_ty = cx.typeck_results().expr_ty(recv).peel_refs();
19
20     let mess = if is_type_diagnostic_item(cx, obj_ty, sym::Option) && !is_err {
21         Some((UNWRAP_USED, "an `Option`", "None", ""))
22     } else if is_type_diagnostic_item(cx, obj_ty, sym::Result) {
23         Some((UNWRAP_USED, "a `Result`", if is_err { "Ok" } else { "Err" }, "an "))
24     } else {
25         None
26     };
27
28     let method_suffix = if is_err { "_err" } else { "" };
29
30     if allow_unwrap_in_tests && is_in_cfg_test(cx.tcx, expr.hir_id) {
31         return;
32     }
33
34     if let Some((lint, kind, none_value, none_prefix)) = mess {
35         let help = if is_lint_allowed(cx, EXPECT_USED, expr.hir_id) {
36             format!(
37                 "if you don't want to handle the `{none_value}` case gracefully, consider \
38                 using `expect{method_suffix}()` to provide a better panic message"
39             )
40         } else {
41             format!("if this value is {none_prefix}`{none_value}`, it will panic")
42         };
43
44         span_lint_and_help(
45             cx,
46             lint,
47             expr.span,
48             &format!("used `unwrap{method_suffix}()` on {kind} value"),
49             None,
50             &help,
51         );
52     }
53 }