1 use rustc_errors::Applicability;
2 use rustc_hir::{Body, Expr, ExprKind, LangItem, MatchSource, QPath};
3 use rustc_lint::{LateContext, LateLintPass, LintContext};
4 use rustc_semver::RustcVersion;
5 use rustc_session::{declare_tool_lint, impl_lint_pass};
9 use if_chain::if_chain;
11 declare_clippy_lint! {
13 /// Suggests alternatives for useless applications of `?` in terminating expressions
15 /// **Why is this bad?** There's no reason to use `?` to short-circuit when execution of the body will end there anyway.
17 /// **Known problems:** None.
23 /// magic: Option<usize>,
26 /// fn f(to: TO) -> Option<usize> {
31 /// magic: Result<usize, bool>,
34 /// fn g(tr: Result<TR, bool>) -> Result<usize, bool> {
35 /// tr.and_then(|t| Ok(t.magic?))
42 /// magic: Option<usize>,
45 /// fn f(to: TO) -> Option<usize> {
50 /// magic: Result<usize, bool>,
53 /// fn g(tr: Result<TR, bool>) -> Result<usize, bool> {
54 /// tr.and_then(|t| t.magic)
57 pub NEEDLESS_QUESTION_MARK,
59 "Suggest `value.inner_option` instead of `Some(value.inner_option?)`. The same goes for `Result<T, E>`."
62 const NEEDLESS_QUESTION_MARK_RESULT_MSRV: RustcVersion = RustcVersion::new(1, 13, 0);
63 const NEEDLESS_QUESTION_MARK_OPTION_MSRV: RustcVersion = RustcVersion::new(1, 22, 0);
65 pub struct NeedlessQuestionMark {
66 msrv: Option<RustcVersion>,
69 impl NeedlessQuestionMark {
71 pub fn new(msrv: Option<RustcVersion>) -> Self {
76 impl_lint_pass!(NeedlessQuestionMark => [NEEDLESS_QUESTION_MARK]);
80 SomeCall(&'a Expr<'a>, &'a Expr<'a>),
81 OkCall(&'a Expr<'a>, &'a Expr<'a>),
84 impl LateLintPass<'_> for NeedlessQuestionMark {
86 * The question mark operator is compatible with both Result<T, E> and Option<T>,
87 * from Rust 1.13 and 1.22 respectively.
92 * Expressions that look like this:
93 * Some(option?), Ok(result?)
96 * Last expression of a body
98 * A body's value (single line closure)
100 * What do we not match:
101 * Implicit calls to `from(..)` on the error value
104 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ Expr<'_>) {
105 let e = match &expr.kind {
106 ExprKind::Ret(Some(e)) => e,
110 if let Some(ok_some_call) = is_some_or_ok_call(self, cx, e) {
111 emit_lint(cx, &ok_some_call);
115 fn check_body(&mut self, cx: &LateContext<'_>, body: &'_ Body<'_>) {
116 // Function / Closure block
117 let expr_opt = if let ExprKind::Block(block, _) = &body.value.kind {
120 // Single line closure
125 if let Some(expr) = expr_opt;
126 if let Some(ok_some_call) = is_some_or_ok_call(self, cx, expr);
128 emit_lint(cx, &ok_some_call);
133 extract_msrv_attr!(LateContext);
136 fn emit_lint(cx: &LateContext<'_>, expr: &SomeOkCall<'_>) {
137 let (entire_expr, inner_expr) = match expr {
138 SomeOkCall::OkCall(outer, inner) | SomeOkCall::SomeCall(outer, inner) => (outer, inner),
141 utils::span_lint_and_sugg(
143 NEEDLESS_QUESTION_MARK,
145 "Question mark operator is useless here",
147 format!("{}", utils::snippet(cx, inner_expr.span, r#""...""#)),
148 Applicability::MachineApplicable,
152 fn is_some_or_ok_call<'a>(
153 nqml: &NeedlessQuestionMark,
154 cx: &'a LateContext<'_>,
156 ) -> Option<SomeOkCall<'a>> {
158 // Check outer expression matches CALL_IDENT(ARGUMENT) format
159 if let ExprKind::Call(path, args) = &expr.kind;
160 if let ExprKind::Path(QPath::Resolved(None, path)) = &path.kind;
161 if utils::is_some_ctor(cx, path.res) || utils::is_ok_ctor(cx, path.res);
163 // Extract inner expression from ARGUMENT
164 if let ExprKind::Match(inner_expr_with_q, _, MatchSource::TryDesugar) = &args[0].kind;
165 if let ExprKind::Call(called, args) = &inner_expr_with_q.kind;
168 if let ExprKind::Path(QPath::LangItem(LangItem::TryIntoResult, _)) = &called.kind;
170 // Extract inner expr type from match argument generated by
171 // question mark operator
172 let inner_expr = &args[0];
174 let inner_ty = cx.typeck_results().expr_ty(inner_expr);
175 let outer_ty = cx.typeck_results().expr_ty(expr);
177 // Check if outer and inner type are Option
178 let outer_is_some = utils::is_type_diagnostic_item(cx, outer_ty, sym::option_type);
179 let inner_is_some = utils::is_type_diagnostic_item(cx, inner_ty, sym::option_type);
181 // Check for Option MSRV
182 let meets_option_msrv = utils::meets_msrv(nqml.msrv.as_ref(), &NEEDLESS_QUESTION_MARK_OPTION_MSRV);
183 if outer_is_some && inner_is_some && meets_option_msrv {
184 return Some(SomeOkCall::SomeCall(expr, inner_expr));
187 // Check if outer and inner type are Result
188 let outer_is_result = utils::is_type_diagnostic_item(cx, outer_ty, sym::result_type);
189 let inner_is_result = utils::is_type_diagnostic_item(cx, inner_ty, sym::result_type);
191 // Additional check: if the error type of the Result can be converted
192 // via the From trait, then don't match
193 let does_not_call_from = !has_implicit_error_from(cx, expr, inner_expr);
195 // Must meet Result MSRV
196 let meets_result_msrv = utils::meets_msrv(nqml.msrv.as_ref(), &NEEDLESS_QUESTION_MARK_RESULT_MSRV);
197 if outer_is_result && inner_is_result && does_not_call_from && meets_result_msrv {
198 return Some(SomeOkCall::OkCall(expr, inner_expr));
206 fn has_implicit_error_from(cx: &LateContext<'_>, entire_expr: &Expr<'_>, inner_result_expr: &Expr<'_>) -> bool {
207 return cx.typeck_results().expr_ty(entire_expr) != cx.typeck_results().expr_ty(inner_result_expr);