Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow any const expression blocks in thread_local! #120181

Merged
merged 3 commits into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions library/std/src/thread/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,12 +186,12 @@ macro_rules! thread_local {
// empty (base case for the recursion)
() => {};

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

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

Expand Down
22 changes: 22 additions & 0 deletions library/std/tests/thread.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::cell::{Cell, RefCell};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
Expand All @@ -14,3 +15,24 @@ fn sleep() {
thread::sleep(Duration::from_millis(100));
assert_eq!(*finished.lock().unwrap(), false);
}

#[test]
fn thread_local_containing_const_statements() {
// This exercises the `const $init:block` cases of the thread_local macro.
// Despite overlapping with expression syntax, the `const { ... }` is not
// parsed as `$init:expr`.
thread_local! {
static CELL: Cell<u32> = const {
let value = 1;
Cell::new(value)
};

static REFCELL: RefCell<u32> = const {
let value = 1;
RefCell::new(value)
};
}

assert_eq!(CELL.get(), 1);
assert_eq!(REFCELL.take(), 1);
}