rust-lang / rust-lang/rust-clippy

`needless_borrow` suggestion causes error when using conditional compilation

Open
#11,908 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Summary

Clippy falsely suggests to remove borrow when using conditional compilation.

Based on the example below, if we listen to clippy and remove borrow (&path -> path), code will compile on any OS but Windows. On Windows however it will throw this error: borrow of moved value: path

Lint Name

clippy::needless_borrow

Reproducer

I tried this code:

use std::{fs, path::PathBuf};

fn main() {
	let path = PathBuf::from(".").canonicalize().unwrap();

	fs::write(&path, "test").ok();

	#[cfg(target_os = "windows")]
	println!("{:?}", path);
}

I saw this happen:

main.rs(6, 12): change this to: `path`

I expected to see this happen:
No suggestion at all

Version
rustc 1.73.0 (cc66ad468 2023-10-03)
binary: rustc
commit-hash: cc66ad468955717ab92600c770da8c1601a4ff33
commit-date: 2023-10-03
host: aarch64-apple-darwin
release: 1.73.0
LLVM version: 17.0.2
Additional Labels

@rustbot label I-suggestion-causes-error

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::needless_borrow implementation and reproduce the supplied Rust example with the Windows-only println!. Trace how conditional compilation affects the borrow analysis; done means the lint no longer emits a suggestion that causes a borrow-of-moved-value error on Windows.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.