rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

`borrow_as_ptr` false negative when borrowing a temporary literal

Open xtqqczze opened this issue 2 weeks ago • 5 comments

Summary

The borrow_as_ptr lint is emitted for borrowing a local variable as a raw pointer, but it is not emitted when the borrowed expression is a temporary literal.

Lint Name

borrow_as_ptr

Reproducer

the lint does not fire for m1, but does for m2

#[inline(never)]
pub fn m1() {
    let _ptr = &42f32 as *const f32;
}

#[inline(never)]
pub fn m2() {
    let tmp = 42f32;
    let _ptr = &tmp as *const f32;
}

https://godbolt.org/z/xoPTzr6sx

Version


xtqqczze avatar Dec 11 '25 14:12 xtqqczze

&raw const and ptr::addr_or can't be used on temporary values. Suggesting to add an additional local in order to avoid the cast is excessive.

Jarcho avatar Dec 11 '25 15:12 Jarcho

&raw const can't be used on temporary values

I wonder why not, since it seems to work fine with the cast version (let _ptr = &42f32 as *const f32;). It's called lifetime extension IIRC.

krobelus avatar Dec 11 '25 15:12 krobelus

this could also be written as:

#[inline(never)]
pub fn m1() {
    let ptr = std::ptr::from_ref(&42f32);
}

xtqqczze avatar Dec 11 '25 16:12 xtqqczze

Related: https://github.com/rust-lang/rust-clippy/pull/16214

xtqqczze avatar Dec 11 '25 16:12 xtqqczze

You can't use from_ref for this since it doesn't extend the lifetime. Technically you can in that specific case due to const promotion, but you can't in general with a temporary.

Jarcho avatar Dec 11 '25 17:12 Jarcho