]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/methods/unwrap_used.rs
Rollup merge of #97130 - notriddle:notriddle/collect-trait-impls-dup, r=GuillaumeGomez
[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::is_in_test_function;
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use rustc_hir as hir;
5 use rustc_lint::LateContext;
6 use rustc_span::sym;
7
8 use super::UNWRAP_USED;
9
10 /// lint use of `unwrap()` for `Option`s and `Result`s
11 pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr<'_>, allow_unwrap_in_tests: bool) {
12     let obj_ty = cx.typeck_results().expr_ty(recv).peel_refs();
13
14     let mess = if is_type_diagnostic_item(cx, obj_ty, sym::Option) {
15         Some((UNWRAP_USED, "an Option", "None"))
16     } else if is_type_diagnostic_item(cx, obj_ty, sym::Result) {
17         Some((UNWRAP_USED, "a Result", "Err"))
18     } else {
19         None
20     };
21
22     if allow_unwrap_in_tests && is_in_test_function(cx.tcx, expr.hir_id) {
23         return;
24     }
25
26     if let Some((lint, kind, none_value)) = mess {
27         span_lint_and_help(
28             cx,
29             lint,
30             expr.span,
31             &format!("used `unwrap()` on `{}` value", kind,),
32             None,
33             &format!(
34                 "if you don't want to handle the `{}` case gracefully, consider \
35                 using `expect()` to provide a better panic message",
36                 none_value,
37             ),
38         );
39     }
40 }