]> git.lizzy.rs Git - rust.git/blob - src/test/ui/lint/lint-const-item-mutation.rs
Auto merge of #106349 - LeSeulArtichaut:dyn-star-tracking-issue, r=jackh726
[rust.git] / src / test / ui / lint / lint-const-item-mutation.rs
1 // check-pass
2
3 struct MyStruct {
4     field: bool,
5     inner_array: [char; 1],
6     raw_ptr: *mut u8
7 }
8 impl MyStruct {
9     fn use_mut(&mut self) {}
10 }
11
12 struct Mutable {
13     msg: &'static str,
14 }
15 impl Drop for Mutable {
16     fn drop(&mut self) {
17         println!("{}", self.msg);
18     }
19 }
20
21 struct Mutable2 { // this one has drop glue but not a Drop impl
22     msg: &'static str,
23     other: String,
24 }
25
26 const ARRAY: [u8; 1] = [25];
27 const MY_STRUCT: MyStruct = MyStruct { field: true, inner_array: ['a'], raw_ptr: 2 as *mut u8 };
28 const RAW_PTR: *mut u8 = 1 as *mut u8;
29 const MUTABLE: Mutable = Mutable { msg: "" };
30 const MUTABLE2: Mutable2 = Mutable2 { msg: "", other: String::new() };
31 const VEC: Vec<i32> = Vec::new();
32 const PTR: *mut () = 1 as *mut _;
33 const PTR_TO_ARRAY: *mut [u32; 4] = 0x12345678 as _;
34 const ARRAY_OF_PTR: [*mut u32; 1] = [1 as *mut _];
35
36 fn main() {
37     ARRAY[0] = 5; //~ WARN attempting to modify
38     MY_STRUCT.field = false; //~ WARN attempting to modify
39     MY_STRUCT.inner_array[0] = 'b'; //~ WARN attempting to modify
40     MY_STRUCT.use_mut(); //~ WARN taking
41     &mut MY_STRUCT; //~ WARN taking
42     (&mut MY_STRUCT).use_mut(); //~ WARN taking
43
44     // Test that we don't warn when writing through
45     // a raw pointer
46     // This is U.B., but this test is check-pass,
47     // so this never actually executes
48     unsafe {
49         *RAW_PTR = 0;
50         *MY_STRUCT.raw_ptr = 0;
51     }
52
53     MUTABLE.msg = "wow"; // no warning, because Drop observes the mutation
54     MUTABLE2.msg = "wow"; //~ WARN attempting to modify
55     VEC.push(0); //~ WARN taking a mutable reference to a `const` item
56
57     // Test that we don't warn when converting a raw pointer
58     // into a mutable reference
59     unsafe { &mut *PTR };
60
61     // Test that we don't warn when there's a dereference involved.
62     // If we ever 'leave' the const via a deference, we're going
63     // to end up modifying something other than the temporary
64     unsafe { (*PTR_TO_ARRAY)[0] = 1 };
65     unsafe { *ARRAY_OF_PTR[0] = 25; }
66 }