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