1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::is_lang_ctor;
3 use clippy_utils::source::snippet;
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::LangItem::{OptionSome, ResultOk};
7 use rustc_hir::{Body, Expr, ExprKind, LangItem, MatchSource, QPath};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::ty::TyS;
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 declare_clippy_lint! {
14 /// Suggests alternatives for useless applications of `?` in terminating expressions
16 /// ### Why is this bad?
17 /// There's no reason to use `?` to short-circuit when execution of the body will end there anyway.
22 /// magic: Option<usize>,
25 /// fn f(to: TO) -> Option<usize> {
30 /// magic: Result<usize, bool>,
33 /// fn g(tr: Result<TR, bool>) -> Result<usize, bool> {
34 /// tr.and_then(|t| Ok(t.magic?))
41 /// magic: Option<usize>,
44 /// fn f(to: TO) -> Option<usize> {
49 /// magic: Result<usize, bool>,
52 /// fn g(tr: Result<TR, bool>) -> Result<usize, bool> {
53 /// tr.and_then(|t| t.magic)
56 pub NEEDLESS_QUESTION_MARK,
58 "Suggest `value.inner_option` instead of `Some(value.inner_option?)`. The same goes for `Result<T, E>`."
61 declare_lint_pass!(NeedlessQuestionMark => [NEEDLESS_QUESTION_MARK]);
63 impl LateLintPass<'_> for NeedlessQuestionMark {
65 * The question mark operator is compatible with both Result<T, E> and Option<T>,
66 * from Rust 1.13 and 1.22 respectively.
71 * Expressions that look like this:
72 * Some(option?), Ok(result?)
75 * Last expression of a body
77 * A body's value (single line closure)
79 * What do we not match:
80 * Implicit calls to `from(..)` on the error value
83 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ Expr<'_>) {
84 if let ExprKind::Ret(Some(e)) = expr.kind {
89 fn check_body(&mut self, cx: &LateContext<'_>, body: &'_ Body<'_>) {
90 check(cx, body.value.peel_blocks());
94 fn check(cx: &LateContext<'_>, expr: &Expr<'_>) {
95 let inner_expr = if_chain! {
96 if let ExprKind::Call(path, [arg]) = &expr.kind;
97 if let ExprKind::Path(ref qpath) = &path.kind;
98 if is_lang_ctor(cx, qpath, OptionSome) || is_lang_ctor(cx, qpath, ResultOk);
99 if let ExprKind::Match(inner_expr_with_q, _, MatchSource::TryDesugar) = &arg.kind;
100 if let ExprKind::Call(called, [inner_expr]) = &inner_expr_with_q.kind;
101 if let ExprKind::Path(QPath::LangItem(LangItem::TryTraitBranch, _)) = &called.kind;
102 if expr.span.ctxt() == inner_expr.span.ctxt();
103 let expr_ty = cx.typeck_results().expr_ty(expr);
104 let inner_ty = cx.typeck_results().expr_ty(inner_expr);
105 if TyS::same_type(expr_ty, inner_ty);
106 then { inner_expr } else { return; }
110 NEEDLESS_QUESTION_MARK,
112 "question mark operator is useless here",
114 format!("{}", snippet(cx, inner_expr.span, r#""...""#)),
115 Applicability::MachineApplicable,