rust-lang / rust-lang/rust-clippy

`unnecessary-operation` suggestion on `[();1][<expr>]` is werid

Open
#12,817 0 comments 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

Summary

Because of my minimal rust version (1.56), I have to use the hack [(); 1][<expr>] in const block for const assertions.

Lint Name

unnecessary-operation

Reproducer

I tried this code:

const _: () = {
    use std::os::windows::io::RawHandle;
    let std_layout = Layout::new::<RawHandle>();
    let win_sys_layout = Layout::new::<usize>();
    // MSRV(Rust v1.57): use assert! instead
    [(); 1][std_layout.size() - win_sys_layout.size()];
};

I saw this happen:

error: unnecessary operation
  --> src/internals/c.rs:42:5
   |
42 |     [(); 1][std_layout.size() - win_sys_layout.size()];
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: statement can be written as: `assert!([(); 1].len() > std_layout.size() - win_sys_layout.size());`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_operation
   = note: `-D clippy::unnecessary-operation` implied by `-D warnings`

I expected to see this happen: It's my fault for using nightly clippy for msrv, however I expect that clippy should suggest

assert!(std_layout.size() == win_sys_layout.size());
Version
rustc 1.80.0-nightly (1a7397988 2024-05-17)
binary: rustc
commit-hash: 1a7397988684934ae01a71f524bdfff24895d8cc
commit-date: 2024-05-17
host: x86_64-unknown-linux-gnu
release: 1.80.0-nightly
LLVM version: 18.1.4
Additional Labels

No response

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 reproducer in the issue and inspect the unnecessary-operation lint behavior around src/internals/c.rs:42. Compare the current suggestion with the expected assertion shown in the report. Done means the lint handles this [(); 1][] const-assertion pattern without suggesting the misleading replacement, with coverage for the reported case.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.