]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/question_mark.rs
Fix `stutter` lints
[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
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use crate::rustc::{declare_tool_lint, lint_array};
13 use if_chain::if_chain;
14 use crate::rustc::hir::*;
15 use crate::rustc::hir::def::Def;
16 use crate::utils::sugg::Sugg;
17 use crate::syntax::ptr::P;
18
19 use crate::utils::{match_def_path, match_type, span_lint_and_then};
20 use crate::utils::paths::*;
21 use crate::rustc_errors::Applicability;
22
23 /// **What it does:** Checks for expressions that could be replaced by the question mark operator
24 ///
25 /// **Why is this bad?** Question mark usage is more idiomatic
26 ///
27 /// **Known problems:** None
28 ///
29 /// **Example:**
30 /// ```rust
31 /// if option.is_none() {
32 ///     return None;
33 /// }
34 /// ```
35 ///
36 /// Could be written:
37 ///
38 /// ```rust
39 /// option?;
40 /// ```
41 declare_clippy_lint!{
42     pub QUESTION_MARK,
43     style,
44     "checks for expressions that could be replaced by the question mark operator"
45 }
46
47 #[allow(clippy::stutter)]
48 #[derive(Copy, Clone)]
49 pub struct QuestionMarkPass;
50
51 impl LintPass for QuestionMarkPass {
52     fn get_lints(&self) -> LintArray {
53         lint_array!(QUESTION_MARK)
54     }
55 }
56
57 impl QuestionMarkPass {
58     /// Check if the given expression on the given context matches the following structure:
59     ///
60     /// ```ignore
61     /// if option.is_none() {
62     ///    return None;
63     /// }
64     /// ```
65     ///
66     /// If it matches, it will suggest to use the question mark operator instead
67     fn check_is_none_and_early_return_none(cx: &LateContext<'_, '_>, expr: &Expr) {
68         if_chain! {
69             if let ExprKind::If(ref if_expr, ref body, _) = expr.node;
70             if let ExprKind::MethodCall(ref segment, _, ref args) = if_expr.node;
71             if segment.ident.name == "is_none";
72             if Self::expression_returns_none(cx, body);
73             if let Some(subject) = args.get(0);
74             if Self::is_option(cx, subject);
75
76             then {
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                         let receiver_str = &Sugg::hir(cx, subject, "..");
84
85                         db.span_suggestion_with_applicability(
86                             expr.span,
87                             "replace_it_with",
88                             format!("{}?;", receiver_str),
89                             Applicability::MachineApplicable, // snippet
90                         );
91                     }
92                 )
93             }
94         }
95     }
96
97     fn is_option(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
98         let expr_ty = cx.tables.expr_ty(expression);
99
100         match_type(cx, expr_ty, &OPTION)
101     }
102
103     fn expression_returns_none(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
104         match expression.node {
105             ExprKind::Block(ref block, _) => {
106                 if let Some(return_expression) = Self::return_expression(block) {
107                     return Self::expression_returns_none(cx, &return_expression);
108                 }
109
110                 false
111             },
112             ExprKind::Ret(Some(ref expr)) => {
113                 Self::expression_returns_none(cx, expr)
114             },
115             ExprKind::Path(ref qp) => {
116                 if let Def::VariantCtor(def_id, _) = cx.tables.qpath_def(qp, expression.hir_id) {
117                     return match_def_path(cx.tcx, def_id,  &OPTION_NONE);
118                 }
119
120                 false
121             },
122             _ => false
123         }
124     }
125
126     fn return_expression(block: &Block) -> Option<P<Expr>> {
127         // Check if last expression is a return statement. Then, return the expression
128         if_chain! {
129             if block.stmts.len() == 1;
130             if let Some(expr) = block.stmts.iter().last();
131             if let StmtKind::Semi(ref expr, _) = expr.node;
132             if let ExprKind::Ret(ref ret_expr) = expr.node;
133             if let &Some(ref ret_expr) = ret_expr;
134
135             then {
136                 return Some(ret_expr.clone());
137             }
138         }
139
140         // Check if the block has an implicit return expression
141         if let Some(ref ret_expr) = block.expr {
142             return Some(ret_expr.clone());
143         }
144
145         None
146     }
147 }
148
149 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for QuestionMarkPass {
150     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
151         Self::check_is_none_and_early_return_none(cx, expr);
152     }
153 }