]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/question_mark.rs
Auto merge of #3623 - phansch:rustup, r=flip1995
[rust.git] / clippy_lints / src / question_mark.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::utils::sugg::Sugg;
11 use if_chain::if_chain;
12 use rustc::hir::def::Def;
13 use rustc::hir::*;
14 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
15 use rustc::{declare_tool_lint, lint_array};
16 use syntax::ptr::P;
17
18 use crate::utils::paths::*;
19 use crate::utils::{match_def_path, match_type, span_lint_and_then, SpanlessEq};
20 use rustc_errors::Applicability;
21
22 /// **What it does:** Checks for expressions that could be replaced by the question mark operator
23 ///
24 /// **Why is this bad?** Question mark usage is more idiomatic
25 ///
26 /// **Known problems:** None
27 ///
28 /// **Example:**
29 /// ```rust
30 /// if option.is_none() {
31 ///     return None;
32 /// }
33 /// ```
34 ///
35 /// Could be written:
36 ///
37 /// ```rust
38 /// option?;
39 /// ```
40 declare_clippy_lint! {
41     pub QUESTION_MARK,
42     style,
43     "checks for expressions that could be replaced by the question mark operator"
44 }
45
46 #[derive(Copy, Clone)]
47 pub struct Pass;
48
49 impl LintPass for Pass {
50     fn get_lints(&self) -> LintArray {
51         lint_array!(QUESTION_MARK)
52     }
53 }
54
55 impl Pass {
56     /// Check if the given expression on the given context matches the following structure:
57     ///
58     /// ```ignore
59     /// if option.is_none() {
60     ///    return None;
61     /// }
62     /// ```
63     ///
64     /// If it matches, it will suggest to use the question mark operator instead
65     fn check_is_none_and_early_return_none(cx: &LateContext<'_, '_>, expr: &Expr) {
66         if_chain! {
67             if let ExprKind::If(if_expr, body, else_) = &expr.node;
68             if let ExprKind::MethodCall(segment, _, args) = &if_expr.node;
69             if segment.ident.name == "is_none";
70             if Self::expression_returns_none(cx, body);
71             if let Some(subject) = args.get(0);
72             if Self::is_option(cx, subject);
73
74             then {
75                 let receiver_str = &Sugg::hir(cx, subject, "..");
76                 let mut replacement: Option<String> = None;
77                 if let Some(else_) = else_ {
78                     if_chain! {
79                         if let ExprKind::Block(block, None) = &else_.node;
80                         if block.stmts.len() == 0;
81                         if let Some(block_expr) = &block.expr;
82                         if SpanlessEq::new(cx).ignore_fn().eq_expr(subject, block_expr);
83                         then {
84                             replacement = Some(format!("Some({}?)", receiver_str));
85                         }
86                     }
87                 } else if Self::moves_by_default(cx, subject) {
88                         replacement = Some(format!("{}.as_ref()?;", receiver_str));
89                 } else {
90                         replacement = Some(format!("{}?;", receiver_str));
91                 }
92
93                 if let Some(replacement_str) = replacement {
94                     span_lint_and_then(
95                         cx,
96                         QUESTION_MARK,
97                         expr.span,
98                         "this block may be rewritten with the `?` operator",
99                         |db| {
100                             db.span_suggestion_with_applicability(
101                                 expr.span,
102                                 "replace_it_with",
103                                 replacement_str,
104                                 Applicability::MaybeIncorrect, // snippet
105                             );
106                         }
107                     )
108                }
109             }
110         }
111     }
112
113     fn moves_by_default(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
114         let expr_ty = cx.tables.expr_ty(expression);
115
116         !expr_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, expression.span)
117     }
118
119     fn is_option(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
120         let expr_ty = cx.tables.expr_ty(expression);
121
122         match_type(cx, expr_ty, &OPTION)
123     }
124
125     fn expression_returns_none(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
126         match expression.node {
127             ExprKind::Block(ref block, _) => {
128                 if let Some(return_expression) = Self::return_expression(block) {
129                     return Self::expression_returns_none(cx, &return_expression);
130                 }
131
132                 false
133             },
134             ExprKind::Ret(Some(ref expr)) => Self::expression_returns_none(cx, expr),
135             ExprKind::Path(ref qp) => {
136                 if let Def::VariantCtor(def_id, _) = cx.tables.qpath_def(qp, expression.hir_id) {
137                     return match_def_path(cx.tcx, def_id, &OPTION_NONE);
138                 }
139
140                 false
141             },
142             _ => false,
143         }
144     }
145
146     fn return_expression(block: &Block) -> Option<P<Expr>> {
147         // Check if last expression is a return statement. Then, return the expression
148         if_chain! {
149             if block.stmts.len() == 1;
150             if let Some(expr) = block.stmts.iter().last();
151             if let StmtKind::Semi(ref expr, _) = expr.node;
152             if let ExprKind::Ret(ref ret_expr) = expr.node;
153             if let &Some(ref ret_expr) = ret_expr;
154
155             then {
156                 return Some(ret_expr.clone());
157             }
158         }
159
160         // Check for `return` without a semicolon.
161         if_chain! {
162             if block.stmts.len() == 0;
163             if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.node);
164             then {
165                 return Some(ret_expr.clone());
166             }
167         }
168
169         None
170     }
171 }
172
173 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
174     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
175         Self::check_is_none_and_early_return_none(cx, expr);
176     }
177 }