]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/question_mark.rs
Merge remote-tracking branch 'upstream/rust-1.39.0' into backport_merge
[rust.git] / clippy_lints / src / question_mark.rs
1 use if_chain::if_chain;
2 use rustc::hir::def::{DefKind, Res};
3 use rustc::hir::ptr::P;
4 use rustc::hir::*;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_lint_pass, declare_tool_lint};
7 use rustc_errors::Applicability;
8
9 use crate::utils::paths::*;
10 use crate::utils::sugg::Sugg;
11 use crate::utils::{higher, match_def_path, match_type, span_lint_and_then, SpanlessEq};
12
13 declare_clippy_lint! {
14     /// **What it does:** Checks for expressions that could be replaced by the question mark operator.
15     ///
16     /// **Why is this bad?** Question mark usage is more idiomatic.
17     ///
18     /// **Known problems:** None
19     ///
20     /// **Example:**
21     /// ```ignore
22     /// if option.is_none() {
23     ///     return None;
24     /// }
25     /// ```
26     ///
27     /// Could be written:
28     ///
29     /// ```ignore
30     /// option?;
31     /// ```
32     pub QUESTION_MARK,
33     style,
34     "checks for expressions that could be replaced by the question mark operator"
35 }
36
37 declare_lint_pass!(QuestionMark => [QUESTION_MARK]);
38
39 impl QuestionMark {
40     /// Checks if the given expression on the given context matches the following structure:
41     ///
42     /// ```ignore
43     /// if option.is_none() {
44     ///    return None;
45     /// }
46     /// ```
47     ///
48     /// If it matches, it will suggest to use the question mark operator instead
49     fn check_is_none_and_early_return_none(cx: &LateContext<'_, '_>, expr: &Expr) {
50         if_chain! {
51             if let Some((if_expr, body, else_)) = higher::if_block(&expr);
52             if let ExprKind::MethodCall(segment, _, args) = &if_expr.kind;
53             if segment.ident.name == sym!(is_none);
54             if Self::expression_returns_none(cx, body);
55             if let Some(subject) = args.get(0);
56             if Self::is_option(cx, subject);
57
58             then {
59                 let receiver_str = &Sugg::hir(cx, subject, "..");
60                 let mut replacement: Option<String> = None;
61                 if let Some(else_) = else_ {
62                     if_chain! {
63                         if let ExprKind::Block(block, None) = &else_.kind;
64                         if block.stmts.len() == 0;
65                         if let Some(block_expr) = &block.expr;
66                         if SpanlessEq::new(cx).ignore_fn().eq_expr(subject, block_expr);
67                         then {
68                             replacement = Some(format!("Some({}?)", receiver_str));
69                         }
70                     }
71                 } else if Self::moves_by_default(cx, subject) {
72                         replacement = Some(format!("{}.as_ref()?;", receiver_str));
73                 } else {
74                         replacement = Some(format!("{}?;", receiver_str));
75                 }
76
77                 if let Some(replacement_str) = replacement {
78                     span_lint_and_then(
79                         cx,
80                         QUESTION_MARK,
81                         expr.span,
82                         "this block may be rewritten with the `?` operator",
83                         |db| {
84                             db.span_suggestion(
85                                 expr.span,
86                                 "replace_it_with",
87                                 replacement_str,
88                                 Applicability::MaybeIncorrect, // snippet
89                             );
90                         }
91                     )
92                }
93             }
94         }
95     }
96
97     fn moves_by_default(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
98         let expr_ty = cx.tables.expr_ty(expression);
99
100         !expr_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, expression.span)
101     }
102
103     fn is_option(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
104         let expr_ty = cx.tables.expr_ty(expression);
105
106         match_type(cx, expr_ty, &OPTION)
107     }
108
109     fn expression_returns_none(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
110         match expression.kind {
111             ExprKind::Block(ref block, _) => {
112                 if let Some(return_expression) = Self::return_expression(block) {
113                     return Self::expression_returns_none(cx, &return_expression);
114                 }
115
116                 false
117             },
118             ExprKind::Ret(Some(ref expr)) => Self::expression_returns_none(cx, expr),
119             ExprKind::Path(ref qp) => {
120                 if let Res::Def(DefKind::Ctor(def::CtorOf::Variant, def::CtorKind::Const), def_id) =
121                     cx.tables.qpath_res(qp, expression.hir_id)
122                 {
123                     return match_def_path(cx, def_id, &OPTION_NONE);
124                 }
125
126                 false
127             },
128             _ => false,
129         }
130     }
131
132     fn return_expression(block: &Block) -> Option<&P<Expr>> {
133         // Check if last expression is a return statement. Then, return the expression
134         if_chain! {
135             if block.stmts.len() == 1;
136             if let Some(expr) = block.stmts.iter().last();
137             if let StmtKind::Semi(ref expr) = expr.kind;
138             if let ExprKind::Ret(ref ret_expr) = expr.kind;
139             if let &Some(ref ret_expr) = ret_expr;
140
141             then {
142                 return Some(ret_expr);
143             }
144         }
145
146         // Check for `return` without a semicolon.
147         if_chain! {
148             if block.stmts.len() == 0;
149             if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.kind);
150             then {
151                 return Some(ret_expr);
152             }
153         }
154
155         None
156     }
157 }
158
159 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for QuestionMark {
160     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
161         Self::check_is_none_and_early_return_none(cx, expr);
162     }
163 }