Skip to content

Add new case for question_mark lint #13772

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 92 additions & 3 deletions clippy_lints/src/question_mark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,21 @@ use clippy_utils::{
pat_and_expr_can_be_question_mark, path_res, path_to_local, path_to_local_id, peel_blocks, peel_blocks_with_stmt,
span_contains_cfg, span_contains_comment,
};
use itertools::Itertools;
use rustc_errors::Applicability;
use rustc_hir::LangItem::{self, OptionNone, OptionSome, ResultErr, ResultOk};
use rustc_hir::def::Res;
use rustc_hir::intravisit::FnKind;
use rustc_hir::{
Arm, BindingMode, Block, Body, ByRef, Expr, ExprKind, FnRetTy, HirId, LetStmt, MatchSource, Mutability, Node, Pat,
PatKind, PathSegment, QPath, Stmt, StmtKind,
Arm, BindingMode, Block, Body, ByRef, Expr, ExprKind, FnDecl, FnRetTy, HirId, LetStmt, MatchSource, Mutability,
Node, Pat, PatKind, PathSegment, QPath, Stmt, StmtKind,
};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::{self, Ty};
use rustc_session::impl_lint_pass;
use rustc_span::sym;
use rustc_span::def_id::LocalDefId;
use rustc_span::symbol::Symbol;
use rustc_span::{Span, sym};

declare_clippy_lint! {
/// ### What it does
Expand Down Expand Up @@ -456,6 +459,61 @@ fn check_if_let_some_or_err_and_early_return<'tcx>(cx: &LateContext<'tcx>, expr:
}
}

fn check_if_let_some_as_return_val<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>) {
if let Some(higher::IfLet {
let_pat,
let_expr,
if_then,
if_else,
..
}) = higher::IfLet::hir(cx, expr)
&& let PatKind::TupleStruct(ref path1, [field], ddpos) = let_pat.kind
&& ddpos.as_opt_usize().is_none()
&& let PatKind::Binding(BindingMode(by_ref, _), _, ident, None) = field.kind
&& let caller_ty = cx.typeck_results().expr_ty(let_expr)
&& let if_block = IfBlockType::IfLet(
cx.qpath_res(path1, let_pat.hir_id),
caller_ty,
ident.name,
let_expr,
if_then,
if_else,
)
&& let ExprKind::Block(if_then_block, _) = if_then.kind
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There should be a check that this code isn't from an (external) macro expansion (can use in_external_macro)

// Don't consider case where if-then branch has only one statement/expression
&& (if_then_block.stmts.len() >= 2 || if_then_block.stmts.len() == 1 && if_then_block.expr.is_some())
&& (is_early_return(sym::Option, cx, &if_block))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
&& (is_early_return(sym::Option, cx, &if_block))
&& is_early_return(sym::Option, cx, &if_block)

&& if_else
.map(|e| eq_expr_value(cx, let_expr, peel_blocks(e)))
.filter(|e| *e)
.is_none()
Comment on lines +486 to +489
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is this checking for? The is_early_return() checks that the else block is just None so this case seems unreachable to me? Unless you want to exclude specifically if let Some() = None but I'm not sure why

{
let mut applicability = Applicability::MachineApplicable;
let receiver_str = snippet_with_applicability(cx, let_expr.span, "..", &mut applicability);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be snippet_with_context with expr.span.ctxt() for the syntax context, and a test case would be good where the if let scrutinee is a macro invocation:

macro_rules! m { () => { Some(()) } }

fn foo() -> Option<()> {
  if let Some(v) = m!() {
    Some(())
  } else {
    None
  }
}

currently the suggestion contains the macro expansion directly (if let Some(v) = Some(()))

let method_call_str = match by_ref {
ByRef::Yes(Mutability::Mut) => ".as_mut()",
ByRef::Yes(Mutability::Not) => ".as_ref()",
ByRef::No => "",
};

let body = snippet_with_applicability(cx, if_then.span, "..", &mut applicability);
let mut body_lines = body.lines().map(|line| &line[line.len().min(4)..]);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of hardcoding 4, this might be a good use case for clippy_utils::source::indent_of(expr.span)

let (_, _) = (body_lines.next(), body_lines.next_back());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like it could lead to broken suggestions if the whole (or parts of the) if let are on the same line as the if let header. I guess it's a bit of an unusual case considering it lints only when there are at least two statements and rustfmt would split that up into separate lines, but still seems suboptimal especially for a machine applicable suggestion.

I wonder if this could use the inside span of the if block's braces and clippy_utils::source::reindent_multiline?

let body_str = body_lines.join("\n");

let sugg = format!("let {ident} = {receiver_str}{method_call_str}?;\n{body_str}",);
span_lint_and_sugg(
cx,
QUESTION_MARK,
expr.span,
"this block may be rewritten with the `?` operator",
"replace it with",
sugg,
applicability,
);
}
}

