Skip to content

Commit 9709a43

Browse files
committed
Auto merge of #106228 - matthiaskrgr:rollup-jsznhww, r=matthiaskrgr
Rollup of 8 pull requests Successful merges: - #104402 (Move `ReentrantMutex` to `std::sync`) - #104493 (available_parallelism: Gracefully handle zero value cfs_period_us) - #105359 (Make sentinel value configurable in `library/std/src/sys_common/thread_local_key.rs`) - #105497 (Clarify `catch_unwind` docs about panic hooks) - #105570 (Properly calculate best failure in macro matching) - #105702 (Format only modified files) - #105998 (adjust message on non-unwinding panic) - #106161 (Iterator::find: link to Iterator::position in docs for discoverability) Failed merges: r? `@ghost` `@rustbot` modify labels: rollup
2 parents 270c94e + 89ccd70 commit 9709a43

File tree

19 files changed

+213
-31
lines changed

19 files changed

+213
-31
lines changed

compiler/rustc_expand/src/mbe/diagnostics.rs

+30-10
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ pub(super) fn failed_to_match_macro<'cx>(
4343
return result;
4444
}
4545

46-
let Some((token, label, remaining_matcher)) = tracker.best_failure else {
46+
let Some(BestFailure { token, msg: label, remaining_matcher, .. }) = tracker.best_failure else {
4747
return DummyResult::any(sp);
4848
};
4949

@@ -95,11 +95,24 @@ struct CollectTrackerAndEmitter<'a, 'cx, 'matcher> {
9595
cx: &'a mut ExtCtxt<'cx>,
9696
remaining_matcher: Option<&'matcher MatcherLoc>,
9797
/// Which arm's failure should we report? (the one furthest along)
98-
best_failure: Option<(Token, &'static str, MatcherLoc)>,
98+
best_failure: Option<BestFailure>,
9999
root_span: Span,
100100
result: Option<Box<dyn MacResult + 'cx>>,
101101
}
102102

103+
struct BestFailure {
104+
token: Token,
105+
position_in_tokenstream: usize,
106+
msg: &'static str,
107+
remaining_matcher: MatcherLoc,
108+
}
109+
110+
impl BestFailure {
111+
fn is_better_position(&self, position: usize) -> bool {
112+
position > self.position_in_tokenstream
113+
}
114+
}
115+
103116
impl<'a, 'cx, 'matcher> Tracker<'matcher> for CollectTrackerAndEmitter<'a, 'cx, 'matcher> {
104117
fn before_match_loc(&mut self, parser: &TtParser, matcher: &'matcher MatcherLoc) {
105118
if self.remaining_matcher.is_none()
@@ -119,18 +132,25 @@ impl<'a, 'cx, 'matcher> Tracker<'matcher> for CollectTrackerAndEmitter<'a, 'cx,
119132
"should not collect detailed info for successful macro match",
120133
);
121134
}
122-
Failure(token, msg) => match self.best_failure {
123-
Some((ref best_token, _, _)) if best_token.span.lo() >= token.span.lo() => {}
124-
_ => {
125-
self.best_failure = Some((
126-
token.clone(),
135+
Failure(token, approx_position, msg) => {
136+
debug!(?token, ?msg, "a new failure of an arm");
137+
138+
if self
139+
.best_failure
140+
.as_ref()
141+
.map_or(true, |failure| failure.is_better_position(*approx_position))
142+
{
143+
self.best_failure = Some(BestFailure {
144+
token: token.clone(),
145+
position_in_tokenstream: *approx_position,
127146
msg,
128-
self.remaining_matcher
147+
remaining_matcher: self
148+
.remaining_matcher
129149
.expect("must have collected matcher already")
130150
.clone(),
131-
))
151+
})
132152
}
133-
},
153+
}
134154
Error(err_sp, msg) => {
135155
let span = err_sp.substitute_dummy(self.root_span);
136156
self.cx.struct_span_err(span, msg).emit();

compiler/rustc_expand/src/mbe/macro_parser.rs

+11-2
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,8 @@ pub(crate) enum ParseResult<T> {
310310
Success(T),
311311
/// Arm failed to match. If the second parameter is `token::Eof`, it indicates an unexpected
312312
/// end of macro invocation. Otherwise, it indicates that no rules expected the given token.
313-
Failure(Token, &'static str),
313+
/// The usize is the approximate position of the token in the input token stream.
314+
Failure(Token, usize, &'static str),
314315
/// Fatal error (malformed macro?). Abort compilation.
315316
Error(rustc_span::Span, String),
316317
ErrorReported(ErrorGuaranteed),
@@ -455,6 +456,7 @@ impl TtParser {
455456
&mut self,
456457
matcher: &'matcher [MatcherLoc],
457458
token: &Token,
459+
approx_position: usize,
458460
track: &mut T,
459461
) -> Option<NamedParseResult> {
460462
// Matcher positions that would be valid if the macro invocation was over now. Only
@@ -598,6 +600,7 @@ impl TtParser {
598600
token::Eof,
599601
if token.span.is_dummy() { token.span } else { token.span.shrink_to_hi() },
600602
),
603+
approx_position,
601604
"missing tokens in macro arguments",
602605
),
603606
})
@@ -627,7 +630,12 @@ impl TtParser {
627630

628631
// Process `cur_mps` until either we have finished the input or we need to get some
629632
// parsing from the black-box parser done.
630-
let res = self.parse_tt_inner(matcher, &parser.token, track);
633+
let res = self.parse_tt_inner(
634+
matcher,
635+
&parser.token,
636+
parser.approx_token_stream_pos(),
637+
track,
638+
);
631639
if let Some(res) = res {
632640
return res;
633641
}
@@ -642,6 +650,7 @@ impl TtParser {
642650
// parser: syntax error.
643651
return Failure(
644652
parser.token.clone(),
653+
parser.approx_token_stream_pos(),
645654
"no rules expected this token in macro call",
646655
);
647656
}

compiler/rustc_expand/src/mbe/macro_rules.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -326,8 +326,8 @@ pub(super) fn try_match_macro<'matcher, T: Tracker<'matcher>>(
326326

327327
return Ok((i, named_matches));
328328
}
329-
Failure(_, _) => {
330-
trace!("Failed to match arm, trying the next one");
329+
Failure(_, reached_position, _) => {
330+
trace!(%reached_position, "Failed to match arm, trying the next one");
331331
// Try the next arm.
332332
}
333333
Error(_, _) => {
@@ -432,7 +432,7 @@ pub fn compile_declarative_macro(
432432
let argument_map =
433433
match tt_parser.parse_tt(&mut Cow::Owned(parser), &argument_gram, &mut NoopTracker) {
434434
Success(m) => m,
435-
Failure(token, msg) => {
435+
Failure(token, _, msg) => {
436436
let s = parse_failure_msg(&token);
437437
let sp = token.span.substitute_dummy(def.span);
438438
let mut err = sess.parse_sess.span_diagnostic.struct_span_err(sp, &s);

compiler/rustc_parse/src/parser/mod.rs

+4
Original file line numberDiff line numberDiff line change
@@ -1499,6 +1499,10 @@ impl<'a> Parser<'a> {
14991499
pub fn clear_expected_tokens(&mut self) {
15001500
self.expected_tokens.clear();
15011501
}
1502+
1503+
pub fn approx_token_stream_pos(&self) -> usize {
1504+
self.token_cursor.num_next_calls
1505+
}
15021506
}
15031507

15041508
pub(crate) fn make_unclosed_delims_error(

library/core/src/iter/traits/iterator.rs

+3
Original file line numberDiff line numberDiff line change
@@ -2654,7 +2654,10 @@ pub trait Iterator {
26542654
/// argument is a double reference. You can see this effect in the
26552655
/// examples below, with `&&x`.
26562656
///
2657+
/// If you need the index of the element, see [`position()`].
2658+
///
26572659
/// [`Some(element)`]: Some
2660+
/// [`position()`]: Iterator::position
26582661
///
26592662
/// # Examples
26602663
///

library/std/src/io/stdio.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,8 @@ use crate::fmt;
1010
use crate::fs::File;
1111
use crate::io::{self, BufReader, IoSlice, IoSliceMut, LineWriter, Lines};
1212
use crate::sync::atomic::{AtomicBool, Ordering};
13-
use crate::sync::{Arc, Mutex, MutexGuard, OnceLock};
13+
use crate::sync::{Arc, Mutex, MutexGuard, OnceLock, ReentrantMutex, ReentrantMutexGuard};
1414
use crate::sys::stdio;
15-
use crate::sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
1615

1716
type LocalStream = Arc<Mutex<Vec<u8>>>;
1817

library/std/src/panic.rs

+3
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,9 @@ where
114114
/// aborting the process as well. This function *only* catches unwinding panics,
115115
/// not those that abort the process.
116116
///
117+
/// Note that if a custom panic hook has been set, it will be invoked before
118+
/// the panic is caught, before unwinding.
119+
///
117120
/// Also note that unwinding into Rust code with a foreign exception (e.g.
118121
/// an exception thrown from C++ code) is undefined behavior.
119122
///

library/std/src/panicking.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -699,7 +699,11 @@ fn rust_panic_with_hook(
699699
// have limited options. Currently our preference is to
700700
// just abort. In the future we may consider resuming
701701
// unwinding or otherwise exiting the thread cleanly.
702-
rtprintpanic!("thread panicked while panicking. aborting.\n");
702+
if !can_unwind {
703+
rtprintpanic!("thread caused non-unwinding panic. aborting.\n");
704+
} else {
705+
rtprintpanic!("thread panicked while panicking. aborting.\n");
706+
}
703707
crate::sys::abort_internal();
704708
}
705709

library/std/src/sync/mod.rs

+3
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,8 @@ pub use self::lazy_lock::LazyLock;
177177
#[unstable(feature = "once_cell", issue = "74465")]
178178
pub use self::once_lock::OnceLock;
179179

180+
pub(crate) use self::remutex::{ReentrantMutex, ReentrantMutexGuard};
181+
180182
pub mod mpsc;
181183

182184
mod barrier;
@@ -187,4 +189,5 @@ mod mutex;
187189
mod once;
188190
mod once_lock;
189191
mod poison;
192+
mod remutex;
190193
mod rwlock;
File renamed without changes.

library/std/src/sys_common/remutex/tests.rs library/std/src/sync/remutex/tests.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1+
use super::{ReentrantMutex, ReentrantMutexGuard};
12
use crate::cell::RefCell;
23
use crate::sync::Arc;
3-
use crate::sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
44
use crate::thread;
55

66
#[test]

library/std/src/sys/unix/thread.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -505,7 +505,7 @@ mod cgroups {
505505
let limit = raw_quota.next()?;
506506
let period = raw_quota.next()?;
507507
match (limit.parse::<usize>(), period.parse::<usize>()) {
508-
(Ok(limit), Ok(period)) => {
508+
(Ok(limit), Ok(period)) if period > 0 => {
509509
quota = quota.min(limit / period);
510510
}
511511
_ => {}
@@ -565,7 +565,7 @@ mod cgroups {
565565
let period = parse_file("cpu.cfs_period_us");
566566

567567
match (limit, period) {
568-
(Some(limit), Some(period)) => quota = quota.min(limit / period),
568+
(Some(limit), Some(period)) if period > 0 => quota = quota.min(limit / period),
569569
_ => {}
570570
}
571571

library/std/src/sys_common/mod.rs

-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ pub mod lazy_box;
2727
pub mod memchr;
2828
pub mod once;
2929
pub mod process;
30-
pub mod remutex;
3130
pub mod thread;
3231
pub mod thread_info;
3332
pub mod thread_local_dtor;

library/std/src/sys_common/thread_local_key.rs

+17-8
Original file line numberDiff line numberDiff line change
@@ -117,10 +117,14 @@ pub struct Key {
117117
/// This value specifies no destructor by default.
118118
pub const INIT: StaticKey = StaticKey::new(None);
119119

120+
// Define a sentinel value that is unlikely to be returned
121+
// as a TLS key (but it may be returned).
122+
const KEY_SENTVAL: usize = 0;
123+
120124
impl StaticKey {
121125
#[rustc_const_unstable(feature = "thread_local_internals", issue = "none")]
122126
pub const fn new(dtor: Option<unsafe extern "C" fn(*mut u8)>) -> StaticKey {
123-
StaticKey { key: atomic::AtomicUsize::new(0), dtor }
127+
StaticKey { key: atomic::AtomicUsize::new(KEY_SENTVAL), dtor }
124128
}
125129

126130
/// Gets the value associated with this TLS key
@@ -144,31 +148,36 @@ impl StaticKey {
144148
#[inline]
145149
unsafe fn key(&self) -> imp::Key {
146150
match self.key.load(Ordering::Relaxed) {
147-
0 => self.lazy_init() as imp::Key,
151+
KEY_SENTVAL => self.lazy_init() as imp::Key,
148152
n => n as imp::Key,
149153
}
150154
}
151155

152156
unsafe fn lazy_init(&self) -> usize {
153-
// POSIX allows the key created here to be 0, but the compare_exchange
154-
// below relies on using 0 as a sentinel value to check who won the
157+
// POSIX allows the key created here to be KEY_SENTVAL, but the compare_exchange
158+
// below relies on using KEY_SENTVAL as a sentinel value to check who won the
155159
// race to set the shared TLS key. As far as I know, there is no
156160
// guaranteed value that cannot be returned as a posix_key_create key,
157161
// so there is no value we can initialize the inner key with to
158162
// prove that it has not yet been set. As such, we'll continue using a
159-
// value of 0, but with some gyrations to make sure we have a non-0
163+
// value of KEY_SENTVAL, but with some gyrations to make sure we have a non-KEY_SENTVAL
160164
// value returned from the creation routine.
161165
// FIXME: this is clearly a hack, and should be cleaned up.
162166
let key1 = imp::create(self.dtor);
163-
let key = if key1 != 0 {
167+
let key = if key1 as usize != KEY_SENTVAL {
164168
key1
165169
} else {
166170
let key2 = imp::create(self.dtor);
167171
imp::destroy(key1);
168172
key2
169173
};
170-
rtassert!(key != 0);
171-
match self.key.compare_exchange(0, key as usize, Ordering::SeqCst, Ordering::SeqCst) {
174+
rtassert!(key as usize != KEY_SENTVAL);
175+
match self.key.compare_exchange(
176+
KEY_SENTVAL,
177+
key as usize,
178+
Ordering::SeqCst,
179+
Ordering::SeqCst,
180+
) {
172181
// The CAS succeeded, so we've created the actual key
173182
Ok(_) => key as usize,
174183
// If someone beat us to the punch, use their key instead

src/bootstrap/CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
1515
- Several unsupported `./configure` options have been removed: `optimize`, `parallel-compiler`. These can still be enabled with `--set`, although it isn't recommended.
1616
- `remote-test-server`'s `verbose` argument has been removed in favor of the `--verbose` flag
1717
- `remote-test-server`'s `remote` argument has been removed in favor of the `--bind` flag. Use `--bind 0.0.0.0:12345` to replicate the behavior of the `remote` argument.
18+
- `x.py fmt` now formats only files modified between the merge-base of HEAD and the last commit in the master branch of the rust-lang repository and the current working directory. To restore old behaviour, use `x.py fmt .`. The check mode is not affected by this change. [#105702](https://github.com/rust-lang/rust/pull/105702)
1819

1920
### Non-breaking changes
2021

src/bootstrap/clean.rs

+1
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ fn clean_default(build: &Build, all: bool) {
9494
rm_rf(&build.out.join("tmp"));
9595
rm_rf(&build.out.join("dist"));
9696
rm_rf(&build.out.join("bootstrap"));
97+
rm_rf(&build.out.join("rustfmt.stamp"));
9798

9899
for host in &build.hosts {
99100
let entries = match build.out.join(host.triple).read_dir() {

0 commit comments

Comments
 (0)