]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/question_mark.rs
Merge pull request #3285 from devonhollowood/pedantic-dogfood-items-after-statements
[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 #[derive(Copy, Clone)]
48 pub struct QuestionMarkPass;
49
50 impl LintPass for QuestionMarkPass {
51     fn get_lints(&self) -> LintArray {
52         lint_array!(QUESTION_MARK)
53     }
54 }
55
56 impl QuestionMarkPass {
57     /// Check if the given expression on the given context matches the following structure:
58     ///
59     /// ```ignore
60     /// if option.is_none() {
61     ///    return None;
62     /// }
63     /// ```
64     ///
65     /// If it matches, it will suggest to use the question mark operator instead
66     fn check_is_none_and_early_return_none(cx: &LateContext<'_, '_>, expr: &Expr) {
67         if_chain! {
68             if let ExprKind::If(ref if_expr, ref body, _) = expr.node;
69             if let ExprKind::MethodCall(ref segment, _, ref args) = if_expr.node;
70             if segment.ident.name == "is_none";
71             if Self::expression_returns_none(cx, body);
72             if let Some(subject) = args.get(0);
73             if Self::is_option(cx, subject);
74
75             then {
76                 span_lint_and_then(
77                     cx,
78                     QUESTION_MARK,
79                     expr.span,
80                     "this block may be rewritten with the `?` operator",
81                     |db| {
82                         let receiver_str = &Sugg::hir(cx, subject, "..");
83
84                         db.span_suggestion_with_applicability(
85                             expr.span,
86                             "replace_it_with",
87                             format!("{}?;", receiver_str),
88                             Applicability::MachineApplicable, // snippet
89                         );
90                     }
91                 )
92             }
93         }
94     }
95
96     fn is_option(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
97         let expr_ty = cx.tables.expr_ty(expression);
98
99         match_type(cx, expr_ty, &OPTION)
100     }
101
102     fn expression_returns_none(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
103         match expression.node {
104             ExprKind::Block(ref block, _) => {
105                 if let Some(return_expression) = Self::return_expression(block) {
106                     return Self::expression_returns_none(cx, &return_expression);
107                 }
108
109                 false
110             },
111             ExprKind::Ret(Some(ref expr)) => {
112                 Self::expression_returns_none(cx, expr)
113             },
114             ExprKind::Path(ref qp) => {
115                 if let Def::VariantCtor(def_id, _) = cx.tables.qpath_def(qp, expression.hir_id) {
116                     return match_def_path(cx.tcx, def_id,  &OPTION_NONE);
117                 }
118
119                 false
120             },
121             _ => false
122         }
123     }
124
125     fn return_expression(block: &Block) -> Option<P<Expr>> {
126         // Check if last expression is a return statement. Then, return the expression
127         if_chain! {
128             if block.stmts.len() == 1;
129             if let Some(expr) = block.stmts.iter().last();
130             if let StmtKind::Semi(ref expr, _) = expr.node;
131             if let ExprKind::Ret(ref ret_expr) = expr.node;
132             if let &Some(ref ret_expr) = ret_expr;
133
134             then {
135                 return Some(ret_expr.clone());
136             }
137         }
138
139         // Check if the block has an implicit return expression
140         if let Some(ref ret_expr) = block.expr {
141             return Some(ret_expr.clone());
142         }
143
144         None
145     }
146 }
147
148 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for QuestionMarkPass {
149     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
150         Self::check_is_none_and_early_return_none(cx, expr);
151     }
152 }