]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/question_mark.rs
e252afce33fd058bc9a0921dec1bc5e6cbd8d62a
[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
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, span_lint_and_sugg, SpanlessEq,
11 };
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 Some((if_expr, body, else_)) = higher::if_block(&expr);
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 SpanlessEq::new(cx).ignore_fn().eq_expr(subject, block_expr);
68                         then {
69                             replacement = Some(format!("Some({}?)", receiver_str));
70                         }
71                     }
72                 } else if Self::moves_by_default(cx, subject) {
73                         replacement = Some(format!("{}.as_ref()?;", receiver_str));
74                 } else {
75                         replacement = Some(format!("{}?;", receiver_str));
76                 }
77
78                 if let Some(replacement_str) = replacement {
79                     span_lint_and_sugg(
80                         cx,
81                         QUESTION_MARK,
82                         expr.span,
83                         "this block may be rewritten with the `?` operator",
84                         "replace it with",
85                         replacement_str,
86                         applicability,
87                     )
88                }
89             }
90         }
91     }
92
93     fn check_if_let_some_and_early_return_none(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
94         if_chain! {
95             if let ExprKind::Match(subject, arms, source) = &expr.kind;
96             if *source == MatchSource::IfLetDesugar { contains_else_clause: true };
97             if Self::is_option(cx, subject);
98
99             if let PatKind::TupleStruct(path1, fields, None) = &arms[0].pat.kind;
100             if match_qpath(path1, &["Some"]);
101             if let PatKind::Binding(annot, _, bind, _) = &fields[0].kind;
102             let by_ref = matches!(annot, BindingAnnotation::Ref | BindingAnnotation::RefMut);
103
104             if let ExprKind::Block(block, None) = &arms[0].body.kind;
105             if block.stmts.is_empty();
106             if let Some(trailing_expr) = &block.expr;
107             if let ExprKind::Path(path) = &trailing_expr.kind;
108             if match_qpath(path, &[&bind.as_str()]);
109
110             if let PatKind::Wild = arms[1].pat.kind;
111             if Self::expression_returns_none(cx, arms[1].body);
112             then {
113                 let mut applicability = Applicability::MachineApplicable;
114                 let receiver_str = snippet_with_applicability(cx, subject.span, "..", &mut applicability);
115                 let replacement = format!(
116                     "{}{}?",
117                     receiver_str,
118                     if by_ref { ".as_ref()" } else { "" },
119                 );
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 moves_by_default(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool {
135         let expr_ty = cx.tables.expr_ty(expression);
136
137         !expr_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, expression.span)
138     }
139
140     fn is_option(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool {
141         let expr_ty = cx.tables.expr_ty(expression);
142
143         is_type_diagnostic_item(cx, expr_ty, sym!(option_type))
144     }
145
146     fn expression_returns_none(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool {
147         match expression.kind {
148             ExprKind::Block(ref block, _) => {
149                 if let Some(return_expression) = Self::return_expression(block) {
150                     return Self::expression_returns_none(cx, &return_expression);
151                 }
152
153                 false
154             },
155             ExprKind::Ret(Some(ref expr)) => Self::expression_returns_none(cx, expr),
156             ExprKind::Path(ref qp) => {
157                 if let Res::Def(DefKind::Ctor(def::CtorOf::Variant, def::CtorKind::Const), def_id) =
158                     cx.tables.qpath_res(qp, expression.hir_id)
159                 {
160                     return match_def_path(cx, def_id, &paths::OPTION_NONE);
161                 }
162
163                 false
164             },
165             _ => false,
166         }
167     }
168
169     fn return_expression<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
170         // Check if last expression is a return statement. Then, return the expression
171         if_chain! {
172             if block.stmts.len() == 1;
173             if let Some(expr) = block.stmts.iter().last();
174             if let StmtKind::Semi(ref expr) = expr.kind;
175             if let ExprKind::Ret(ret_expr) = expr.kind;
176             if let Some(ret_expr) = ret_expr;
177
178             then {
179                 return Some(ret_expr);
180             }
181         }
182
183         // Check for `return` without a semicolon.
184         if_chain! {
185             if block.stmts.is_empty();
186             if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.kind);
187             then {
188                 return Some(ret_expr);
189             }
190         }
191
192         None
193     }
194 }
195
196 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for QuestionMark {
197     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
198         Self::check_is_none_and_early_return_none(cx, expr);
199         Self::check_if_let_some_and_early_return_none(cx, expr);
200     }
201 }