impl QuestionMark {
fn inside_try_block(&self) -> bool {
self.try_block_depth_stack.last() > Some(&0)
Expand Down Expand Up @@ -531,6 +589,37 @@ impl<'tcx> LateLintPass<'tcx> for QuestionMark {
self.try_block_depth_stack.push(0);
}

// Defining check_fn instead of using check_body to avoid accidentally triggering on
// const expressions, not sure if this is necessary
Comment on lines +592 to +593
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense to me

fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
_: FnKind<'tcx>,
_: &'tcx FnDecl<'tcx>,
body: &'tcx Body<'tcx>,
_: Span,
_: LocalDefId,
) {
let return_expr = match body.value.kind {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also needs some of the checks that are in check_expr. Notably, a check that this isn't a const fn and that the question_mark_used lint isn't enabled

ExprKind::Block(block, _) => block.expr.or_else(|| {
block.stmts.iter().last().and_then(|stmt| {
if let StmtKind::Semi(expr) = stmt.kind
&& let ExprKind::Ret(Some(ret)) = expr.kind
{
Some(ret)
} else {
None
}
})
}),
_ => None,
};

if let Some(expr) = return_expr {
check_if_let_some_as_return_val(cx, expr);
}
}

fn check_body_post(&mut self, _: &LateContext<'tcx>, _: &Body<'tcx>) {
self.try_block_depth_stack.pop();
}
Expand Down
21 changes: 21 additions & 0 deletions tests/ui/question_mark.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -373,3 +373,24 @@ fn issue12412(foo: &Foo, bar: &Bar) -> Option<()> {
let v = bar.foo.owned.clone()?;
Some(())
}

mod issue13626 {
fn basic_test(x: Option<u32>) -> Option<u32> {
let x = x?;
dbg!(x);
Some(x * 2)
}

fn mut_ref_test(mut x: Option<u32>) -> Option<u32> {
let x = x.as_mut()?;
dbg!(*x);
Some(*x * 2)
}

#[allow(clippy::needless_return)]
fn explicit_return_test(x: Option<u32>) -> Option<u32> {
let x = x?;
dbg!(x);
return Some(x * 2);
}
}
30 changes: 30 additions & 0 deletions tests/ui/question_mark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -430,3 +430,33 @@ fn issue12412(foo: &Foo, bar: &Bar) -> Option<()> {
};
Some(())
}

mod issue13626 {
fn basic_test(x: Option<u32>) -> Option<u32> {
if let Some(x) = x {
dbg!(x);
Some(x * 2)
} else {
None
}
}

fn mut_ref_test(mut x: Option<u32>) -> Option<u32> {
if let Some(ref mut x) = x {
dbg!(*x);
Some(*x * 2)
} else {
None
}
}

#[allow(clippy::needless_return)]
fn explicit_return_test(x: Option<u32>) -> Option<u32> {
if let Some(x) = x {
dbg!(x);
return Some(x * 2);
} else {
return None;
}
}
}
56 changes: 55 additions & 1 deletion tests/ui/question_mark.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -196,5 +196,59 @@ LL | | return None;
LL | | };
| |______^ help: replace it with: `let v = bar.foo.owned.clone()?;`

error: aborting due to 22 previous errors
error: this block may be rewritten with the `?` operator
--> tests/ui/question_mark.rs:436:9
|
LL | / if let Some(x) = x {
LL | | dbg!(x);
LL | | Some(x * 2)
LL | | } else {
LL | | None
LL | | }
| |_________^
|
help: replace it with
|
LL ~ let x = x?;
LL + dbg!(x);
LL + Some(x * 2)
|

error: this block may be rewritten with the `?` operator
--> tests/ui/question_mark.rs:445:9
|
LL | / if let Some(ref mut x) = x {
LL | | dbg!(*x);
LL | | Some(*x * 2)
LL | | } else {
LL | | None
LL | | }
| |_________^
|
help: replace it with
|
LL ~ let x = x.as_mut()?;
LL + dbg!(*x);
LL + Some(*x * 2)
|

error: this block may be rewritten with the `?` operator
--> tests/ui/question_mark.rs:455:9
|
LL | / if let Some(x) = x {
LL | | dbg!(x);
LL | | return Some(x * 2);
LL | | } else {
LL | | return None;
LL | | }
| |_________^
|
help: replace it with
|
LL ~ let x = x?;
LL + dbg!(x);
LL + return Some(x * 2);
|

error: aborting due to 25 previous errors

Loading