Skip to content

Commit 6184099

Browse files
committed
Fewer early errors.
`build_session` is passed an `EarlyErrorHandler` and then constructs a `Handler`. But the `EarlyErrorHandler` is still used for some time after that. This commit changes `build_session` so it consumes the passed `EarlyErrorHandler`, and also drops it as soon as the `Handler` is built. As a result, `parse_cfg` and `parse_check_cfg` now take a `Handler` instead of an `EarlyErrorHandler`.
1 parent 35ac281 commit 6184099

File tree

7 files changed

+60
-38
lines changed

7 files changed

+60
-38
lines changed

compiler/rustc_interface/src/interface.rs

+24-16
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ pub struct Compiler {
4242
}
4343

4444
/// Converts strings provided as `--cfg [cfgspec]` into a `Cfg`.
45-
pub(crate) fn parse_cfg(handler: &EarlyErrorHandler, cfgs: Vec<String>) -> Cfg {
45+
pub(crate) fn parse_cfg(handler: &Handler, cfgs: Vec<String>) -> Cfg {
4646
cfgs.into_iter()
4747
.map(|s| {
4848
let sess = ParseSess::with_silent_emitter(Some(format!(
@@ -52,10 +52,14 @@ pub(crate) fn parse_cfg(handler: &EarlyErrorHandler, cfgs: Vec<String>) -> Cfg {
5252

5353
macro_rules! error {
5454
($reason: expr) => {
55-
handler.early_error(format!(
56-
concat!("invalid `--cfg` argument: `{}` (", $reason, ")"),
57-
s
58-
));
55+
#[allow(rustc::untranslatable_diagnostic)]
56+
#[allow(rustc::diagnostic_outside_of_impl)]
57+
handler
58+
.struct_fatal(format!(
59+
concat!("invalid `--cfg` argument: `{}` (", $reason, ")"),
60+
s
61+
))
62+
.emit();
5963
};
6064
}
6165

@@ -97,7 +101,7 @@ pub(crate) fn parse_cfg(handler: &EarlyErrorHandler, cfgs: Vec<String>) -> Cfg {
97101
}
98102

99103
/// Converts strings provided as `--check-cfg [specs]` into a `CheckCfg`.
100-
pub(crate) fn parse_check_cfg(handler: &EarlyErrorHandler, specs: Vec<String>) -> CheckCfg {
104+
pub(crate) fn parse_check_cfg(handler: &Handler, specs: Vec<String>) -> CheckCfg {
101105
// If any --check-cfg is passed then exhaustive_values and exhaustive_names
102106
// are enabled by default.
103107
let exhaustive_names = !specs.is_empty();
@@ -113,10 +117,14 @@ pub(crate) fn parse_check_cfg(handler: &EarlyErrorHandler, specs: Vec<String>) -
113117

114118
macro_rules! error {
115119
($reason:expr) => {
116-
handler.early_error(format!(
117-
concat!("invalid `--check-cfg` argument: `{}` (", $reason, ")"),
118-
s
119-
))
120+
#[allow(rustc::untranslatable_diagnostic)]
121+
#[allow(rustc::diagnostic_outside_of_impl)]
122+
handler
123+
.struct_fatal(format!(
124+
concat!("invalid `--check-cfg` argument: `{}` (", $reason, ")"),
125+
s
126+
))
127+
.emit()
120128
};
121129
}
122130

@@ -388,13 +396,13 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
388396
|| {
389397
crate::callbacks::setup_callbacks();
390398

391-
let handler = EarlyErrorHandler::new(config.opts.error_format);
399+
let early_handler = EarlyErrorHandler::new(config.opts.error_format);
392400

393401
let codegen_backend = if let Some(make_codegen_backend) = config.make_codegen_backend {
394402
make_codegen_backend(&config.opts)
395403
} else {
396404
util::get_codegen_backend(
397-
&handler,
405+
&early_handler,
398406
&config.opts.maybe_sysroot,
399407
config.opts.unstable_opts.codegen_backend.as_deref(),
400408
)
@@ -411,7 +419,7 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
411419
) {
412420
Ok(bundle) => bundle,
413421
Err(e) => {
414-
handler.early_error(format!("failed to load fluent bundle: {e}"));
422+
early_handler.early_error(format!("failed to load fluent bundle: {e}"));
415423
}
416424
};
417425

@@ -422,7 +430,7 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
422430
let target_override = codegen_backend.target_override(&config.opts);
423431

424432
let mut sess = rustc_session::build_session(
425-
&handler,
433+
early_handler,
426434
config.opts,
427435
CompilerIO {
428436
input: config.input,
@@ -444,12 +452,12 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
444452

445453
codegen_backend.init(&sess);
446454

447-
let cfg = parse_cfg(&handler, config.crate_cfg);
455+
let cfg = parse_cfg(&sess.diagnostic(), config.crate_cfg);
448456
let mut cfg = config::build_configuration(&sess, cfg);
449457
util::add_configuration(&mut cfg, &mut sess, &*codegen_backend);
450458
sess.parse_sess.config = cfg;
451459

452-
let mut check_cfg = parse_check_cfg(&handler, config.crate_check_cfg);
460+
let mut check_cfg = parse_check_cfg(&sess.diagnostic(), config.crate_check_cfg);
453461
check_cfg.fill_well_known(&sess.target);
454462
sess.parse_sess.check_config = check_cfg;
455463

compiler/rustc_interface/src/tests.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,9 @@ use std::path::{Path, PathBuf};
2626
use std::sync::Arc;
2727

2828
fn mk_session(matches: getopts::Matches) -> (Session, Cfg) {
29-
let mut handler = EarlyErrorHandler::new(ErrorOutputType::default());
29+
let mut early_handler = EarlyErrorHandler::new(ErrorOutputType::default());
3030
let registry = registry::Registry::new(&[]);
31-
let sessopts = build_session_options(&mut handler, &matches);
32-
let cfg = parse_cfg(&handler, matches.opt_strs("cfg"));
31+
let sessopts = build_session_options(&mut early_handler, &matches);
3332
let temps_dir = sessopts.unstable_opts.temps_dir.as_deref().map(PathBuf::from);
3433
let io = CompilerIO {
3534
input: Input::Str { name: FileName::Custom(String::new()), input: String::new() },
@@ -38,7 +37,7 @@ fn mk_session(matches: getopts::Matches) -> (Session, Cfg) {
3837
temps_dir,
3938
};
4039
let sess = build_session(
41-
&handler,
40+
early_handler,
4241
sessopts,
4342
io,
4443
None,
@@ -52,6 +51,7 @@ fn mk_session(matches: getopts::Matches) -> (Session, Cfg) {
5251
Arc::default(),
5352
Default::default(),
5453
);
54+
let cfg = parse_cfg(&sess.diagnostic(), matches.opt_strs("cfg"));
5555
(sess, cfg)
5656
}
5757

compiler/rustc_session/messages.ftl

+3
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ session_crate_name_invalid = crate names cannot start with a `-`, but `{$s}` has
1616
1717
session_expr_parentheses_needed = parentheses are required to parse this as an expression
1818
19+
session_failed_to_create_profiler = failed to create profiler: {$err}
20+
1921
session_feature_diagnostic_for_issue =
2022
see issue #{$n} <https://github.com/rust-lang/rust/issues/{$n}> for more information
2123
@@ -73,6 +75,7 @@ session_not_supported = not supported
7375
session_nul_in_c_str = null characters in C string literals are not supported
7476
7577
session_octal_float_literal_not_supported = octal float literal is not supported
78+
7679
session_optimization_fuel_exhausted = optimization-fuel-exhausted: {$msg}
7780
7881
session_profile_sample_use_file_does_not_exist = file `{$path}` passed to `-C profile-sample-use` does not exist.

compiler/rustc_session/src/errors.rs

+6
Original file line numberDiff line numberDiff line change
@@ -444,3 +444,9 @@ pub(crate) struct FunctionReturnRequiresX86OrX8664;
444444
#[derive(Diagnostic)]
445445
#[diag(session_function_return_thunk_extern_requires_non_large_code_model)]
446446
pub(crate) struct FunctionReturnThunkExternRequiresNonLargeCodeModel;
447+
448+
#[derive(Diagnostic)]
449+
#[diag(session_failed_to_create_profiler)]
450+
pub struct FailedToCreateProfiler {
451+
pub err: String,
452+
}

compiler/rustc_session/src/session.rs

+19-18
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ use rustc_errors::registry::Registry;
2424
use rustc_errors::{
2525
error_code, fallback_fluent_bundle, DiagnosticBuilder, DiagnosticId, DiagnosticMessage,
2626
ErrorGuaranteed, FluentBundle, Handler, IntoDiagnostic, LazyFallbackBundle, MultiSpan, Noted,
27-
SubdiagnosticMessage, TerminalUrl,
27+
TerminalUrl,
2828
};
2929
use rustc_macros::HashStable_Generic;
3030
pub use rustc_span::def_id::StableCrateId;
@@ -1349,7 +1349,7 @@ fn default_emitter(
13491349
// JUSTIFICATION: literally session construction
13501350
#[allow(rustc::bad_opt_access)]
13511351
pub fn build_session(
1352-
handler: &EarlyErrorHandler,
1352+
early_handler: EarlyErrorHandler,
13531353
sopts: config::Options,
13541354
io: CompilerIO,
13551355
bundle: Option<Lrc<rustc_errors::FluentBundle>>,
@@ -1379,12 +1379,13 @@ pub fn build_session(
13791379
None => filesearch::get_or_default_sysroot().expect("Failed finding sysroot"),
13801380
};
13811381

1382-
let target_cfg = config::build_target_config(handler, &sopts, target_override, &sysroot);
1382+
let target_cfg = config::build_target_config(&early_handler, &sopts, target_override, &sysroot);
13831383
let host_triple = TargetTriple::from_triple(config::host_triple());
1384-
let (host, target_warnings) = Target::search(&host_triple, &sysroot)
1385-
.unwrap_or_else(|e| handler.early_error(format!("Error loading host specification: {e}")));
1384+
let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| {
1385+
early_handler.early_error(format!("Error loading host specification: {e}"))
1386+
});
13861387
for warning in target_warnings.warning_messages() {
1387-
handler.early_warn(warning)
1388+
early_handler.early_warn(warning)
13881389
}
13891390

13901391
let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
@@ -1413,6 +1414,10 @@ pub fn build_session(
14131414
span_diagnostic = span_diagnostic.with_ice_file(ice_file);
14141415
}
14151416

1417+
// Now that the proper handler has been constructed, drop the early handler
1418+
// to prevent accidental use.
1419+
drop(early_handler);
1420+
14161421
let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
14171422
{
14181423
let directory =
@@ -1427,7 +1432,7 @@ pub fn build_session(
14271432
match profiler {
14281433
Ok(profiler) => Some(Arc::new(profiler)),
14291434
Err(e) => {
1430-
handler.early_warn(format!("failed to create profiler: {e}"));
1435+
span_diagnostic.emit_warning(errors::FailedToCreateProfiler { err: e.to_string() });
14311436
None
14321437
}
14331438
}
@@ -1471,7 +1476,13 @@ pub fn build_session(
14711476

14721477
// Check jobserver before getting `jobserver::client`.
14731478
jobserver::check(|err| {
1474-
handler.early_warn_with_note(err, "the build environment is likely misconfigured")
1479+
#[allow(rustc::untranslatable_diagnostic)]
1480+
#[allow(rustc::diagnostic_outside_of_impl)]
1481+
parse_sess
1482+
.span_diagnostic
1483+
.struct_warn(err)
1484+
.note("the build environment is likely misconfigured")
1485+
.emit()
14751486
});
14761487

14771488
let sess = Session {
@@ -1781,16 +1792,6 @@ impl EarlyErrorHandler {
17811792
pub fn early_warn(&self, msg: impl Into<DiagnosticMessage>) {
17821793
self.handler.struct_warn(msg).emit()
17831794
}
1784-
1785-
#[allow(rustc::untranslatable_diagnostic)]
1786-
#[allow(rustc::diagnostic_outside_of_impl)]
1787-
pub fn early_warn_with_note(
1788-
&self,
1789-
msg: impl Into<DiagnosticMessage>,
1790-
note: impl Into<SubdiagnosticMessage>,
1791-
) {
1792-
self.handler.struct_warn(msg).note(note).emit()
1793-
}
17941795
}
17951796

17961797
fn mk_emitter(output: ErrorOutputType) -> Box<DynEmitter> {

tests/run-make/jobserver-error/cannot_open_fd.stderr

+2
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,5 @@ warning: failed to connect to jobserver from environment variable `MAKEFLAGS="--
44

55
error: no input filename given
66

7+
warning: 1 warning emitted
8+

tests/run-make/jobserver-error/not_a_pipe.stderr

+2
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,5 @@ warning: failed to connect to jobserver from environment variable `MAKEFLAGS="--
22
|
33
= note: the build environment is likely misconfigured
44

5+
warning: 1 warning emitted
6+

0 commit comments

Comments
 (0)