1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet;
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use clippy_utils::{is_ok_ctor, is_some_ctor, meets_msrv};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::{Body, Expr, ExprKind, LangItem, MatchSource, QPath};
8 use rustc_lint::{LateContext, LateLintPass, LintContext};
9 use rustc_semver::RustcVersion;
10 use rustc_session::{declare_tool_lint, impl_lint_pass};
13 declare_clippy_lint! {
15 /// Suggests alternatives for useless applications of `?` in terminating expressions
17 /// **Why is this bad?** There's no reason to use `?` to short-circuit when execution of the body will end there anyway.
19 /// **Known problems:** None.
25 /// magic: Option<usize>,
28 /// fn f(to: TO) -> Option<usize> {
33 /// magic: Result<usize, bool>,
36 /// fn g(tr: Result<TR, bool>) -> Result<usize, bool> {
37 /// tr.and_then(|t| Ok(t.magic?))
44 /// magic: Option<usize>,
47 /// fn f(to: TO) -> Option<usize> {
52 /// magic: Result<usize, bool>,
55 /// fn g(tr: Result<TR, bool>) -> Result<usize, bool> {
56 /// tr.and_then(|t| t.magic)
59 pub NEEDLESS_QUESTION_MARK,
61 "Suggest `value.inner_option` instead of `Some(value.inner_option?)`. The same goes for `Result<T, E>`."
64 const NEEDLESS_QUESTION_MARK_RESULT_MSRV: RustcVersion = RustcVersion::new(1, 13, 0);
65 const NEEDLESS_QUESTION_MARK_OPTION_MSRV: RustcVersion = RustcVersion::new(1, 22, 0);
67 pub struct NeedlessQuestionMark {
68 msrv: Option<RustcVersion>,
71 impl NeedlessQuestionMark {
73 pub fn new(msrv: Option<RustcVersion>) -> Self {
78 impl_lint_pass!(NeedlessQuestionMark => [NEEDLESS_QUESTION_MARK]);
82 SomeCall(&'a Expr<'a>, &'a Expr<'a>),
83 OkCall(&'a Expr<'a>, &'a Expr<'a>),
86 impl LateLintPass<'_> for NeedlessQuestionMark {
88 * The question mark operator is compatible with both Result<T, E> and Option<T>,
89 * from Rust 1.13 and 1.22 respectively.
94 * Expressions that look like this:
95 * Some(option?), Ok(result?)
98 * Last expression of a body
100 * A body's value (single line closure)
102 * What do we not match:
103 * Implicit calls to `from(..)` on the error value
106 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ Expr<'_>) {
107 let e = match &expr.kind {
108 ExprKind::Ret(Some(e)) => e,
112 if let Some(ok_some_call) = is_some_or_ok_call(self, cx, e) {
113 emit_lint(cx, &ok_some_call);
117 fn check_body(&mut self, cx: &LateContext<'_>, body: &'_ Body<'_>) {
118 // Function / Closure block
119 let expr_opt = if let ExprKind::Block(block, _) = &body.value.kind {
122 // Single line closure
127 if let Some(expr) = expr_opt;
128 if let Some(ok_some_call) = is_some_or_ok_call(self, cx, expr);
130 emit_lint(cx, &ok_some_call);
135 extract_msrv_attr!(LateContext);
138 fn emit_lint(cx: &LateContext<'_>, expr: &SomeOkCall<'_>) {
139 let (entire_expr, inner_expr) = match expr {
140 SomeOkCall::OkCall(outer, inner) | SomeOkCall::SomeCall(outer, inner) => (outer, inner),
145 NEEDLESS_QUESTION_MARK,
147 "question mark operator is useless here",
149 format!("{}", snippet(cx, inner_expr.span, r#""...""#)),
150 Applicability::MachineApplicable,
154 fn is_some_or_ok_call<'a>(
155 nqml: &NeedlessQuestionMark,
156 cx: &'a LateContext<'_>,
158 ) -> Option<SomeOkCall<'a>> {
160 // Check outer expression matches CALL_IDENT(ARGUMENT) format
161 if let ExprKind::Call(path, args) = &expr.kind;
162 if let ExprKind::Path(QPath::Resolved(None, path)) = &path.kind;
163 if is_some_ctor(cx, path.res) || is_ok_ctor(cx, path.res);
165 // Extract inner expression from ARGUMENT
166 if let ExprKind::Match(inner_expr_with_q, _, MatchSource::TryDesugar) = &args[0].kind;
167 if let ExprKind::Call(called, args) = &inner_expr_with_q.kind;
170 if let ExprKind::Path(QPath::LangItem(LangItem::TryIntoResult, _)) = &called.kind;
172 // Extract inner expr type from match argument generated by
173 // question mark operator
174 let inner_expr = &args[0];
176 let inner_ty = cx.typeck_results().expr_ty(inner_expr);
177 let outer_ty = cx.typeck_results().expr_ty(expr);
179 // Check if outer and inner type are Option
180 let outer_is_some = is_type_diagnostic_item(cx, outer_ty, sym::option_type);
181 let inner_is_some = is_type_diagnostic_item(cx, inner_ty, sym::option_type);
183 // Check for Option MSRV
184 let meets_option_msrv = meets_msrv(nqml.msrv.as_ref(), &NEEDLESS_QUESTION_MARK_OPTION_MSRV);
185 if outer_is_some && inner_is_some && meets_option_msrv {
186 return Some(SomeOkCall::SomeCall(expr, inner_expr));
189 // Check if outer and inner type are Result
190 let outer_is_result = is_type_diagnostic_item(cx, outer_ty, sym::result_type);
191 let inner_is_result = is_type_diagnostic_item(cx, inner_ty, sym::result_type);
193 // Additional check: if the error type of the Result can be converted
194 // via the From trait, then don't match
195 let does_not_call_from = !has_implicit_error_from(cx, expr, inner_expr);
197 // Must meet Result MSRV
198 let meets_result_msrv = meets_msrv(nqml.msrv.as_ref(), &NEEDLESS_QUESTION_MARK_RESULT_MSRV);
199 if outer_is_result && inner_is_result && does_not_call_from && meets_result_msrv {
200 return Some(SomeOkCall::OkCall(expr, inner_expr));
208 fn has_implicit_error_from(cx: &LateContext<'_>, entire_expr: &Expr<'_>, inner_result_expr: &Expr<'_>) -> bool {
209 return cx.typeck_results().expr_ty(entire_expr) != cx.typeck_results().expr_ty(inner_result_expr);