1 use if_chain::if_chain;
2 use rustc_errors::Applicability;
3 use rustc_hir::def::{DefKind, Res};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use crate::utils::paths::*;
9 use crate::utils::sugg::Sugg;
10 use crate::utils::{higher, match_def_path, match_type, span_lint_and_then, SpanlessEq};
12 declare_clippy_lint! {
13 /// **What it does:** Checks for expressions that could be replaced by the question mark operator.
15 /// **Why is this bad?** Question mark usage is more idiomatic.
17 /// **Known problems:** None
21 /// if option.is_none() {
33 "checks for expressions that could be replaced by the question mark operator"
36 declare_lint_pass!(QuestionMark => [QUESTION_MARK]);
39 /// Checks if the given expression on the given context matches the following structure:
42 /// if option.is_none() {
47 /// If it matches, it will suggest to use the question mark operator instead
48 fn check_is_none_and_early_return_none(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
50 if let Some((if_expr, body, else_)) = higher::if_block(&expr);
51 if let ExprKind::MethodCall(segment, _, args) = &if_expr.kind;
52 if segment.ident.name == sym!(is_none);
53 if Self::expression_returns_none(cx, body);
54 if let Some(subject) = args.get(0);
55 if Self::is_option(cx, subject);
58 let receiver_str = &Sugg::hir(cx, subject, "..");
59 let mut replacement: Option<String> = None;
60 if let Some(else_) = else_ {
62 if let ExprKind::Block(block, None) = &else_.kind;
63 if block.stmts.is_empty();
64 if let Some(block_expr) = &block.expr;
65 if SpanlessEq::new(cx).ignore_fn().eq_expr(subject, block_expr);
67 replacement = Some(format!("Some({}?)", receiver_str));
70 } else if Self::moves_by_default(cx, subject) {
71 replacement = Some(format!("{}.as_ref()?;", receiver_str));
73 replacement = Some(format!("{}?;", receiver_str));
76 if let Some(replacement_str) = replacement {
81 "this block may be rewritten with the `?` operator",
87 Applicability::MaybeIncorrect, // snippet
96 fn moves_by_default(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool {
97 let expr_ty = cx.tables.expr_ty(expression);
99 !expr_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, expression.span)
102 fn is_option(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool {
103 let expr_ty = cx.tables.expr_ty(expression);
105 match_type(cx, expr_ty, &OPTION)
108 fn expression_returns_none(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool {
109 match expression.kind {
110 ExprKind::Block(ref block, _) => {
111 if let Some(return_expression) = Self::return_expression(block) {
112 return Self::expression_returns_none(cx, &return_expression);
117 ExprKind::Ret(Some(ref expr)) => Self::expression_returns_none(cx, expr),
118 ExprKind::Path(ref qp) => {
119 if let Res::Def(DefKind::Ctor(def::CtorOf::Variant, def::CtorKind::Const), def_id) =
120 cx.tables.qpath_res(qp, expression.hir_id)
122 return match_def_path(cx, def_id, &OPTION_NONE);
131 fn return_expression<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
132 // Check if last expression is a return statement. Then, return the expression
134 if block.stmts.len() == 1;
135 if let Some(expr) = block.stmts.iter().last();
136 if let StmtKind::Semi(ref expr) = expr.kind;
137 if let ExprKind::Ret(ret_expr) = expr.kind;
138 if let Some(ret_expr) = ret_expr;
141 return Some(ret_expr);
145 // Check for `return` without a semicolon.
147 if block.stmts.is_empty();
148 if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.kind);
150 return Some(ret_expr);
158 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for QuestionMark {
159 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
160 Self::check_is_none_and_early_return_none(cx, expr);