rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
97.5k stars 12.61k forks source link

Produce a warning when using `const` with interior mutability #40543

Open matklad opened 7 years ago

matklad commented 7 years ago

Originally reported in https://users.rust-lang.org/t/broken-atomics-puzzle/9533

Consider this code

use std::sync::atomic::{AtomicBool, Ordering};

pub const A: AtomicBool = AtomicBool::new(false);

fn main() {
    A.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst);
    println!("A = {}", A.load(Ordering::SeqCst));
}

Playground

It compiles and runs cleanly, but produces unexpected results because const is used instead of static.

It would be nice to somehow give a warning for .compare_and_swap call, but I am not sure it is possible.

petrochenkov commented 7 years ago

cc https://github.com/rust-lang/rfcs/issues/885 https://github.com/Manishearth/rust-clippy/issues/829

matklad commented 7 years ago

Note that compare_and_swap uses &self:

compare_and_swap(&self, current: bool, new: bool, order: Ordering) -> bool
petrochenkov commented 7 years ago

The underlying issue is the same - A is a rvalue and copied on use and this becomes observable when any mutability is involved, interior or exterior.

steveklabnik commented 7 years ago

New warnings generally require an RFC, but I'll let @rust-lang/compiler make the call

nikomatsakis commented 7 years ago

I'm not sure -- precisely what conditions would trigger the warning? I agree there is a subtle footgun at play here, if you don't understand the rules.

matklad commented 7 years ago

I'm not sure -- precisely what conditions would trigger the warning?

I think "calling a method exploiting interior mutability on const" is the right condition, but I don't think we can really check it because we don't know which methods involve interior mutability.

nikomatsakis commented 7 years ago

Seems like it would have to "calling any method on const if the type of that const involves UnsafeCell", roughly speaking. Right?

matklad commented 7 years ago

Seems like it would have to "calling any method on const if the type of that const involves UnsafeCell", roughly speaking. Right?

Yep. Perhaps this won't add false positives in practice?

I wonder if we need to warn about creating constants with interior mutability. This is the root of the problem. Currently we need such constants for ATOMIC_X_INIT, but it is only because there are no constant functions in Rust yet.

Diggsey commented 7 years ago

I'm not sure that's quite right:

Seems to me like this behaviour occurs whenever an internally mutable rvalue is borrowed. However, it's only surprising when that rvalue comes from a constant, because constants don't look like rvalues, and because they can be used multiple times, whereas most rvalues can only be used once.

Putting that together, it looks like the compiler should issue a warning whenever a constant containing an UnsafeCell is borrowed.

burdges commented 6 years ago

Another autotrait would be required for this, no? All atomics have this problem, but maybe not all usages of UnsafeCell? Also variance matters, like a &AtomicBool or &Arc<T> sounds okay.

Also, there are usages for const fn with smart pointer, like Mutex/Arc::new() should become const fn so that statics containing Arcs can be initialized at compile time, meaning you'll transiently have a const with an Atomic and/or UnsafeCell during compilation.

pedrohjordao commented 6 years ago

Just got hit by this unexpected behavior as well and thought I was going crazy. Reading the explanations made everything make sense, but some warning would be ideal.

dhardy commented 6 years ago

@burdges has a point. Items like the following should be illegal, not merely illegal to try mutating.

const X: Cell<u32> = Cell::new(0);
eddyb commented 6 years ago

@dhardy Why so? That's not a static, there's no Cell<u32> place in memory, it's just a constant value, a "template" for creating the same value.

dhardy commented 6 years ago

But are there any legitimate uses for this? Possibly as part of a compound type I guess, but that would be unusual. A lint may be better then.

Okay, the problematic bit is that one can call X.set(5); even though consts do not permit mutation.

eddyb commented 6 years ago

@dhardy Yeah. IMO, this is in the same category as this:

struct Foo<T>(T);
const X: Foo<i32> = Foo(0);
fn main() {
    X.0 += 1;
}

