1 use if_chain::if_chain;
2 use rustc_errors::Applicability;
3 use rustc_hir::def::{DefKind, Res};
4 use rustc_hir::{def, BindingAnnotation, Block, Expr, ExprKind, MatchSource, PatKind, StmtKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use crate::utils::paths::{OPTION, OPTION_NONE};
9 use crate::utils::sugg::Sugg;
11 higher, match_def_path, match_qpath, match_type, snippet_with_applicability, span_lint_and_then, SpanlessEq,
14 declare_clippy_lint! {
15 /// **What it does:** Checks for expressions that could be replaced by the question mark operator.
17 /// **Why is this bad?** Question mark usage is more idiomatic.
19 /// **Known problems:** None
23 /// if option.is_none() {
35 "checks for expressions that could be replaced by the question mark operator"
38 declare_lint_pass!(QuestionMark => [QUESTION_MARK]);
41 /// Checks if the given expression on the given context matches the following structure:
44 /// if option.is_none() {
49 /// If it matches, it will suggest to use the question mark operator instead
50 fn check_is_none_and_early_return_none(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
52 if let Some((if_expr, body, else_)) = higher::if_block(&expr);
53 if let ExprKind::MethodCall(segment, _, args) = &if_expr.kind;
54 if segment.ident.name == sym!(is_none);
55 if Self::expression_returns_none(cx, body);
56 if let Some(subject) = args.get(0);
57 if Self::is_option(cx, subject);
60 let mut applicability = Applicability::MachineApplicable;
61 let receiver_str = snippet_with_applicability(cx, subject.span, "..", &mut applicability);
62 let mut replacement: Option<String> = None;
63 if let Some(else_) = else_ {
65 if let ExprKind::Block(block, None) = &else_.kind;
66 if block.stmts.is_empty();
67 if let Some(block_expr) = &block.expr;
68 if SpanlessEq::new(cx).ignore_fn().eq_expr(subject, block_expr);
70 replacement = Some(format!("Some({}?)", receiver_str));
73 } else if Self::moves_by_default(cx, subject) {
74 replacement = Some(format!("{}.as_ref()?;", receiver_str));
76 replacement = Some(format!("{}?;", receiver_str));
79 if let Some(replacement_str) = replacement {
84 "this block may be rewritten with the `?` operator",
99 fn check_if_let_some_and_early_return_none(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
101 if let ExprKind::Match(subject, arms, source) = &expr.kind;
102 if *source == MatchSource::IfLetDesugar { contains_else_clause: true };
103 if Self::is_option(cx, subject);
105 if let PatKind::TupleStruct(path1, fields, None) = &arms[0].pat.kind;
106 if match_qpath(path1, &["Some"]);
107 if let PatKind::Binding(annot, _, bind, _) = &fields[0].kind;
108 let by_ref = matches!(annot, BindingAnnotation::Ref | BindingAnnotation::RefMut);
110 if let ExprKind::Block(block, None) = &arms[0].body.kind;
111 if block.stmts.is_empty();
112 if let Some(trailing_expr) = &block.expr;
113 if let ExprKind::Path(path) = &trailing_expr.kind;
114 if match_qpath(path, &[&bind.as_str()]);
116 if let PatKind::Wild = arms[1].pat.kind;
117 if Self::expression_returns_none(cx, arms[1].body);
119 let mut applicability = Applicability::MachineApplicable;
120 let receiver_str = snippet_with_applicability(cx, subject.span, "..", &mut applicability);
121 let replacement = format!(
124 if by_ref { ".as_ref()" } else { "" },
131 "this if-let-else may be rewritten with the `?` operator",
145 fn moves_by_default(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool {
146 let expr_ty = cx.tables.expr_ty(expression);
148 !expr_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, expression.span)
151 fn is_option(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool {
152 let expr_ty = cx.tables.expr_ty(expression);
154 match_type(cx, expr_ty, &OPTION)
157 fn expression_returns_none(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool {
158 match expression.kind {
159 ExprKind::Block(ref block, _) => {
160 if let Some(return_expression) = Self::return_expression(block) {
161 return Self::expression_returns_none(cx, &return_expression);
166 ExprKind::Ret(Some(ref expr)) => Self::expression_returns_none(cx, expr),
167 ExprKind::Path(ref qp) => {
168 if let Res::Def(DefKind::Ctor(def::CtorOf::Variant, def::CtorKind::Const), def_id) =
169 cx.tables.qpath_res(qp, expression.hir_id)
171 return match_def_path(cx, def_id, &OPTION_NONE);
180 fn return_expression<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
181 // Check if last expression is a return statement. Then, return the expression
183 if block.stmts.len() == 1;
184 if let Some(expr) = block.stmts.iter().last();
185 if let StmtKind::Semi(ref expr) = expr.kind;
186 if let ExprKind::Ret(ret_expr) = expr.kind;
187 if let Some(ret_expr) = ret_expr;
190 return Some(ret_expr);
194 // Check for `return` without a semicolon.
196 if block.stmts.is_empty();
197 if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.kind);
199 return Some(ret_expr);
207 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for QuestionMark {
208 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
209 Self::check_is_none_and_early_return_none(cx, expr);
210 Self::check_if_let_some_and_early_return_none(cx, expr);