1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::is_lang_ctor;
3 use clippy_utils::source::snippet_with_applicability;
4 use clippy_utils::sugg::Sugg;
5 use clippy_utils::ty::is_type_diagnostic_item;
6 use clippy_utils::{eq_expr_value, path_to_local_id};
7 use if_chain::if_chain;
8 use rustc_errors::Applicability;
9 use rustc_hir::LangItem::{OptionNone, OptionSome};
10 use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, MatchSource, PatKind, StmtKind};
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
15 declare_clippy_lint! {
16 /// **What it does:** Checks for expressions that could be replaced by the question mark operator.
18 /// **Why is this bad?** Question mark usage is more idiomatic.
20 /// **Known problems:** None
24 /// if option.is_none() {
36 "checks for expressions that could be replaced by the question mark operator"
39 declare_lint_pass!(QuestionMark => [QUESTION_MARK]);
42 /// Checks if the given expression on the given context matches the following structure:
45 /// if option.is_none() {
50 /// If it matches, it will suggest to use the question mark operator instead
51 fn check_is_none_and_early_return_none(cx: &LateContext<'_>, expr: &Expr<'_>) {
53 if let ExprKind::If(if_expr, body, else_) = &expr.kind;
54 if let ExprKind::MethodCall(segment, _, args, _) = &if_expr.kind;
55 if segment.ident.name == sym!(is_none);
56 if Self::expression_returns_none(cx, body);
57 if let Some(subject) = args.get(0);
58 if Self::is_option(cx, subject);
61 let mut applicability = Applicability::MachineApplicable;
62 let receiver_str = &Sugg::hir_with_applicability(cx, subject, "..", &mut applicability);
63 let mut replacement: Option<String> = None;
64 if let Some(else_) = else_ {
66 if let ExprKind::Block(block, None) = &else_.kind;
67 if block.stmts.is_empty();
68 if let Some(block_expr) = &block.expr;
69 if eq_expr_value(cx, subject, block_expr);
71 replacement = Some(format!("Some({}?)", receiver_str));
74 } else if Self::moves_by_default(cx, subject)
75 && !matches!(subject.kind, ExprKind::Call(..) | ExprKind::MethodCall(..))
77 replacement = Some(format!("{}.as_ref()?;", receiver_str));
79 replacement = Some(format!("{}?;", receiver_str));
82 if let Some(replacement_str) = replacement {
87 "this block may be rewritten with the `?` operator",
97 fn check_if_let_some_and_early_return_none(cx: &LateContext<'_>, expr: &Expr<'_>) {
99 if let ExprKind::Match(subject, arms, source) = &expr.kind;
100 if *source == MatchSource::IfLetDesugar { contains_else_clause: true };
101 if Self::is_option(cx, subject);
103 if let PatKind::TupleStruct(path1, fields, None) = &arms[0].pat.kind;
104 if is_lang_ctor(cx, path1, OptionSome);
105 if let PatKind::Binding(annot, bind_id, _, _) = fields[0].kind;
106 let by_ref = matches!(annot, BindingAnnotation::Ref | BindingAnnotation::RefMut);
108 if let ExprKind::Block(block, None) = &arms[0].body.kind;
109 if block.stmts.is_empty();
110 if let Some(trailing_expr) = &block.expr;
111 if path_to_local_id(trailing_expr, bind_id);
113 if let PatKind::Wild = arms[1].pat.kind;
114 if Self::expression_returns_none(cx, arms[1].body);
116 let mut applicability = Applicability::MachineApplicable;
117 let receiver_str = snippet_with_applicability(cx, subject.span, "..", &mut applicability);
118 let replacement = format!(
121 if by_ref { ".as_ref()" } else { "" },
128 "this if-let-else may be rewritten with the `?` operator",
137 fn moves_by_default(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
138 let expr_ty = cx.typeck_results().expr_ty(expression);
140 !expr_ty.is_copy_modulo_regions(cx.tcx.at(expression.span), cx.param_env)
143 fn is_option(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
144 let expr_ty = cx.typeck_results().expr_ty(expression);
146 is_type_diagnostic_item(cx, expr_ty, sym::option_type)
149 fn expression_returns_none(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
150 match expression.kind {
151 ExprKind::Block(block, _) => {
152 if let Some(return_expression) = Self::return_expression(block) {
153 return Self::expression_returns_none(cx, return_expression);
158 ExprKind::Ret(Some(expr)) => Self::expression_returns_none(cx, expr),
159 ExprKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
164 fn return_expression<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
165 // Check if last expression is a return statement. Then, return the expression
167 if block.stmts.len() == 1;
168 if let Some(expr) = block.stmts.iter().last();
169 if let StmtKind::Semi(expr) = expr.kind;
170 if let ExprKind::Ret(Some(ret_expr)) = expr.kind;
173 return Some(ret_expr);
177 // Check for `return` without a semicolon.
179 if block.stmts.is_empty();
180 if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.kind);
182 return Some(ret_expr);
190 impl<'tcx> LateLintPass<'tcx> for QuestionMark {
191 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
192 Self::check_is_none_and_early_return_none(cx, expr);
193 Self::check_if_let_some_and_early_return_none(cx, expr);