]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/question_mark.rs
Auto merge of #5040 - JohnTitor:rustup-0111, r=flip1995
[rust.git] / clippy_lints / src / question_mark.rs
1 use if_chain::if_chain;
2 use rustc::lint::{LateContext, LateLintPass};
3 use rustc_errors::Applicability;
4 use rustc_hir::def::{DefKind, Res};
5 use rustc_hir::*;
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7
8 use crate::utils::paths::*;
9 use crate::utils::sugg::Sugg;
10 use crate::utils::{higher, match_def_path, match_type, span_lint_and_then, SpanlessEq};
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks for expressions that could be replaced by the question mark operator.
14     ///
15     /// **Why is this bad?** Question mark usage is more idiomatic.
16     ///
17     /// **Known problems:** None
18     ///
19     /// **Example:**
20     /// ```ignore
21     /// if option.is_none() {
22     ///     return None;
23     /// }
24     /// ```
25     ///
26     /// Could be written:
27     ///
28     /// ```ignore
29     /// option?;
30     /// ```
31     pub QUESTION_MARK,
32     style,
33     "checks for expressions that could be replaced by the question mark operator"
34 }
35
36 declare_lint_pass!(QuestionMark => [QUESTION_MARK]);
37
38 impl QuestionMark {
39     /// Checks if the given expression on the given context matches the following structure:
40     ///
41     /// ```ignore
42     /// if option.is_none() {
43     ///    return None;
44     /// }
45     /// ```
46     ///
47     /// If it matches, it will suggest to use the question mark operator instead
48     fn check_is_none_and_early_return_none(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
49         if_chain! {
50             if let Some((if_expr, body, else_)) = higher::if_block(&expr);
51             if let ExprKind::MethodCall(segment, _, args) = &if_expr.kind;
52             if segment.ident.name == sym!(is_none);
53             if Self::expression_returns_none(cx, body);
54             if let Some(subject) = args.get(0);
55             if Self::is_option(cx, subject);
56
57             then {
58                 let receiver_str = &Sugg::hir(cx, subject, "..");
59                 let mut replacement: Option<String> = None;
60                 if let Some(else_) = else_ {
61                     if_chain! {
62                         if let ExprKind::Block(block, None) = &else_.kind;
63                         if block.stmts.is_empty();
64                         if let Some(block_expr) = &block.expr;
65                         if SpanlessEq::new(cx).ignore_fn().eq_expr(subject, block_expr);
66                         then {
67                             replacement = Some(format!("Some({}?)", receiver_str));
68                         }
69                     }
70                 } else if Self::moves_by_default(cx, subject) {
71                         replacement = Some(format!("{}.as_ref()?;", receiver_str));
72                 } else {
73                         replacement = Some(format!("{}?;", receiver_str));
74                 }
75
76                 if let Some(replacement_str) = replacement {
77                     span_lint_and_then(
78                         cx,
79                         QUESTION_MARK,
80                         expr.span,
81                         "this block may be rewritten with the `?` operator",
82                         |db| {
83                             db.span_suggestion(
84                                 expr.span,
85                                 "replace_it_with",
86                                 replacement_str,
87                                 Applicability::MaybeIncorrect, // snippet
88                             );
89                         }
90                     )
91                }
92             }
93         }
94     }
95
96     fn moves_by_default(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool {
97         let expr_ty = cx.tables.expr_ty(expression);
98
99         !expr_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, expression.span)
100     }
101
102     fn is_option(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool {
103         let expr_ty = cx.tables.expr_ty(expression);
104
105         match_type(cx, expr_ty, &OPTION)
106     }
107
108     fn expression_returns_none(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool {
109         match expression.kind {
110             ExprKind::Block(ref block, _) => {
111                 if let Some(return_expression) = Self::return_expression(block) {
112                     return Self::expression_returns_none(cx, &return_expression);
113                 }
114
115                 false
116             },
117             ExprKind::Ret(Some(ref expr)) => Self::expression_returns_none(cx, expr),
118             ExprKind::Path(ref qp) => {
119                 if let Res::Def(DefKind::Ctor(def::CtorOf::Variant, def::CtorKind::Const), def_id) =
120                     cx.tables.qpath_res(qp, expression.hir_id)
121                 {
122                     return match_def_path(cx, def_id, &OPTION_NONE);
123                 }
124
125                 false
126             },
127             _ => false,
128         }
129     }
130
131     fn return_expression<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
132         // Check if last expression is a return statement. Then, return the expression
133         if_chain! {
134             if block.stmts.len() == 1;
135             if let Some(expr) = block.stmts.iter().last();
136             if let StmtKind::Semi(ref expr) = expr.kind;
137             if let ExprKind::Ret(ret_expr) = expr.kind;
138             if let Some(ret_expr) = ret_expr;
139
140             then {
141                 return Some(ret_expr);
142             }
143         }
144
145         // Check for `return` without a semicolon.
146         if_chain! {
147             if block.stmts.is_empty();
148             if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.kind);
149             then {
150                 return Some(ret_expr);
151             }
152         }
153
154         None
155     }
156 }
157
158 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for QuestionMark {
159     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
160         Self::check_is_none_and_early_return_none(cx, expr);
161     }
162 }