1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::higher;
3 use clippy_utils::is_lang_ctor;
4 use clippy_utils::source::snippet_with_applicability;
5 use clippy_utils::sugg::Sugg;
6 use clippy_utils::ty::is_type_diagnostic_item;
7 use clippy_utils::{eq_expr_value, path_to_local, path_to_local_id};
8 use if_chain::if_chain;
9 use rustc_errors::Applicability;
10 use rustc_hir::LangItem::{OptionNone, OptionSome, ResultOk};
11 use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, PatKind, StmtKind};
12 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_session::{declare_lint_pass, declare_tool_lint};
16 declare_clippy_lint! {
18 /// Checks for expressions that could be replaced by the question mark operator.
20 /// ### Why is this bad?
21 /// Question mark usage is more idiomatic.
25 /// if option.is_none() {
37 "checks for expressions that could be replaced by the question mark operator"
40 declare_lint_pass!(QuestionMark => [QUESTION_MARK]);
43 /// Checks if the given expression on the given context matches the following structure:
46 /// if option.is_none() {
52 /// if result.is_err() {
57 /// If it matches, it will suggest to use the question mark operator instead
58 fn check_is_none_or_err_and_early_return(cx: &LateContext<'_>, expr: &Expr<'_>) {
60 if let Some(higher::If { cond, then, r#else }) = higher::If::hir(expr);
61 if let ExprKind::MethodCall(segment, _, args, _) = &cond.kind;
62 if let Some(subject) = args.get(0);
63 if (Self::is_option(cx, subject)
64 && Self::expression_returns_none(cx, then)
65 && segment.ident.name == sym!(is_none))
67 (Self::is_result(cx, subject)
68 && Self::expression_returns_unmodified_err(cx, then, subject)
69 && segment.ident.name == sym!(is_err));
71 let mut applicability = Applicability::MachineApplicable;
72 let receiver_str = &Sugg::hir_with_applicability(cx, subject, "..", &mut applicability);
73 let mut replacement: Option<String> = None;
74 if let Some(else_inner) = r#else {
76 if let ExprKind::Block(block, None) = &else_inner.kind;
77 if block.stmts.is_empty();
78 if let Some(block_expr) = &block.expr;
79 if eq_expr_value(cx, subject, block_expr);
81 replacement = Some(format!("Some({}?)", receiver_str));
84 } else if Self::moves_by_default(cx, subject)
85 && !matches!(subject.kind, ExprKind::Call(..) | ExprKind::MethodCall(..))
87 replacement = Some(format!("{}.as_ref()?;", receiver_str));
89 replacement = Some(format!("{}?;", receiver_str));
92 if let Some(replacement_str) = replacement {
97 "this block may be rewritten with the `?` operator",
107 fn check_if_let_some_or_err_and_early_return(cx: &LateContext<'_>, expr: &Expr<'_>) {
109 if let Some(higher::IfLet { let_pat, let_expr, if_then, if_else: Some(if_else) })
110 = higher::IfLet::hir(cx, expr);
111 if let PatKind::TupleStruct(ref path1, fields, None) = let_pat.kind;
112 if (Self::is_option(cx, let_expr)
113 && Self::expression_returns_none(cx, if_else)
114 && is_lang_ctor(cx, path1, OptionSome))
116 (Self::is_result(cx, let_expr)
117 && Self::expression_returns_unmodified_err(cx, if_else, let_expr)
118 && is_lang_ctor(cx, path1, ResultOk));
120 if let PatKind::Binding(annot, bind_id, _, _) = fields[0].kind;
121 let by_ref = matches!(annot, BindingAnnotation::Ref | BindingAnnotation::RefMut);
122 if let ExprKind::Block(block, None) = if_then.kind;
123 if block.stmts.is_empty();
124 if let Some(trailing_expr) = &block.expr;
125 if path_to_local_id(trailing_expr, bind_id);
127 let mut applicability = Applicability::MachineApplicable;
128 let receiver_str = snippet_with_applicability(cx, let_expr.span, "..", &mut applicability);
129 let replacement = format!("{}{}?", receiver_str, if by_ref { ".as_ref()" } else { "" },);
135 "this if-let-else may be rewritten with the `?` operator",
144 fn moves_by_default(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
145 let expr_ty = cx.typeck_results().expr_ty(expression);
147 !expr_ty.is_copy_modulo_regions(cx.tcx.at(expression.span), cx.param_env)
150 fn is_option(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
151 let expr_ty = cx.typeck_results().expr_ty(expression);
153 is_type_diagnostic_item(cx, expr_ty, sym::Option)
156 fn is_result(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
157 let expr_ty = cx.typeck_results().expr_ty(expression);
159 is_type_diagnostic_item(cx, expr_ty, sym::Result)
162 fn expression_returns_none(cx: &LateContext<'_>, expression: &Expr<'_>) -> bool {
163 match expression.kind {
164 ExprKind::Block(block, _) => {
165 if let Some(return_expression) = Self::return_expression(block) {
166 return Self::expression_returns_none(cx, return_expression);
171 ExprKind::Ret(Some(expr)) => Self::expression_returns_none(cx, expr),
172 ExprKind::Path(ref qpath) => is_lang_ctor(cx, qpath, OptionNone),
177 fn expression_returns_unmodified_err(
178 cx: &LateContext<'_>,
179 expression: &Expr<'_>,
180 origin_hir_id: &Expr<'_>,
182 match expression.kind {
183 ExprKind::Block(block, _) => {
184 if let Some(return_expression) = Self::return_expression(block) {
185 return Self::expression_returns_unmodified_err(cx, return_expression, origin_hir_id);
190 ExprKind::Ret(Some(expr)) | ExprKind::Call(expr, _) => {
191 Self::expression_returns_unmodified_err(cx, expr, origin_hir_id)
193 ExprKind::Path(_) => path_to_local(expression) == path_to_local(origin_hir_id),
198 fn return_expression<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
199 // Check if last expression is a return statement. Then, return the expression
201 if block.stmts.len() == 1;
202 if let Some(expr) = block.stmts.iter().last();
203 if let StmtKind::Semi(expr) = expr.kind;
204 if let ExprKind::Ret(Some(ret_expr)) = expr.kind;
207 return Some(ret_expr);
211 // Check for `return` without a semicolon.
213 if block.stmts.is_empty();
214 if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.kind);
216 return Some(ret_expr);
224 impl<'tcx> LateLintPass<'tcx> for QuestionMark {
225 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
226 Self::check_is_none_or_err_and_early_return(cx, expr);
227 Self::check_if_let_some_or_err_and_early_return(cx, expr);