]> git.proxmox.com Git - rustc.git/blame - src/tools/clippy/clippy_lints/src/loops/for_loops_over_fallibles.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / loops / for_loops_over_fallibles.rs
CommitLineData
f20569fa 1use super::FOR_LOOPS_OVER_FALLIBLES;
cdc7bbd5
XL
2use clippy_utils::diagnostics::span_lint_and_help;
3use clippy_utils::source::snippet;
4use clippy_utils::ty::is_type_diagnostic_item;
f20569fa
XL
5use rustc_hir::{Expr, Pat};
6use rustc_lint::LateContext;
7use rustc_span::symbol::sym;
8
9/// Checks for `for` loops over `Option`s and `Result`s.
923072b8 10pub(super) fn check(cx: &LateContext<'_>, pat: &Pat<'_>, arg: &Expr<'_>, method_name: Option<&str>) {
f20569fa 11 let ty = cx.typeck_results().expr_ty(arg);
c295e0f8 12 if is_type_diagnostic_item(cx, ty, sym::Option) {
923072b8
FG
13 let help_string = if let Some(method_name) = method_name {
14 format!(
15 "consider replacing `for {0} in {1}.{method_name}()` with `if let Some({0}) = {1}`",
16 snippet(cx, pat.span, "_"),
17 snippet(cx, arg.span, "_")
18 )
19 } else {
20 format!(
21 "consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
22 snippet(cx, pat.span, "_"),
23 snippet(cx, arg.span, "_")
24 )
25 };
f20569fa
XL
26 span_lint_and_help(
27 cx,
28 FOR_LOOPS_OVER_FALLIBLES,
29 arg.span,
30 &format!(
31 "for loop over `{0}`, which is an `Option`. This is more readably written as an \
32 `if let` statement",
33 snippet(cx, arg.span, "_")
34 ),
35 None,
923072b8 36 &help_string,
f20569fa 37 );
c295e0f8 38 } else if is_type_diagnostic_item(cx, ty, sym::Result) {
923072b8
FG
39 let help_string = if let Some(method_name) = method_name {
40 format!(
41 "consider replacing `for {0} in {1}.{method_name}()` with `if let Ok({0}) = {1}`",
42 snippet(cx, pat.span, "_"),
43 snippet(cx, arg.span, "_")
44 )
45 } else {
46 format!(
47 "consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
48 snippet(cx, pat.span, "_"),
49 snippet(cx, arg.span, "_")
50 )
51 };
f20569fa
XL
52 span_lint_and_help(
53 cx,
54 FOR_LOOPS_OVER_FALLIBLES,
55 arg.span,
56 &format!(
57 "for loop over `{0}`, which is a `Result`. This is more readably written as an \
58 `if let` statement",
59 snippet(cx, arg.span, "_")
60 ),
61 None,
923072b8 62 &help_string,
f20569fa
XL
63 );
64 }
65}