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