]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/question_mark.rs
Rollup merge of #85833 - willcrichton:example-analyzer, r=jyn514
[rust.git] / src / tools / clippy / clippy_lints / src / question_mark.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::higher;
3 use clippy_utils::is_lang_ctor;
4 use clippy_utils::source::snippet_with_applicability;
5 use clippy_utils::sugg::Sugg;
6 use clippy_utils::ty::is_type_diagnostic_item;
7 use clippy_utils::{eq_expr_value, path_to_local, path_to_local_id};
8 use if_chain::if_chain;
9 use rustc_errors::Applicability;
10 use rustc_hir::LangItem::{OptionNone, OptionSome, ResultOk};
11 use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, PatKind, StmtKind};
12 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 use rustc_span::sym;
15
16 declare_clippy_lint! {
17     /// ### What it does
18     /// Checks for expressions that could be replaced by the question mark operator.
19     ///
20     /// ### Why is this bad?
21     /// Question mark usage is more idiomatic.
22     ///
23     /// ### Example
24     /// ```ignore
25     /// if option.is_none() {
26     ///     return None;
27     /// }
28     /// ```
29     ///
30     /// Could be written:
31     ///
32     /// ```ignore
33     /// option?;
34     /// ```
35     pub QUESTION_MARK,
36     style,
37     "checks for expressions that could be replaced by the question mark operator"
38 }
39
40 declare_lint_pass!(QuestionMark => [QUESTION_MARK]);
41
42 impl QuestionMark {
43     /// Checks if the given expression on the given context matches the following structure:
44     ///
45     /// ```ignore
46     /// if option.is_none() {
47     ///    return None;
48     /// }
49     /// ```
50     ///
51     /// ```ignore
52     /// if result.is_err() {
53     ///     return result;
54     /// }
55     /// ```
56     ///
57     /// If it matches, it will suggest to use the question mark operator instead
58     fn check_is_none_or_err_and_early_return(cx: &LateContext<'_>, expr: &Expr<'_>) {
59         if_chain! {
60             if let Some(higher::If { cond, then, r#else }) = higher::If::hir(expr);
61             if let ExprKind::MethodCall(segment, _, args, _) = &cond.kind;
62             if let Some(subject) = args.get(0);
63             if (Self::option_check_and_early_return(cx, subject, then) && segment.ident.name == sym!(is_none)) ||
64                 (Self::result_check_and_early_return(cx, subject, then) && segment.ident.name == sym!(is_err));
65             then {
66                 let mut applicability = Applicability::MachineApplicable;
67                 let receiver_str = &Sugg::hir_with_applicability(cx, subject, "..", &mut applicability);
68                 let mut replacement: Option<String> = None;
69                 if let Some(else_inner) = r#else {
70                     if_chain! {
71                         if let ExprKind::Block(block, None) = &else_inner.kind;
72                         if block.stmts.is_empty();
73                         if let Some(block_expr) = &block.expr;
74                         if eq_expr_value(cx, subject, block_expr);
75                         then {
76                             replacement = Some(format!("Some({}?)", receiver_str));
77                         }
78                     }
79                 } else if Self::moves_by_default(cx, subject)
80                     && !matches!(subject.kind, ExprKind::Call(..) | ExprKind::MethodCall(..))
81                 {
82                     replacement = Some(format!("{}.as_ref()?;", receiver_str));
83                 } else {
84                     replacement = Some(format!("{}?;", receiver_str));
85                 }
86
87                 if let Some(replacement_str) = replacement {
88                     span_lint_and_sugg(
89                         cx,
90                         QUESTION_MARK,
91                         expr.span,
92                         "this block may be rewritten with the `?` operator",
93                         "replace it with",
94                         replacement_str,
95                         applicability,
96                     );
97                 }
98             }
99         }
100     }
101
102     fn check_if_let_some_or_err_and_early_return(cx: &LateContext<'_>, expr: &Expr<'_>) {
103         if_chain! {
104             if let Some(higher::IfLet { let_pat, let_expr, if_then, if_else: Some(if_else) })
105                 = higher::IfLet::hir(cx, expr);
106             if let PatKind::TupleStruct(ref path1, fields, None) = let_pat.kind;
107             if (Self::option_check_and_early_return(cx, let_expr, if_else) && is_lang_ctor(cx, path1, OptionSome)) ||
108                 (Self::result_check_and_early_return(cx, let_expr, if_else) && is_lang_ctor(cx, path1, ResultOk));
109
110             if let PatKind::Binding(annot, bind_id, _, _) = fields[0].kind;
111             let by_ref = matches!(annot, BindingAnnotation::Ref | BindingAnnotation::RefMut);
112             if let ExprKind::Block(block, None) = if_then.kind;
113             if block.stmts.is_empty();
114             if let Some(trailing_expr) = &block.expr;
115             if path_to_local_id(trailing_expr, bind_id);
116             then {
117                 let mut applicability = Applicability::MachineApplicable;
118                 let receiver_str = snippet_with_applicability(cx, let_expr.span, "..", &mut applicability);
119                 let replacement = format!("{}{}?", receiver_str, if by_ref { ".as_ref()" } else { "" },);
120
121                 span_lint_and_sugg(
122                     cx,
123                     QUESTION_MARK,
124                     expr.span,
125                     "this if-let-else may be rewritten with the `?` operator",
126                     "replace it with",
127                     replacement,
128                     applicability,
129                 );
130             }
131         }
132     }
133
134     fn result_check_and_early_return(cx: &LateContext<'_>, expr: &Expr<'_>, nested_expr: &Expr<'_>) -> bool {
135         Self::is_result(cx, expr) && Self::expression_returns_unmodified_err(cx, nested_expr, expr)
136     }
137
138     fn option_check_and_early_return(cx: &LateContext<'_>, expr: &Expr<'_>, nested_expr: &Expr<'_>) -> bool {
139         Self::is_option(cx, expr) && Self::expression_returns_none(cx, nested_expr)
140     }
141
142     fn moves_by_default(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
143         let expr_ty = cx.typeck_results().expr_ty(expression);
144
145         !expr_ty.is_copy_modulo_regions(cx.tcx.at(expression.span), cx.param_env)
146     }
147
148     fn is_option(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
149         let expr_ty = cx.typeck_results().expr_ty(expression);
150
151         is_type_diagnostic_item(cx, expr_ty, sym::Option)
152     }
153
154     fn is_result(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
155         let expr_ty = cx.typeck_results().expr_ty(expression);
156
157         is_type_diagnostic_item(cx, expr_ty, sym::Result)
158     }
159
160     fn expression_returns_none(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
161         match expression.kind {
162             ExprKind::Block(block, _) => {
163                 if let Some(return_expression) = Self::return_expression(block) {
164                     return Self::expression_returns_none(cx, return_expression);
165                 }
166
167                 false
168             },
169             ExprKind::Ret(Some(expr)) => Self::expression_returns_none(cx, expr),
170             ExprKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
171             _ => false,
172         }
173     }
174
175     fn expression_returns_unmodified_err(
176         cx: &LateContext<'_>,
177         expression: &Expr<'_>,
178         origin_hir_id: &Expr<'_>,
179     ) -> bool {
180         match expression.kind {
181             ExprKind::Block(block, _) => {
182                 if let Some(return_expression) = Self::return_expression(block) {
183                     return Self::expression_returns_unmodified_err(cx, return_expression, origin_hir_id);
184                 }
185
186                 false
187             },
188             ExprKind::Ret(Some(expr)) | ExprKind::Call(expr, _) => {
189                 Self::expression_returns_unmodified_err(cx, expr, origin_hir_id)
190             },
191             ExprKind::Path(_) => path_to_local(expression) == path_to_local(origin_hir_id),
192             _ => false,
193         }
194     }
195
196     fn return_expression<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
197         // Check if last expression is a return statement. Then, return the expression
198         if_chain! {
199             if block.stmts.len() == 1;
200             if let Some(expr) = block.stmts.iter().last();
201             if let StmtKind::Semi(expr) = expr.kind;
202             if let ExprKind::Ret(Some(ret_expr)) = expr.kind;
203
204             then {
205                 return Some(ret_expr);
206             }
207         }
208
209         // Check for `return` without a semicolon.
210         if_chain! {
211             if block.stmts.is_empty();
212             if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.kind);
213             then {
214                 return Some(ret_expr);
215             }
216         }
217
218         None
219     }
220 }
221
222 impl<'tcx> LateLintPass<'tcx> for QuestionMark {
223     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
224         Self::check_is_none_or_err_and_early_return(cx, expr);
225         Self::check_if_let_some_or_err_and_early_return(cx, expr);
226     }
227 }