]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/question_mark.rs
question_mark: Fix applicability
[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::rustc::hir::def::Def;
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::syntax::ptr::P;
15 use crate::utils::sugg::Sugg;
16 use if_chain::if_chain;
17
18 use crate::rustc_errors::Applicability;
19 use crate::utils::paths::*;
20 use crate::utils::{match_def_path, match_type, span_lint_and_then};
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(ref if_expr, ref body, _) = expr.node;
68             if let ExprKind::MethodCall(ref segment, _, ref 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                 span_lint_and_then(
76                     cx,
77                     QUESTION_MARK,
78                     expr.span,
79                     "this block may be rewritten with the `?` operator",
80                     |db| {
81                         let receiver_str = &Sugg::hir(cx, subject, "..");
82
83                         db.span_suggestion_with_applicability(
84                             expr.span,
85                             "replace_it_with",
86                             format!("{}?;", receiver_str),
87                             Applicability::MaybeIncorrect, // snippet
88                         );
89                     }
90                 )
91             }
92         }
93     }
94
95     fn is_option(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
96         let expr_ty = cx.tables.expr_ty(expression);
97
98         match_type(cx, expr_ty, &OPTION)
99     }
100
101     fn expression_returns_none(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
102         match expression.node {
103             ExprKind::Block(ref block, _) => {
104                 if let Some(return_expression) = Self::return_expression(block) {
105                     return Self::expression_returns_none(cx, &return_expression);
106                 }
107
108                 false
109             },
110             ExprKind::Ret(Some(ref expr)) => Self::expression_returns_none(cx, expr),
111             ExprKind::Path(ref qp) => {
112                 if let Def::VariantCtor(def_id, _) = cx.tables.qpath_def(qp, expression.hir_id) {
113                     return match_def_path(cx.tcx, def_id, &OPTION_NONE);
114                 }
115
116                 false
117             },
118             _ => false,
119         }
120     }
121
122     fn return_expression(block: &Block) -> Option<P<Expr>> {
123         // Check if last expression is a return statement. Then, return the expression
124         if_chain! {
125             if block.stmts.len() == 1;
126             if let Some(expr) = block.stmts.iter().last();
127             if let StmtKind::Semi(ref expr, _) = expr.node;
128             if let ExprKind::Ret(ref ret_expr) = expr.node;
129             if let &Some(ref ret_expr) = ret_expr;
130
131             then {
132                 return Some(ret_expr.clone());
133             }
134         }
135
136         // Check if the block has an implicit return expression
137         if let Some(ref ret_expr) = block.expr {
138             return Some(ret_expr.clone());
139         }
140
141         None
142     }
143 }
144
145 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
146     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
147         Self::check_is_none_and_early_return_none(cx, expr);
148     }
149 }