]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/question_mark.rs
Run rustfmt
[rust.git] / clippy_lints / src / question_mark.rs
1 use if_chain::if_chain;
2 use rustc::hir::def::Def;
3 use rustc::hir::*;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_tool_lint, lint_array};
6 use rustc_errors::Applicability;
7 use syntax::ptr::P;
8
9 use crate::utils::paths::*;
10 use crate::utils::sugg::Sugg;
11 use crate::utils::{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 #[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     fn name(&self) -> &'static str {
46         "QuestionMark"
47     }
48 }
49
50 impl Pass {
51     /// Checks if the given expression on the given context matches the following structure:
52     ///
53     /// ```ignore
54     /// if option.is_none() {
55     ///    return None;
56     /// }
57     /// ```
58     ///
59     /// If it matches, it will suggest to use the question mark operator instead
60     fn check_is_none_and_early_return_none(cx: &LateContext<'_, '_>, expr: &Expr) {
61         if_chain! {
62             if let ExprKind::If(if_expr, body, else_) = &expr.node;
63             if let ExprKind::MethodCall(segment, _, args) = &if_expr.node;
64             if segment.ident.name == "is_none";
65             if Self::expression_returns_none(cx, body);
66             if let Some(subject) = args.get(0);
67             if Self::is_option(cx, subject);
68
69             then {
70                 let receiver_str = &Sugg::hir(cx, subject, "..");
71                 let mut replacement: Option<String> = None;
72                 if let Some(else_) = else_ {
73                     if_chain! {
74                         if let ExprKind::Block(block, None) = &else_.node;
75                         if block.stmts.len() == 0;
76                         if let Some(block_expr) = &block.expr;
77                         if SpanlessEq::new(cx).ignore_fn().eq_expr(subject, block_expr);
78                         then {
79                             replacement = Some(format!("Some({}?)", receiver_str));
80                         }
81                     }
82                 } else if Self::moves_by_default(cx, subject) {
83                         replacement = Some(format!("{}.as_ref()?;", receiver_str));
84                 } else {
85                         replacement = Some(format!("{}?;", receiver_str));
86                 }
87
88                 if let Some(replacement_str) = replacement {
89                     span_lint_and_then(
90                         cx,
91                         QUESTION_MARK,
92                         expr.span,
93                         "this block may be rewritten with the `?` operator",
94                         |db| {
95                             db.span_suggestion(
96                                 expr.span,
97                                 "replace_it_with",
98                                 replacement_str,
99                                 Applicability::MaybeIncorrect, // snippet
100                             );
101                         }
102                     )
103                }
104             }
105         }
106     }
107
108     fn moves_by_default(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
109         let expr_ty = cx.tables.expr_ty(expression);
110
111         !expr_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, expression.span)
112     }
113
114     fn is_option(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
115         let expr_ty = cx.tables.expr_ty(expression);
116
117         match_type(cx, expr_ty, &OPTION)
118     }
119
120     fn expression_returns_none(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
121         match expression.node {
122             ExprKind::Block(ref block, _) => {
123                 if let Some(return_expression) = Self::return_expression(block) {
124                     return Self::expression_returns_none(cx, &return_expression);
125                 }
126
127                 false
128             },
129             ExprKind::Ret(Some(ref expr)) => Self::expression_returns_none(cx, expr),
130             ExprKind::Path(ref qp) => {
131                 if let Def::VariantCtor(def_id, _) = cx.tables.qpath_def(qp, expression.hir_id) {
132                     return match_def_path(cx.tcx, def_id, &OPTION_NONE);
133                 }
134
135                 false
136             },
137             _ => false,
138         }
139     }
140
141     fn return_expression(block: &Block) -> Option<P<Expr>> {
142         // Check if last expression is a return statement. Then, return the expression
143         if_chain! {
144             if block.stmts.len() == 1;
145             if let Some(expr) = block.stmts.iter().last();
146             if let StmtKind::Semi(ref expr) = expr.node;
147             if let ExprKind::Ret(ref ret_expr) = expr.node;
148             if let &Some(ref ret_expr) = ret_expr;
149
150             then {
151                 return Some(ret_expr.clone());
152             }
153         }
154
155         // Check for `return` without a semicolon.
156         if_chain! {
157             if block.stmts.len() == 0;
158             if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.node);
159             then {
160                 return Some(ret_expr.clone());
161             }
162         }
163
164         None
165     }
166 }
167
168 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
169     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
170         Self::check_is_none_and_early_return_none(cx, expr);
171     }
172 }