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