]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/question_mark.rs
Rollup merge of #79051 - LeSeulArtichaut:if-let-guard, r=matthewjasper
[rust.git] / clippy_lints / src / question_mark.rs
1 use if_chain::if_chain;
2 use rustc_errors::Applicability;
3 use rustc_hir::def::{DefKind, Res};
4 use rustc_hir::{def, BindingAnnotation, Block, Expr, ExprKind, MatchSource, PatKind, StmtKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7 use rustc_span::sym;
8
9 use crate::utils::sugg::Sugg;
10 use crate::utils::{
11     eq_expr_value, higher, is_type_diagnostic_item, match_def_path, match_qpath, paths, snippet_with_applicability,
12     span_lint_and_sugg,
13 };
14
15 declare_clippy_lint! {
16     /// **What it does:** Checks for expressions that could be replaced by the question mark operator.
17     ///
18     /// **Why is this bad?** Question mark usage is more idiomatic.
19     ///
20     /// **Known problems:** None
21     ///
22     /// **Example:**
23     /// ```ignore
24     /// if option.is_none() {
25     ///     return None;
26     /// }
27     /// ```
28     ///
29     /// Could be written:
30     ///
31     /// ```ignore
32     /// option?;
33     /// ```
34     pub QUESTION_MARK,
35     style,
36     "checks for expressions that could be replaced by the question mark operator"
37 }
38
39 declare_lint_pass!(QuestionMark => [QUESTION_MARK]);
40
41 impl QuestionMark {
42     /// Checks if the given expression on the given context matches the following structure:
43     ///
44     /// ```ignore
45     /// if option.is_none() {
46     ///    return None;
47     /// }
48     /// ```
49     ///
50     /// If it matches, it will suggest to use the question mark operator instead
51     fn check_is_none_and_early_return_none(cx: &LateContext<'_>, expr: &Expr<'_>) {
52         if_chain! {
53             if let Some((if_expr, body, else_)) = higher::if_block(&expr);
54             if let ExprKind::MethodCall(segment, _, args, _) = &if_expr.kind;
55             if segment.ident.name == sym!(is_none);
56             if Self::expression_returns_none(cx, body);
57             if let Some(subject) = args.get(0);
58             if Self::is_option(cx, subject);
59
60             then {
61                 let mut applicability = Applicability::MachineApplicable;
62                 let receiver_str = &Sugg::hir_with_applicability(cx, subject, "..", &mut applicability);
63                 let mut replacement: Option<String> = None;
64                 if let Some(else_) = else_ {
65                     if_chain! {
66                         if let ExprKind::Block(block, None) = &else_.kind;
67                         if block.stmts.is_empty();
68                         if let Some(block_expr) = &block.expr;
69                         if eq_expr_value(cx, subject, block_expr);
70                         then {
71                             replacement = Some(format!("Some({}?)", receiver_str));
72                         }
73                     }
74                 } else if Self::moves_by_default(cx, subject)
75                     && !matches!(subject.kind, ExprKind::Call(..) | ExprKind::MethodCall(..))
76                 {
77                     replacement = Some(format!("{}.as_ref()?;", receiver_str));
78                 } else {
79                     replacement = Some(format!("{}?;", receiver_str));
80                 }
81
82                 if let Some(replacement_str) = replacement {
83                     span_lint_and_sugg(
84                         cx,
85                         QUESTION_MARK,
86                         expr.span,
87                         "this block may be rewritten with the `?` operator",
88                         "replace it with",
89                         replacement_str,
90                         applicability,
91                     )
92                 }
93             }
94         }
95     }
96
97     fn check_if_let_some_and_early_return_none(cx: &LateContext<'_>, expr: &Expr<'_>) {
98         if_chain! {
99             if let ExprKind::Match(subject, arms, source) = &expr.kind;
100             if *source == MatchSource::IfLetDesugar { contains_else_clause: true };
101             if Self::is_option(cx, subject);
102
103             if let PatKind::TupleStruct(path1, fields, None) = &arms[0].pat.kind;
104             if match_qpath(path1, &["Some"]);
105             if let PatKind::Binding(annot, _, bind, _) = &fields[0].kind;
106             let by_ref = matches!(annot, BindingAnnotation::Ref | BindingAnnotation::RefMut);
107
108             if let ExprKind::Block(block, None) = &arms[0].body.kind;
109             if block.stmts.is_empty();
110             if let Some(trailing_expr) = &block.expr;
111             if let ExprKind::Path(path) = &trailing_expr.kind;
112             if match_qpath(path, &[&bind.as_str()]);
113
114             if let PatKind::Wild = arms[1].pat.kind;
115             if Self::expression_returns_none(cx, arms[1].body);
116             then {
117                 let mut applicability = Applicability::MachineApplicable;
118                 let receiver_str = snippet_with_applicability(cx, subject.span, "..", &mut applicability);
119                 let replacement = format!(
120                     "{}{}?",
121                     receiver_str,
122                     if by_ref { ".as_ref()" } else { "" },
123                 );
124
125                 span_lint_and_sugg(
126                     cx,
127                     QUESTION_MARK,
128                     expr.span,
129                     "this if-let-else may be rewritten with the `?` operator",
130                     "replace it with",
131                     replacement,
132                     applicability,
133                 )
134             }
135         }
136     }
137
138     fn moves_by_default(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
139         let expr_ty = cx.typeck_results().expr_ty(expression);
140
141         !expr_ty.is_copy_modulo_regions(cx.tcx.at(expression.span), cx.param_env)
142     }
143
144     fn is_option(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
145         let expr_ty = cx.typeck_results().expr_ty(expression);
146
147         is_type_diagnostic_item(cx, expr_ty, sym::option_type)
148     }
149
150     fn expression_returns_none(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
151         match expression.kind {
152             ExprKind::Block(ref block, _) => {
153                 if let Some(return_expression) = Self::return_expression(block) {
154                     return Self::expression_returns_none(cx, &return_expression);
155                 }
156
157                 false
158             },
159             ExprKind::Ret(Some(ref expr)) => Self::expression_returns_none(cx, expr),
160             ExprKind::Path(ref qp) => {
161                 if let Res::Def(DefKind::Ctor(def::CtorOf::Variant, def::CtorKind::Const), def_id) =
162                     cx.qpath_res(qp, expression.hir_id)
163                 {
164                     return match_def_path(cx, def_id, &paths::OPTION_NONE);
165                 }
166
167                 false
168             },
169             _ => false,
170         }
171     }
172
173     fn return_expression<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
174         // Check if last expression is a return statement. Then, return the expression
175         if_chain! {
176             if block.stmts.len() == 1;
177             if let Some(expr) = block.stmts.iter().last();
178             if let StmtKind::Semi(ref expr) = expr.kind;
179             if let ExprKind::Ret(Some(ret_expr)) = expr.kind;
180
181             then {
182                 return Some(ret_expr);
183             }
184         }
185
186         // Check for `return` without a semicolon.
187         if_chain! {
188             if block.stmts.is_empty();
189             if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.kind);
190             then {
191                 return Some(ret_expr);
192             }
193         }
194
195         None
196     }
197 }
198
199 impl<'tcx> LateLintPass<'tcx> for QuestionMark {
200     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
201         Self::check_is_none_and_early_return_none(cx, expr);
202         Self::check_if_let_some_and_early_return_none(cx, expr);
203     }
204 }