1 use clippy_utils::ty::is_type_diagnostic_item;
2 use if_chain::if_chain;
3 use rustc_errors::Applicability;
4 use rustc_hir::def::{DefKind, Res};
5 use rustc_hir::{def, BindingAnnotation, Block, Expr, ExprKind, MatchSource, PatKind, StmtKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use crate::utils::sugg::Sugg;
11 use crate::utils::{eq_expr_value, match_def_path, match_qpath, paths, snippet_with_applicability, span_lint_and_sugg};
13 declare_clippy_lint! {
14 /// **What it does:** Checks for expressions that could be replaced by the question mark operator.
16 /// **Why is this bad?** Question mark usage is more idiomatic.
18 /// **Known problems:** None
22 /// if option.is_none() {
34 "checks for expressions that could be replaced by the question mark operator"
37 declare_lint_pass!(QuestionMark => [QUESTION_MARK]);
40 /// Checks if the given expression on the given context matches the following structure:
43 /// if option.is_none() {
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<'_>) {
51 if let ExprKind::If(if_expr, body, else_) = &expr.kind;
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);
59 let mut applicability = Applicability::MachineApplicable;
60 let receiver_str = &Sugg::hir_with_applicability(cx, subject, "..", &mut applicability);
61 let mut replacement: Option<String> = None;
62 if let Some(else_) = else_ {
64 if let ExprKind::Block(block, None) = &else_.kind;
65 if block.stmts.is_empty();
66 if let Some(block_expr) = &block.expr;
67 if eq_expr_value(cx, subject, block_expr);
69 replacement = Some(format!("Some({}?)", receiver_str));
72 } else if Self::moves_by_default(cx, subject)
73 && !matches!(subject.kind, ExprKind::Call(..) | ExprKind::MethodCall(..))
75 replacement = Some(format!("{}.as_ref()?;", receiver_str));
77 replacement = Some(format!("{}?;", receiver_str));
80 if let Some(replacement_str) = replacement {
85 "this block may be rewritten with the `?` operator",
95 fn check_if_let_some_and_early_return_none(cx: &LateContext<'_>, expr: &Expr<'_>) {
97 if let ExprKind::Match(subject, arms, source) = &expr.kind;
98 if *source == MatchSource::IfLetDesugar { contains_else_clause: true };
99 if Self::is_option(cx, subject);
101 if let PatKind::TupleStruct(path1, fields, None) = &arms[0].pat.kind;
102 if match_qpath(path1, &["Some"]);
103 if let PatKind::Binding(annot, _, bind, _) = &fields[0].kind;
104 let by_ref = matches!(annot, BindingAnnotation::Ref | BindingAnnotation::RefMut);
106 if let ExprKind::Block(block, None) = &arms[0].body.kind;
107 if block.stmts.is_empty();
108 if let Some(trailing_expr) = &block.expr;
109 if let ExprKind::Path(path) = &trailing_expr.kind;
110 if match_qpath(path, &[&bind.as_str()]);
112 if let PatKind::Wild = arms[1].pat.kind;
113 if Self::expression_returns_none(cx, arms[1].body);
115 let mut applicability = Applicability::MachineApplicable;
116 let receiver_str = snippet_with_applicability(cx, subject.span, "..", &mut applicability);
117 let replacement = format!(
120 if by_ref { ".as_ref()" } else { "" },
127 "this if-let-else may be rewritten with the `?` operator",
136 fn moves_by_default(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
137 let expr_ty = cx.typeck_results().expr_ty(expression);
139 !expr_ty.is_copy_modulo_regions(cx.tcx.at(expression.span), cx.param_env)
142 fn is_option(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
143 let expr_ty = cx.typeck_results().expr_ty(expression);
145 is_type_diagnostic_item(cx, expr_ty, sym::option_type)
148 fn expression_returns_none(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
149 match expression.kind {
150 ExprKind::Block(ref block, _) => {
151 if let Some(return_expression) = Self::return_expression(block) {
152 return Self::expression_returns_none(cx, &return_expression);
157 ExprKind::Ret(Some(ref expr)) => Self::expression_returns_none(cx, expr),
158 ExprKind::Path(ref qp) => {
159 if let Res::Def(DefKind::Ctor(def::CtorOf::Variant, def::CtorKind::Const), def_id) =
160 cx.qpath_res(qp, expression.hir_id)
162 return match_def_path(cx, def_id, &paths::OPTION_NONE);
171 fn return_expression<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
172 // Check if last expression is a return statement. Then, return the expression
174 if block.stmts.len() == 1;
175 if let Some(expr) = block.stmts.iter().last();
176 if let StmtKind::Semi(ref expr) = expr.kind;
177 if let ExprKind::Ret(Some(ret_expr)) = expr.kind;
180 return Some(ret_expr);
184 // Check for `return` without a semicolon.
186 if block.stmts.is_empty();
187 if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.kind);
189 return Some(ret_expr);
197 impl<'tcx> LateLintPass<'tcx> for QuestionMark {
198 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
199 Self::check_is_none_and_early_return_none(cx, expr);
200 Self::check_if_let_some_and_early_return_none(cx, expr);