]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/needless_question_mark.rs
Rollup merge of #87759 - m-ou-se:linux-process-sealed, r=jyn514
[rust.git] / src / tools / clippy / clippy_lints / src / needless_question_mark.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::is_lang_ctor;
3 use clippy_utils::source::snippet;
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::LangItem::{OptionSome, ResultOk};
7 use rustc_hir::{Body, Expr, ExprKind, LangItem, MatchSource, QPath};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::ty::TyS;
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11
12 declare_clippy_lint! {
13     /// ### What it does
14     /// Suggests alternatives for useless applications of `?` in terminating expressions
15     ///
16     /// ### Why is this bad?
17     /// There's no reason to use `?` to short-circuit when execution of the body will end there anyway.
18     ///
19     /// ### Example
20     /// ```rust
21     /// struct TO {
22     ///     magic: Option<usize>,
23     /// }
24     ///
25     /// fn f(to: TO) -> Option<usize> {
26     ///     Some(to.magic?)
27     /// }
28     ///
29     /// struct TR {
30     ///     magic: Result<usize, bool>,
31     /// }
32     ///
33     /// fn g(tr: Result<TR, bool>) -> Result<usize, bool> {
34     ///     tr.and_then(|t| Ok(t.magic?))
35     /// }
36     ///
37     /// ```
38     /// Use instead:
39     /// ```rust
40     /// struct TO {
41     ///     magic: Option<usize>,
42     /// }
43     ///
44     /// fn f(to: TO) -> Option<usize> {
45     ///    to.magic
46     /// }
47     ///
48     /// struct TR {
49     ///     magic: Result<usize, bool>,
50     /// }
51     ///
52     /// fn g(tr: Result<TR, bool>) -> Result<usize, bool> {
53     ///     tr.and_then(|t| t.magic)
54     /// }
55     /// ```
56     pub NEEDLESS_QUESTION_MARK,
57     complexity,
58     "Suggest `value.inner_option` instead of `Some(value.inner_option?)`. The same goes for `Result<T, E>`."
59 }
60
61 declare_lint_pass!(NeedlessQuestionMark => [NEEDLESS_QUESTION_MARK]);
62
63 impl LateLintPass<'_> for NeedlessQuestionMark {
64     /*
65      * The question mark operator is compatible with both Result<T, E> and Option<T>,
66      * from Rust 1.13 and 1.22 respectively.
67      */
68
69     /*
70      * What do we match:
71      * Expressions that look like this:
72      * Some(option?), Ok(result?)
73      *
74      * Where do we match:
75      *      Last expression of a body
76      *      Return statement
77      *      A body's value (single line closure)
78      *
79      * What do we not match:
80      *      Implicit calls to `from(..)` on the error value
81      */
82
83     fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ Expr<'_>) {
84         if let ExprKind::Ret(Some(e)) = expr.kind {
85             check(cx, e);
86         }
87     }
88
89     fn check_body(&mut self, cx: &LateContext<'_>, body: &'_ Body<'_>) {
90         check(cx, body.value.peel_blocks());
91     }
92 }
93
94 fn check(cx: &LateContext<'_>, expr: &Expr<'_>) {
95     let inner_expr = if_chain! {
96         if let ExprKind::Call(path, [arg]) = &expr.kind;
97         if let ExprKind::Path(ref qpath) = &path.kind;
98         if is_lang_ctor(cx, qpath, OptionSome) || is_lang_ctor(cx, qpath, ResultOk);
99         if let ExprKind::Match(inner_expr_with_q, _, MatchSource::TryDesugar) = &arg.kind;
100         if let ExprKind::Call(called, [inner_expr]) = &inner_expr_with_q.kind;
101         if let ExprKind::Path(QPath::LangItem(LangItem::TryTraitBranch, _)) = &called.kind;
102         if expr.span.ctxt() == inner_expr.span.ctxt();
103         let expr_ty = cx.typeck_results().expr_ty(expr);
104         let inner_ty = cx.typeck_results().expr_ty(inner_expr);
105         if TyS::same_type(expr_ty, inner_ty);
106         then { inner_expr } else { return; }
107     };
108     span_lint_and_sugg(
109         cx,
110         NEEDLESS_QUESTION_MARK,
111         expr.span,
112         "question mark operator is useless here",
113         "try",
114         format!("{}", snippet(cx, inner_expr.span, r#""...""#)),
115         Applicability::MachineApplicable,
116     );
117 }