1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::rustc::hir::def::Def;
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::syntax::ptr::P;
15 use crate::utils::sugg::Sugg;
16 use if_chain::if_chain;
18 use crate::rustc_errors::Applicability;
19 use crate::utils::paths::*;
20 use crate::utils::{match_def_path, match_type, span_lint_and_then, SpanlessEq};
22 /// **What it does:** Checks for expressions that could be replaced by the question mark operator
24 /// **Why is this bad?** Question mark usage is more idiomatic
26 /// **Known problems:** None
30 /// if option.is_none() {
40 declare_clippy_lint! {
43 "checks for expressions that could be replaced by the question mark operator"
46 #[derive(Copy, Clone)]
49 impl LintPass for Pass {
50 fn get_lints(&self) -> LintArray {
51 lint_array!(QUESTION_MARK)
56 /// Check if the given expression on the given context matches the following structure:
59 /// if option.is_none() {
64 /// If it matches, it will suggest to use the question mark operator instead
65 fn check_is_none_and_early_return_none(cx: &LateContext<'_, '_>, expr: &Expr) {
67 if let ExprKind::If(if_expr, body, else_) = &expr.node;
68 if let ExprKind::MethodCall(segment, _, args) = &if_expr.node;
69 if segment.ident.name == "is_none";
70 if Self::expression_returns_none(cx, body);
71 if let Some(subject) = args.get(0);
72 if Self::is_option(cx, subject);
75 let receiver_str = &Sugg::hir(cx, subject, "..");
76 let mut replacement_str = String::new();
77 if let Some(else_) = else_ {
79 if let ExprKind::Block(block, None) = &else_.node;
80 if block.stmts.len() == 0;
81 if let Some(block_expr) = &block.expr;
82 if SpanlessEq::new(cx).ignore_fn().eq_expr(subject, block_expr);
84 replacement_str = format!("Some({}?)", receiver_str);
87 } else if Self::moves_by_default(cx, subject) {
88 replacement_str = format!("{}.as_ref()?;", receiver_str);
90 replacement_str = format!("{}?;", receiver_str);
96 "this block may be rewritten with the `?` operator",
98 db.span_suggestion_with_applicability(
102 Applicability::MaybeIncorrect, // snippet
110 fn moves_by_default(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
111 let expr_ty = cx.tables.expr_ty(expression);
113 expr_ty.moves_by_default(cx.tcx, cx.param_env, expression.span)
116 fn is_option(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
117 let expr_ty = cx.tables.expr_ty(expression);
119 match_type(cx, expr_ty, &OPTION)
122 fn expression_returns_none(cx: &LateContext<'_, '_>, expression: &Expr) -> bool {
123 match expression.node {
124 ExprKind::Block(ref block, _) => {
125 if let Some(return_expression) = Self::return_expression(block) {
126 return Self::expression_returns_none(cx, &return_expression);
131 ExprKind::Ret(Some(ref expr)) => Self::expression_returns_none(cx, expr),
132 ExprKind::Path(ref qp) => {
133 if let Def::VariantCtor(def_id, _) = cx.tables.qpath_def(qp, expression.hir_id) {
134 return match_def_path(cx.tcx, def_id, &OPTION_NONE);
143 fn return_expression(block: &Block) -> Option<P<Expr>> {
144 // Check if last expression is a return statement. Then, return the expression
146 if block.stmts.len() == 1;
147 if let Some(expr) = block.stmts.iter().last();
148 if let StmtKind::Semi(ref expr, _) = expr.node;
149 if let ExprKind::Ret(ref ret_expr) = expr.node;
150 if let &Some(ref ret_expr) = ret_expr;
153 return Some(ret_expr.clone());
157 // Check for `return` without a semicolon.
159 if block.stmts.len() == 0;
160 if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.node);
162 return Some(ret_expr.clone());
170 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
171 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
172 Self::check_is_none_and_early_return_none(cx, expr);