]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/question_mark.rs
Auto merge of #3646 - matthiaskrgr:travis, r=phansch
[rust.git] / clippy_lints / src / question_mark.rs
1 use crate::utils::sugg::Sugg;
2 use if_chain::if_chain;
3 use rustc::hir::def::Def;
4 use rustc::hir::*;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_tool_lint, lint_array};
7 use syntax::ptr::P;
8
9 use crate::utils::paths::*;
10 use crate::utils::{match_def_path, match_type, span_lint_and_then, SpanlessEq};
11 use 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 Pass;
39
40 impl LintPass for Pass {
41     fn get_lints(&self) -> LintArray {
42         lint_array!(QUESTION_MARK)
43     }
44 }
45
46 impl Pass {
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(if_expr, body, else_) = &expr.node;
59             if let ExprKind::MethodCall(segment, _, 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                 let receiver_str = &Sugg::hir(cx, subject, "..");
67                 let mut replacement: Option<String> = None;
68                 if let Some(else_) = else_ {
69                     if_chain! {
70                         if let ExprKind::Block(block, None) = &else_.node;
71                         if block.stmts.len() == 0;
72                         if let Some(block_expr) = &block.expr;
73                         if SpanlessEq::new(cx).ignore_fn().eq_expr(subject, block_expr);
74                         then {
75                             replacement = Some(format!("Some({}?)", receiver_str));
76                         }
77                     }
78                 } else if Self::moves_by_default(cx, subject) {
79                         replacement = Some(format!("{}.as_ref()?;", receiver_str));
80                 } else {
81                         replacement = Some(format!("{}?;", receiver_str));
82                 }
83
84                 if let Some(replacement_str) = replacement {
85                     span_lint_and_then(
86                         cx,
87                         QUESTION_MARK,
88                         expr.span,
89                         "this block may be rewritten with the `?` operator",
90                         |db| {
91                             db.span_suggestion_with_applicability(
92                                 expr.span,
93                                 "replace_it_with",
94                                 replacement_str,
95                                 Applicability::MaybeIncorrect, // snippet
96                             );
97                         }
98                     )
99                }
100             }
101         }
102     }
103
104     fn moves_by_default(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
105         let expr_ty = cx.tables.expr_ty(expression);
106
107         !expr_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, expression.span)
108     }
109
110     fn is_option(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
111         let expr_ty = cx.tables.expr_ty(expression);
112
113         match_type(cx, expr_ty, &OPTION)
114     }
115
116     fn expression_returns_none(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
117         match expression.node {
118             ExprKind::Block(ref block, _) => {
119                 if let Some(return_expression) = Self::return_expression(block) {
120                     return Self::expression_returns_none(cx, &return_expression);
121                 }
122
123                 false
124             },
125             ExprKind::Ret(Some(ref expr)) => Self::expression_returns_none(cx, expr),
126             ExprKind::Path(ref qp) => {
127                 if let Def::VariantCtor(def_id, _) = cx.tables.qpath_def(qp, expression.hir_id) {
128                     return match_def_path(cx.tcx, def_id, &OPTION_NONE);
129                 }
130
131                 false
132             },
133             _ => false,
134         }
135     }
136
137     fn return_expression(block: &Block) -> Option<P<Expr>> {
138         // Check if last expression is a return statement. Then, return the expression
139         if_chain! {
140             if block.stmts.len() == 1;
141             if let Some(expr) = block.stmts.iter().last();
142             if let StmtKind::Semi(ref expr, _) = expr.node;
143             if let ExprKind::Ret(ref ret_expr) = expr.node;
144             if let &Some(ref ret_expr) = ret_expr;
145
146             then {
147                 return Some(ret_expr.clone());
148             }
149         }
150
151         // Check for `return` without a semicolon.
152         if_chain! {
153             if block.stmts.len() == 0;
154             if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.node);
155             then {
156                 return Some(ret_expr.clone());
157             }
158         }
159
160         None
161     }
162 }
163
164 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
165     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
166         Self::check_is_none_and_early_return_none(cx, expr);
167     }
168 }