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