rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
10.89k stars 1.46k forks source link

box_default causes type error #12684

Closed matthiaskrgr closed 1 week ago

matthiaskrgr commented 3 weeks ago

Summary

.

Lint Name

box_default

Reproducer

I tried this code:

//@revisions: stack tree
//@[tree]compile-flags: -Zmiri-tree-borrows
use std::cell::UnsafeCell;

#[repr(C)]
#[derive(Default)]
struct Node {
    _meta: UnsafeCell<usize>,
    value: usize,
}

impl Node {
    fn value(&self) -> &usize {
        &self.value
    }
}

/// This used to cause Stacked Borrows errors because of trouble around conversion
/// from Box to raw pointer.
fn main() {
    unsafe {
        let a = Box::into_raw(Box::new(Node::default()));
        let ptr = &*a;
        *UnsafeCell::raw_get(a.cast::<UnsafeCell<usize>>()) = 2;
        assert_eq!(*ptr.value(), 0);
        drop(Box::from_raw(a));
    }
}

I saw this happen:

warning: `Box::new(_)` of default value
  --> ./src/tools/miri/tests/pass/issues/issue-miri-3473.rs:22:31
   |
22 |         let a = Box::into_raw(Box::new(Node::default()));
   |                               ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Box::default()`
   |

it does not build;

error[E0282]: type annotations needed for `*mut _`
  --> ./src/tools/miri/tests/pass/issues/issue-miri-3473.rs:22:13
   |
22 |         let a = Box::into_raw(Box::default());
   |             ^
...
25 |         assert_eq!(*ptr.value(), 0);
   |                         ----- type must be known at this point
   |
help: consider giving `a` an explicit type, where the type for type parameter `T` is specified
   |
22 |         let a: *mut T = Box::into_raw(Box::default());
   |              ++++++++

error: aborting due to 1 previous error; 1 warning emitted

Version

rustc 1.79.0-nightly (1cec373f6 2024-04-16)
binary: rustc
commit-hash: 1cec373f65eb76e8e4b4d1847213cf3ec6c292b6
commit-date: 2024-04-16
host: x86_64-unknown-linux-gnu
release: 1.79.0-nightly
LLVM version: 18.1.3

Additional Labels

No response

matthiaskrgr commented 3 weeks ago

maybe we have to suggest Box::::default() or something?