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::sugg::Sugg;
10 higher, is_type_diagnostic_item, match_def_path, match_qpath, paths, snippet_with_applicability, span_lint_and_sugg, SpanlessEq,
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 Some((if_expr, body, else_)) = higher::if_block(&expr);
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 SpanlessEq::new(cx).ignore_fn().eq_expr(subject, block_expr);
69 replacement = Some(format!("Some({}?)", receiver_str));
72 } else if Self::moves_by_default(cx, subject) {
73 replacement = Some(format!("{}.as_ref()?;", receiver_str));
75 replacement = Some(format!("{}?;", receiver_str));
78 if let Some(replacement_str) = replacement {
83 "this block may be rewritten with the `?` operator",
93 fn check_if_let_some_and_early_return_none(cx: &LateContext<'_, '_>, expr: &Expr<'_>) {
95 if let ExprKind::Match(subject, arms, source) = &expr.kind;
96 if *source == MatchSource::IfLetDesugar { contains_else_clause: true };
97 if Self::is_option(cx, subject);
99 if let PatKind::TupleStruct(path1, fields, None) = &arms[0].pat.kind;
100 if match_qpath(path1, &["Some"]);
101 if let PatKind::Binding(annot, _, bind, _) = &fields[0].kind;
102 let by_ref = matches!(annot, BindingAnnotation::Ref | BindingAnnotation::RefMut);
104 if let ExprKind::Block(block, None) = &arms[0].body.kind;
105 if block.stmts.is_empty();
106 if let Some(trailing_expr) = &block.expr;
107 if let ExprKind::Path(path) = &trailing_expr.kind;
108 if match_qpath(path, &[&bind.as_str()]);
110 if let PatKind::Wild = arms[1].pat.kind;
111 if Self::expression_returns_none(cx, arms[1].body);
113 let mut applicability = Applicability::MachineApplicable;
114 let receiver_str = snippet_with_applicability(cx, subject.span, "..", &mut applicability);
115 let replacement = format!(
118 if by_ref { ".as_ref()" } else { "" },
125 "this if-let-else may be rewritten with the `?` operator",
134 fn moves_by_default(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool {
135 let expr_ty = cx.tables.expr_ty(expression);
137 !expr_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, expression.span)
140 fn is_option(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool {
141 let expr_ty = cx.tables.expr_ty(expression);
143 is_type_diagnostic_item(cx, expr_ty, sym!(option_type))
146 fn expression_returns_none(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool {
147 match expression.kind {
148 ExprKind::Block(ref block, _) => {
149 if let Some(return_expression) = Self::return_expression(block) {
150 return Self::expression_returns_none(cx, &return_expression);
155 ExprKind::Ret(Some(ref expr)) => Self::expression_returns_none(cx, expr),
156 ExprKind::Path(ref qp) => {
157 if let Res::Def(DefKind::Ctor(def::CtorOf::Variant, def::CtorKind::Const), def_id) =
158 cx.tables.qpath_res(qp, expression.hir_id)
160 return match_def_path(cx, def_id, &paths::OPTION_NONE);
169 fn return_expression<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
170 // Check if last expression is a return statement. Then, return the expression
172 if block.stmts.len() == 1;
173 if let Some(expr) = block.stmts.iter().last();
174 if let StmtKind::Semi(ref expr) = expr.kind;
175 if let ExprKind::Ret(ret_expr) = expr.kind;
176 if let Some(ret_expr) = ret_expr;
179 return Some(ret_expr);
183 // Check for `return` without a semicolon.
185 if block.stmts.is_empty();
186 if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.kind);
188 return Some(ret_expr);
196 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for QuestionMark {
197 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
198 Self::check_is_none_and_early_return_none(cx, expr);
199 Self::check_if_let_some_and_early_return_none(cx, expr);