rust-lang / rust-lang/rust-clippy

clippy::question_mark suggests code that's more confusing than before

Open
#7,967 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Lint name: clippy::question_mark

I tried this code:

pub struct Message;
pub struct MessageUpdateEvent { content: Option<String> }

pub fn process_message_update(
    user_msg_update: MessageUpdateEvent,
) -> Option<Message> {
    // [some code]
    
    // If message content wasn't touched, don't re-run command
    if user_msg_update.content.is_none() {
        return None;
    }
    
    // [more code]
    
    Some(Message)
}

(for more context, see https://github.com/kangalioo/poise/blob/19bcc0afef2c77533a4e2f0a4aaffa4baea74f2a/src/prefix/track_edits.rs#L85-L92)

I expected to see this happen: no warning is emitted

Why: semantically, the ? operator is meant for propagating exceptional values which the current function doesn't want to deal with. The semantics in this code are different, so usage of ? would be confusing and make it harder to figure what is actually happening here

Instead, this happened: Clippy suggested to replace the check with user_msg_update.content.as_ref()?;

I am not sure how or if Clippy can detect intended semantics of if value.is_none() { return None; }. The best course of action may be to keep this lint as is, if it's not worth it to accommodate this small issue

Meta

Rust version (rustc -Vv):

rustc 1.55.0 (c8dfcfe04 2021-09-06)
binary: rustc
commit-hash: c8dfcfe046a7680554bf4eb612bad840e7631c4b
commit-date: 2021-09-06
host: x86_64-unknown-linux-gnu
release: 1.55.0
LLVM version: 12.0.1

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the clippy::question_mark lint and compare its suggestion against the linked track_edits.rs example at lines 85-92. Review the lint's existing behavior and tests, then determine whether this pattern should be excluded or documented; done means the example no longer receives a misleading suggestion, or the decision is covered by a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.