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