Skip to content

Commit a71e49c

Browse files
authored
Rollup merge of rust-lang#120181 - dtolnay:tlconst, r=thomcc
Allow any `const` expression blocks in `thread_local!` This PR contains a rebase of the macro change from rust-lang#116392, together with adding a test under library/std/tests. Testing this feature by making the documentation's example code needlessly more complicated was not appropriate as pointed out in rust-lang#116392 (review). Without the macro change, this new test would fail to build as follows: ```console error: no rules expected the token `let` --> library/std/tests/thread.rs:26:13 | 26 | let value = 1; | ^^^ no rules expected this token in macro call | note: while trying to match meta-variable `$init:expr` --> library/std/src/thread/local.rs:189:69 | 189 | ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }; $($rest:tt)*) => ( | ^^^^^^^^^^ ``` Closes rust-lang#116392.
2 parents dc4234d + c43344e commit a71e49c

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

library/std/src/thread/local.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -186,12 +186,12 @@ macro_rules! thread_local {
186186
// empty (base case for the recursion)
187187
() => {};
188188

189-
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }; $($rest:tt)*) => (
189+
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const $init:block; $($rest:tt)*) => (
190190
$crate::thread::local_impl::thread_local_inner!($(#[$attr])* $vis $name, $t, const $init);
191191
$crate::thread_local!($($rest)*);
192192
);
193193

194-
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }) => (
194+
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const $init:block) => (
195195
$crate::thread::local_impl::thread_local_inner!($(#[$attr])* $vis $name, $t, const $init);
196196
);
197197

library/std/tests/thread.rs

+22
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::cell::{Cell, RefCell};
12
use std::sync::{Arc, Mutex};
23
use std::thread;
34
use std::time::Duration;
@@ -14,3 +15,24 @@ fn sleep() {
1415
thread::sleep(Duration::from_millis(100));
1516
assert_eq!(*finished.lock().unwrap(), false);
1617
}
18+
19+
#[test]
20+
fn thread_local_containing_const_statements() {
21+
// This exercises the `const $init:block` cases of the thread_local macro.
22+
// Despite overlapping with expression syntax, the `const { ... }` is not
23+
// parsed as `$init:expr`.
24+
thread_local! {
25+
static CELL: Cell<u32> = const {
26+
let value = 1;
27+
Cell::new(value)
28+
};
29+
30+
static REFCELL: RefCell<u32> = const {
31+
let value = 1;
32+
RefCell::new(value)
33+
};
34+
}
35+
36+
assert_eq!(CELL.get(), 1);
37+
assert_eq!(REFCELL.take(), 1);
38+
}

0 commit comments

Comments
 (0)