Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 97add31

Browse files
authoredFeb 3, 2025
Unrolled build for rust-lang#136445
Rollup merge of rust-lang#136445 - bjorn3:diag_ctxt_cleanup, r=oli-obk Couple of cleanups to DiagCtxt and EarlyDiagCtxt
2 parents 4a43094 + 6a566ee commit 97add31

File tree

13 files changed

+63
-111
lines changed

13 files changed

+63
-111
lines changed
 

‎compiler/rustc_driver_impl/src/args.rs

+9-10
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
use std::{env, error, fmt, fs, io};
22

33
use rustc_session::EarlyDiagCtxt;
4-
use rustc_span::ErrorGuaranteed;
54

65
/// Expands argfiles in command line arguments.
76
#[derive(Default)]
@@ -118,22 +117,22 @@ pub fn arg_expand_all(early_dcx: &EarlyDiagCtxt, at_args: &[String]) -> Vec<Stri
118117
///
119118
/// This function is identical to [`env::args()`] except that it emits an error when it encounters
120119
/// non-Unicode arguments instead of panicking.
121-
pub fn raw_args(early_dcx: &EarlyDiagCtxt) -> Result<Vec<String>, ErrorGuaranteed> {
122-
let mut res = Ok(Vec::new());
120+
pub fn raw_args(early_dcx: &EarlyDiagCtxt) -> Vec<String> {
121+
let mut args = Vec::new();
122+
let mut guar = Ok(());
123123
for (i, arg) in env::args_os().enumerate() {
124124
match arg.into_string() {
125-
Ok(arg) => {
126-
if let Ok(args) = &mut res {
127-
args.push(arg);
128-
}
129-
}
125+
Ok(arg) => args.push(arg),
130126
Err(arg) => {
131-
res =
127+
guar =
132128
Err(early_dcx.early_err(format!("argument {i} is not valid Unicode: {arg:?}")))
133129
}
134130
}
135131
}
136-
res
132+
if let Err(guar) = guar {
133+
guar.raise_fatal();
134+
}
135+
args
137136
}
138137

139138
#[derive(Debug)]

‎compiler/rustc_driver_impl/src/lib.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -1212,9 +1212,9 @@ pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, FatalError> {
12121212

12131213
/// Variant of `catch_fatal_errors` for the `interface::Result` return type
12141214
/// that also computes the exit code.
1215-
pub fn catch_with_exit_code(f: impl FnOnce() -> interface::Result<()>) -> i32 {
1215+
pub fn catch_with_exit_code(f: impl FnOnce()) -> i32 {
12161216
match catch_fatal_errors(f) {
1217-
Ok(Ok(())) => EXIT_SUCCESS,
1217+
Ok(()) => EXIT_SUCCESS,
12181218
_ => EXIT_FAILURE,
12191219
}
12201220
}
@@ -1499,10 +1499,8 @@ pub fn main() -> ! {
14991499
install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
15001500
install_ctrlc_handler();
15011501

1502-
let exit_code = catch_with_exit_code(|| {
1503-
run_compiler(&args::raw_args(&early_dcx)?, &mut callbacks);
1504-
Ok(())
1505-
});
1502+
let exit_code =
1503+
catch_with_exit_code(|| run_compiler(&args::raw_args(&early_dcx), &mut callbacks));
15061504

15071505
if let Some(format) = callbacks.time_passes {
15081506
let end_rss = get_resident_set_size();

‎compiler/rustc_errors/src/emitter.rs

+7-10
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ use crate::snippet::{
3535
use crate::styled_buffer::StyledBuffer;
3636
use crate::translation::{Translate, to_fluent_args};
3737
use crate::{
38-
CodeSuggestion, DiagCtxt, DiagInner, DiagMessage, ErrCode, FluentBundle, LazyFallbackBundle,
39-
Level, MultiSpan, Subdiag, SubstitutionHighlight, SuggestionStyle, TerminalUrl,
38+
CodeSuggestion, DiagInner, DiagMessage, ErrCode, FluentBundle, LazyFallbackBundle, Level,
39+
MultiSpan, Subdiag, SubstitutionHighlight, SuggestionStyle, TerminalUrl,
4040
};
4141

4242
/// Default column width, used in tests and when terminal dimensions cannot be determined.
@@ -537,11 +537,10 @@ impl Emitter for HumanEmitter {
537537
}
538538

539539
/// An emitter that does nothing when emitting a non-fatal diagnostic.
540-
/// Fatal diagnostics are forwarded to `fatal_dcx` to avoid silent
540+
/// Fatal diagnostics are forwarded to `fatal_emitter` to avoid silent
541541
/// failures of rustc, as witnessed e.g. in issue #89358.
542542
pub struct SilentEmitter {
543-
pub fallback_bundle: LazyFallbackBundle,
544-
pub fatal_dcx: DiagCtxt,
543+
pub fatal_emitter: Box<dyn Emitter + DynSend>,
545544
pub fatal_note: Option<String>,
546545
pub emit_fatal_diagnostic: bool,
547546
}
@@ -552,9 +551,7 @@ impl Translate for SilentEmitter {
552551
}
553552

554553
fn fallback_fluent_bundle(&self) -> &FluentBundle {
555-
// Ideally this field wouldn't be necessary and the fallback bundle in `fatal_dcx` would be
556-
// used but the lock prevents this.
557-
&self.fallback_bundle
554+
self.fatal_emitter.fallback_fluent_bundle()
558555
}
559556
}
560557

@@ -563,12 +560,12 @@ impl Emitter for SilentEmitter {
563560
None
564561
}
565562

566-
fn emit_diagnostic(&mut self, mut diag: DiagInner, _registry: &Registry) {
563+
fn emit_diagnostic(&mut self, mut diag: DiagInner, registry: &Registry) {
567564
if self.emit_fatal_diagnostic && diag.level == Level::Fatal {
568565
if let Some(fatal_note) = &self.fatal_note {
569566
diag.sub(Level::Note, fatal_note.clone(), MultiSpan::new());
570567
}
571-
self.fatal_dcx.handle().emit_diagnostic(diag);
568+
self.fatal_emitter.emit_diagnostic(diag, registry);
572569
}
573570
}
574571
}

‎compiler/rustc_errors/src/lib.rs

+20-33
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ use emitter::{DynEmitter, Emitter, is_case_difference, is_different};
5959
use rustc_data_structures::AtomicRef;
6060
use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
6161
use rustc_data_structures::stable_hasher::{Hash128, StableHasher};
62-
use rustc_data_structures::sync::Lock;
62+
use rustc_data_structures::sync::{DynSend, Lock};
6363
pub use rustc_error_messages::{
6464
DiagMessage, FluentBundle, LanguageIdentifier, LazyFallbackBundle, MultiSpan, SpanLabel,
6565
SubdiagMessage, fallback_fluent_bundle, fluent_bundle,
@@ -676,57 +676,44 @@ impl DiagCtxt {
676676
Self { inner: Lock::new(DiagCtxtInner::new(emitter)) }
677677
}
678678

679-
pub fn make_silent(
680-
&self,
681-
fallback_bundle: LazyFallbackBundle,
682-
fatal_note: Option<String>,
683-
emit_fatal_diagnostic: bool,
684-
) {
685-
self.wrap_emitter(|old_dcx| {
686-
Box::new(emitter::SilentEmitter {
687-
fallback_bundle,
688-
fatal_dcx: DiagCtxt { inner: Lock::new(old_dcx) },
689-
fatal_note,
690-
emit_fatal_diagnostic,
691-
})
692-
});
693-
}
694-
695-
fn wrap_emitter<F>(&self, f: F)
696-
where
697-
F: FnOnce(DiagCtxtInner) -> Box<DynEmitter>,
698-
{
699-
// A empty type that implements `Emitter` so that a `DiagCtxtInner` can be constructed
700-
// to temporarily swap in place of the real one, which will be used in constructing
701-
// its replacement.
679+
pub fn make_silent(&self, fatal_note: Option<String>, emit_fatal_diagnostic: bool) {
680+
// An empty type that implements `Emitter` to temporarily swap in place of the real one,
681+
// which will be used in constructing its replacement.
702682
struct FalseEmitter;
703683

704684
impl Emitter for FalseEmitter {
705685
fn emit_diagnostic(&mut self, _: DiagInner, _: &Registry) {
706-
unimplemented!("false emitter must only used during `wrap_emitter`")
686+
unimplemented!("false emitter must only used during `make_silent`")
707687
}
708688

709689
fn source_map(&self) -> Option<&SourceMap> {
710-
unimplemented!("false emitter must only used during `wrap_emitter`")
690+
unimplemented!("false emitter must only used during `make_silent`")
711691
}
712692
}
713693

714694
impl translation::Translate for FalseEmitter {
715695
fn fluent_bundle(&self) -> Option<&FluentBundle> {
716-
unimplemented!("false emitter must only used during `wrap_emitter`")
696+
unimplemented!("false emitter must only used during `make_silent`")
717697
}
718698

719699
fn fallback_fluent_bundle(&self) -> &FluentBundle {
720-
unimplemented!("false emitter must only used during `wrap_emitter`")
700+
unimplemented!("false emitter must only used during `make_silent`")
721701
}
722702
}
723703

724704
let mut inner = self.inner.borrow_mut();
725-
let mut prev_dcx = DiagCtxtInner::new(Box::new(FalseEmitter));
726-
std::mem::swap(&mut *inner, &mut prev_dcx);
727-
let new_emitter = f(prev_dcx);
728-
let mut new_dcx = DiagCtxtInner::new(new_emitter);
729-
std::mem::swap(&mut *inner, &mut new_dcx);
705+
let mut prev_emitter = Box::new(FalseEmitter) as Box<dyn Emitter + DynSend>;
706+
std::mem::swap(&mut inner.emitter, &mut prev_emitter);
707+
let new_emitter = Box::new(emitter::SilentEmitter {
708+
fatal_emitter: prev_emitter,
709+
fatal_note,
710+
emit_fatal_diagnostic,
711+
});
712+
inner.emitter = new_emitter;
713+
}
714+
715+
pub fn set_emitter(&self, emitter: Box<dyn Emitter + DynSend>) {
716+
self.inner.borrow_mut().emitter = emitter;
730717
}
731718

732719
/// Translate `message` eagerly with `args` to `SubdiagMessage::Eager`.

‎compiler/rustc_session/src/config.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -1819,7 +1819,7 @@ pub fn parse_error_format(
18191819
ErrorOutputType::HumanReadable(HumanReadableErrorType::Unicode, color)
18201820
}
18211821
Some(arg) => {
1822-
early_dcx.abort_if_error_and_set_error_format(ErrorOutputType::HumanReadable(
1822+
early_dcx.set_error_format(ErrorOutputType::HumanReadable(
18231823
HumanReadableErrorType::Default,
18241824
color,
18251825
));
@@ -2360,7 +2360,7 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
23602360

23612361
let error_format = parse_error_format(early_dcx, matches, color, json_color, json_rendered);
23622362

2363-
early_dcx.abort_if_error_and_set_error_format(error_format);
2363+
early_dcx.set_error_format(error_format);
23642364

23652365
let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_else(|_| {
23662366
early_dcx.early_fatal("`--diagnostic-width` must be an positive integer");
@@ -2770,6 +2770,7 @@ pub mod nightly_options {
27702770
"the option `{}` is only accepted on the nightly compiler",
27712771
opt.name
27722772
);
2773+
// The non-zero nightly_options_on_stable will force an early_fatal eventually.
27732774
let _ = early_dcx.early_err(msg);
27742775
}
27752776
OptionStability::Stable => {}

‎compiler/rustc_session/src/parse.rs

+3-11
Original file line numberDiff line numberDiff line change
@@ -277,14 +277,10 @@ impl ParseSess {
277277
) -> Self {
278278
let fallback_bundle = fallback_fluent_bundle(locale_resources, false);
279279
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
280-
let emitter = Box::new(HumanEmitter::new(
281-
stderr_destination(ColorConfig::Auto),
282-
Lrc::clone(&fallback_bundle),
283-
));
284-
let fatal_dcx = DiagCtxt::new(emitter);
280+
let fatal_emitter =
281+
Box::new(HumanEmitter::new(stderr_destination(ColorConfig::Auto), fallback_bundle));
285282
let dcx = DiagCtxt::new(Box::new(SilentEmitter {
286-
fallback_bundle,
287-
fatal_dcx,
283+
fatal_emitter,
288284
fatal_note: Some(fatal_note),
289285
emit_fatal_diagnostic,
290286
}))
@@ -341,8 +337,4 @@ impl ParseSess {
341337
pub fn dcx(&self) -> DiagCtxtHandle<'_> {
342338
self.dcx.handle()
343339
}
344-
345-
pub fn set_dcx(&mut self, dcx: DiagCtxt) {
346-
self.dcx = dcx;
347-
}
348340
}

‎compiler/rustc_session/src/session.rs

+4-11
Original file line numberDiff line numberDiff line change
@@ -1362,23 +1362,16 @@ pub struct EarlyDiagCtxt {
13621362
dcx: DiagCtxt,
13631363
}
13641364

1365-
impl Default for EarlyDiagCtxt {
1366-
fn default() -> Self {
1367-
Self::new(ErrorOutputType::default())
1368-
}
1369-
}
1370-
13711365
impl EarlyDiagCtxt {
13721366
pub fn new(output: ErrorOutputType) -> Self {
13731367
let emitter = mk_emitter(output);
13741368
Self { dcx: DiagCtxt::new(emitter) }
13751369
}
13761370

13771371
/// Swap out the underlying dcx once we acquire the user's preference on error emission
1378-
/// format. Any errors prior to that will cause an abort and all stashed diagnostics of the
1379-
/// previous dcx will be emitted.
1380-
pub fn abort_if_error_and_set_error_format(&mut self, output: ErrorOutputType) {
1381-
self.dcx.handle().abort_if_errors();
1372+
/// format. If `early_err` was previously called this will panic.
1373+
pub fn set_error_format(&mut self, output: ErrorOutputType) {
1374+
assert!(self.dcx.handle().has_errors().is_none());
13821375

13831376
let emitter = mk_emitter(output);
13841377
self.dcx = DiagCtxt::new(emitter);
@@ -1398,7 +1391,7 @@ impl EarlyDiagCtxt {
13981391

13991392
#[allow(rustc::untranslatable_diagnostic)]
14001393
#[allow(rustc::diagnostic_outside_of_impl)]
1401-
#[must_use = "ErrorGuaranteed must be returned from `run_compiler` in order to exit with a non-zero status code"]
1394+
#[must_use = "raise_fatal must be called on the returned ErrorGuaranteed in order to exit with a non-zero status code"]
14021395
pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
14031396
self.dcx.handle().err(msg)
14041397
}

‎src/doc/rustc-dev-guide/examples/rustc-interface-getting-diagnostics.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,15 @@ extern crate rustc_interface;
1010
extern crate rustc_session;
1111
extern crate rustc_span;
1212

13+
use std::sync::{Arc, Mutex};
14+
1315
use rustc_errors::emitter::Emitter;
1416
use rustc_errors::registry::{self, Registry};
1517
use rustc_errors::translation::Translate;
1618
use rustc_errors::{DiagCtxt, DiagInner, FluentBundle};
1719
use rustc_session::config;
1820
use rustc_span::source_map::SourceMap;
1921

20-
use std::sync::{Arc, Mutex};
21-
2222
struct DebugEmitter {
2323
source_map: Arc<SourceMap>,
2424
diagnostics: Arc<Mutex<Vec<DiagInner>>>,
@@ -67,10 +67,10 @@ fn main() {
6767
locale_resources: rustc_driver::DEFAULT_LOCALE_RESOURCES.to_owned(),
6868
lint_caps: rustc_hash::FxHashMap::default(),
6969
psess_created: Some(Box::new(|parse_sess| {
70-
parse_sess.set_dcx(DiagCtxt::new(Box::new(DebugEmitter {
70+
parse_sess.dcx().set_emitter(Box::new(DebugEmitter {
7171
source_map: parse_sess.clone_source_map(),
7272
diagnostics,
73-
})));
73+
}));
7474
})),
7575
register_lints: None,
7676
override_queries: None,

‎src/librustdoc/lib.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -177,9 +177,8 @@ pub fn main() {
177177
rustc_driver::init_logger(&early_dcx, rustc_log::LoggerConfig::from_env("RUSTDOC_LOG"));
178178

179179
let exit_code = rustc_driver::catch_with_exit_code(|| {
180-
let at_args = rustc_driver::args::raw_args(&early_dcx)?;
180+
let at_args = rustc_driver::args::raw_args(&early_dcx);
181181
main_args(&mut early_dcx, &at_args);
182-
Ok(())
183182
});
184183
process::exit(exit_code);
185184
}

‎src/tools/clippy/src/driver.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ pub fn main() {
197197
});
198198

199199
exit(rustc_driver::catch_with_exit_code(move || {
200-
let mut orig_args = rustc_driver::args::raw_args(&early_dcx)?;
200+
let mut orig_args = rustc_driver::args::raw_args(&early_dcx);
201201

202202
let has_sysroot_arg = |args: &mut [String]| -> bool {
203203
if has_arg(args, "--sysroot") {
@@ -239,7 +239,7 @@ pub fn main() {
239239
pass_sysroot_env_if_given(&mut args, sys_root_env);
240240

241241
rustc_driver::run_compiler(&args, &mut DefaultCallbacks);
242-
return Ok(());
242+
return;
243243
}
244244

245245
if orig_args.iter().any(|a| a == "--version" || a == "-V") {
@@ -301,7 +301,6 @@ pub fn main() {
301301
} else {
302302
rustc_driver::run_compiler(&args, &mut RustcCallbacks { clippy_args_var });
303303
}
304-
Ok(())
305304
}))
306305
}
307306

‎src/tools/miri/src/bin/miri.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -379,10 +379,8 @@ fn run_compiler_and_exit(
379379
callbacks: &mut (dyn rustc_driver::Callbacks + Send),
380380
) -> ! {
381381
// Invoke compiler, and handle return code.
382-
let exit_code = rustc_driver::catch_with_exit_code(move || {
383-
rustc_driver::run_compiler(args, callbacks);
384-
Ok(())
385-
});
382+
let exit_code =
383+
rustc_driver::catch_with_exit_code(move || rustc_driver::run_compiler(args, callbacks));
386384
std::process::exit(exit_code)
387385
}
388386

@@ -461,7 +459,7 @@ fn main() {
461459
// (`install_ice_hook` might change `RUST_BACKTRACE`.)
462460
let env_snapshot = env::vars_os().collect::<Vec<_>>();
463461

464-
let args = rustc_driver::args::raw_args(&early_dcx)
462+
let args = rustc_driver::catch_fatal_errors(|| rustc_driver::args::raw_args(&early_dcx))
465463
.unwrap_or_else(|_| std::process::exit(rustc_driver::EXIT_FAILURE));
466464

467465
// Install the ctrlc handler that sets `rustc_const_eval::CTRL_C_RECEIVED`, even if
There was a problem loading the remainder of the diff.

0 commit comments

Comments
 (0)
Failed to load comments.