Skip to content

Commit 7df0c21

Browse files
committed
Auto merge of #118635 - nnethercote:fewer-early-errors, r=davidtwco
Fewer early errors r? `@davidtwco`
2 parents b9540b7 + 6184099 commit 7df0c21

File tree

7 files changed

+66
-48
lines changed

7 files changed

+66
-48
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();
@@ -112,10 +116,14 @@ pub(crate) fn parse_check_cfg(handler: &EarlyErrorHandler, specs: Vec<String>) -
112116

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

@@ -314,13 +322,13 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
314322
|| {
315323
crate::callbacks::setup_callbacks();
316324

317-
let handler = EarlyErrorHandler::new(config.opts.error_format);
325+
let early_handler = EarlyErrorHandler::new(config.opts.error_format);
318326

319327
let codegen_backend = if let Some(make_codegen_backend) = config.make_codegen_backend {
320328
make_codegen_backend(&config.opts)
321329
} else {
322330
util::get_codegen_backend(
323-
&handler,
331+
&early_handler,
324332
&config.opts.maybe_sysroot,
325333
config.opts.unstable_opts.codegen_backend.as_deref(),
326334
)
@@ -337,7 +345,7 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
337345
) {
338346
Ok(bundle) => bundle,
339347
Err(e) => {
340-
handler.early_error(format!("failed to load fluent bundle: {e}"));
348+
early_handler.early_error(format!("failed to load fluent bundle: {e}"));
341349
}
342350
};
343351

@@ -348,7 +356,7 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
348356
let target_override = codegen_backend.target_override(&config.opts);
349357

350358
let mut sess = rustc_session::build_session(
351-
&handler,
359+
early_handler,
352360
config.opts,
353361
CompilerIO {
354362
input: config.input,
@@ -370,12 +378,12 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
370378

371379
codegen_backend.init(&sess);
372380

373-
let cfg = parse_cfg(&handler, config.crate_cfg);
381+
let cfg = parse_cfg(&sess.diagnostic(), config.crate_cfg);
374382
let mut cfg = config::build_configuration(&sess, cfg);
375383
util::add_configuration(&mut cfg, &mut sess, &*codegen_backend);
376384
sess.parse_sess.config = cfg;
377385

378-
let mut check_cfg = parse_check_cfg(&handler, config.crate_check_cfg);
386+
let mut check_cfg = parse_check_cfg(&sess.diagnostic(), config.crate_check_cfg);
379387
check_cfg.fill_well_known(&sess.target);
380388
sess.parse_sess.check_config = check_cfg;
381389

compiler/rustc_interface/src/tests.rs

+10-14
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,10 @@ use std::num::NonZeroUsize;
2525
use std::path::{Path, PathBuf};
2626
use std::sync::Arc;
2727

28-
fn mk_session(handler: &mut EarlyErrorHandler, matches: getopts::Matches) -> (Session, Cfg) {
28+
fn mk_session(matches: getopts::Matches) -> (Session, Cfg) {
29+
let mut early_handler = EarlyErrorHandler::new(ErrorOutputType::default());
2930
let registry = registry::Registry::new(&[]);
30-
let sessopts = build_session_options(handler, &matches);
31-
let cfg = parse_cfg(handler, matches.opt_strs("cfg"));
31+
let sessopts = build_session_options(&mut early_handler, &matches);
3232
let temps_dir = sessopts.unstable_opts.temps_dir.as_deref().map(PathBuf::from);
3333
let io = CompilerIO {
3434
input: Input::Str { name: FileName::Custom(String::new()), input: String::new() },
@@ -37,7 +37,7 @@ fn mk_session(handler: &mut EarlyErrorHandler, matches: getopts::Matches) -> (Se
3737
temps_dir,
3838
};
3939
let sess = build_session(
40-
handler,
40+
early_handler,
4141
sessopts,
4242
io,
4343
None,
@@ -51,6 +51,7 @@ fn mk_session(handler: &mut EarlyErrorHandler, matches: getopts::Matches) -> (Se
5151
Arc::default(),
5252
Default::default(),
5353
);
54+
let cfg = parse_cfg(&sess.diagnostic(), matches.opt_strs("cfg"));
5455
(sess, cfg)
5556
}
5657

@@ -117,8 +118,7 @@ fn assert_non_crate_hash_different(x: &Options, y: &Options) {
117118
fn test_switch_implies_cfg_test() {
118119
rustc_span::create_default_session_globals_then(|| {
119120
let matches = optgroups().parse(&["--test".to_string()]).unwrap();
120-
let mut handler = EarlyErrorHandler::new(ErrorOutputType::default());
121-
let (sess, cfg) = mk_session(&mut handler, matches);
121+
let (sess, cfg) = mk_session(matches);
122122
let cfg = build_configuration(&sess, cfg);
123123
assert!(cfg.contains(&(sym::test, None)));
124124
});
@@ -129,8 +129,7 @@ fn test_switch_implies_cfg_test() {
129129
fn test_switch_implies_cfg_test_unless_cfg_test() {
130130
rustc_span::create_default_session_globals_then(|| {
131131
let matches = optgroups().parse(&["--test".to_string(), "--cfg=test".to_string()]).unwrap();
132-
let mut handler = EarlyErrorHandler::new(ErrorOutputType::default());
133-
let (sess, cfg) = mk_session(&mut handler, matches);
132+
let (sess, cfg) = mk_session(matches);
134133
let cfg = build_configuration(&sess, cfg);
135134
let mut test_items = cfg.iter().filter(|&&(name, _)| name == sym::test);
136135
assert!(test_items.next().is_some());
@@ -142,23 +141,20 @@ fn test_switch_implies_cfg_test_unless_cfg_test() {
142141
fn test_can_print_warnings() {
143142
rustc_span::create_default_session_globals_then(|| {
144143
let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap();
145-
let mut handler = EarlyErrorHandler::new(ErrorOutputType::default());
146-
let (sess, _) = mk_session(&mut handler, matches);
144+
let (sess, _) = mk_session(matches);
147145
assert!(!sess.diagnostic().can_emit_warnings());
148146
});
149147

150148
rustc_span::create_default_session_globals_then(|| {
151149
let matches =
152150
optgroups().parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()]).unwrap();
153-
let mut handler = EarlyErrorHandler::new(ErrorOutputType::default());
154-
let (sess, _) = mk_session(&mut handler, matches);
151+
let (sess, _) = mk_session(matches);
155152
assert!(sess.diagnostic().can_emit_warnings());
156153
});
157154

158155
rustc_span::create_default_session_globals_then(|| {
159156
let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap();
160-
let mut handler = EarlyErrorHandler::new(ErrorOutputType::default());
161-
let (sess, _) = mk_session(&mut handler, matches);
157+
let (sess, _) = mk_session(matches);
162158
assert!(sess.diagnostic().can_emit_warnings());
163159
});
164160
}

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)