Clippy should be linting both this and your example, saying that you're mutating a (field of a) temporary and you probably wanted to do something else. Although it's maybe harder for Cell::set (assuming we'd rather not hardcode it in clippy).

dhardy commented 6 years ago

Why rely on Clippy here? As I understand it, Clippy is primarily about style and succinctness, not correctness. If someone is assigning to a temporary field that is very likely incorrect code.

ryanwarsaw commented 4 years ago

Hi, I'm a beginner learning Rust and I ran into this issue as well. I see this hasn't had much movement in the last year or so, I would love to contribute towards this I'm just not sure where I need to start. Thanks in advance.

Here is the snippet I was using:

const ARRAY: [i32; 3] = [0; 3];
    ARRAY[1] = 2;
    for x in &ARRAY {
        print!("{} ", x);
    }
    // output: 0 0 0 % 

Interestingly enough if I use let it will throw an error:

error[E0594]: cannot assign to ARRAY[_], as ARRAY is not declared as mutable

matklad commented 3 years ago

OnceCell / std::lazy is also to this: https://github.com/matklad/once_cell/issues/145, https://github.com/rust-lang/rust/issues/82842

kupiakos commented 2 years ago

Pinging this thread to see if there's any progress or thought and how this might be properly implemented.

const also doesn't check whether an item is Sync so if you're new to the language, and your goal is to get Rust to compile your global variable, you might try the following, which compiles but produces unexpected results:

use core::cell::Cell;
pub const TEST_CELL: Cell<u32> = Cell::new(10);

pub fn test(x: &Cell<u32>) -> u32 {
    x.set(x.get() + 1);
    x.get()
}

pub fn main() {
    // 11 is printed twice
    println!("got: {}", test(&TEST_CELL));
    println!("got: {}", test(&TEST_CELL));
}

Given the only usage of consts with interior mutability in the stdlib are ATOMIC_X_INIT, which are deprecated, I'd say it's fair to emit a warning for any const that contains interior mutability at construction site, something like this:

warning: constant `SOME_FOO` contains interior mutability which cannot be observed
 --> src/lib.rs:2:11
  |
2 | pub const SOME_FOO: Cell<u32> = Cell::new(10);
  |     ^^^^^ help: use a `static` or `static mut` instead
  |
  = note: `#[warn(interior_mutable_const)]` on by default
PatchMixolydic commented 2 years ago

Clippy has two lints for this situation: clippy::declare_interior_mutable_const and clippy::borrow_interior_mutable_const. Since this seems to be a common stumbling block and there don't seem to be many reasons for placing an interior mutable value in a const, I believe this lint should probably be lifted into rustc.

mitsuhiko commented 2 years ago

Now that Mutex has a const ctor this is more likely to trip up people. It has come up more than once in the discussions of the announcement post. If this lint is lifted it would probably be nice if types gain an attribute similar to #[must_use] on functions so that user code can also annotate this. An alternative would be not to warn on the declaration but when someone tries to do something like acquire (thus adding the annotation to the methods instead).

jplatte commented 2 years ago

Yeah, an opt-in or opt-out would be nice. The clippy lint is pretty useful, but sometimes it's also unhelpful, for example when storing the result of http::header::HeaderName::from_static in a const such that the compiler guarantees its validity.

bbqsrc commented 1 year ago

This too has hit me now.

vultix commented 1 year ago

I accidentally ran into this when using a OnceCell, accidentally reinitializing my type each call due to const instead of static. This is certainly an easy footgun to run into

quaternic commented 1 year ago

I've previously hit and reported a false positive (https://github.com/rust-lang/rust-clippy/issues/7665) with the clippy lint clippy::declare_interior_mutable_const.

In short, when [Cell::new(true); 7] fails as the type is not Copy, rustc correctly suggests this fix:

const TRUE_CELL: Cell<bool> = Cell::new(true);
let _: [Cell<bool>; 7] = [TRUE_CELL; 7];

However, this code triggers the clippy lint, and even gives the incorrect suggestion to change the const to a static.

I did just learn that since 1.63 we've had this cleaner alternative:

let array: [Cell<bool>; 7] = std::array::from_fn(|_| Cell::new(true));

Either way, the relevant question I was wondering about in that issue:

The example in the documentation also triggers borrow_interior_mutable_const, so it's not clear why this lint is needed in addition. In fact, it seems to me that any attempt to mutate the const requires a shared reference and triggers borrow_interior_mutable_const. If there is no such attempt, the interior mutability is inconsequential.

Are there cases where an interior mutable const is never used by reference (e.g. by calling Once::call_once), but the lint would still be useful?