Rename many DiagCtxt arguments.

This commit is contained in:
Nicholas Nethercote 2023-12-18 10:15:45 +11:00
parent 4dc7fab56f
commit f422dca3ae
44 changed files with 317 additions and 353 deletions

View file

@ -696,7 +696,7 @@ impl<'a> AstValidator<'a> {
/// Checks that generic parameters are in the correct order, /// Checks that generic parameters are in the correct order,
/// which is lifetimes, then types and then consts. (`<'a, T, const N: usize>`) /// which is lifetimes, then types and then consts. (`<'a, T, const N: usize>`)
fn validate_generic_param_order( fn validate_generic_param_order(
handler: &rustc_errors::DiagCtxt, dcx: &rustc_errors::DiagCtxt,
generics: &[GenericParam], generics: &[GenericParam],
span: Span, span: Span,
) { ) {
@ -759,7 +759,7 @@ fn validate_generic_param_order(
ordered_params += ">"; ordered_params += ">";
for (param_ord, (max_param, spans)) in &out_of_order { for (param_ord, (max_param, spans)) in &out_of_order {
handler.emit_err(errors::OutOfOrderParams { dcx.emit_err(errors::OutOfOrderParams {
spans: spans.clone(), spans: spans.clone(),
sugg_span: span, sugg_span: span,
param_ord, param_ord,

View file

@ -51,9 +51,9 @@ pub(crate) struct UnknownMetaItem<'a> {
// Manual implementation to be able to format `expected` items correctly. // Manual implementation to be able to format `expected` items correctly.
impl<'a> IntoDiagnostic<'a> for UnknownMetaItem<'_> { impl<'a> IntoDiagnostic<'a> for UnknownMetaItem<'_> {
fn into_diagnostic(self, handler: &'a DiagCtxt) -> DiagnosticBuilder<'a, ErrorGuaranteed> { fn into_diagnostic(self, dcx: &'a DiagCtxt) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
let expected = self.expected.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>(); let expected = self.expected.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>();
let mut diag = handler.struct_span_err_with_code( let mut diag = dcx.struct_span_err_with_code(
self.span, self.span,
fluent::attr_unknown_meta_item, fluent::attr_unknown_meta_item,
error_code!(E0541), error_code!(E0541),
@ -201,8 +201,8 @@ pub(crate) struct UnsupportedLiteral {
} }
impl<'a> IntoDiagnostic<'a> for UnsupportedLiteral { impl<'a> IntoDiagnostic<'a> for UnsupportedLiteral {
fn into_diagnostic(self, handler: &'a DiagCtxt) -> DiagnosticBuilder<'a, ErrorGuaranteed> { fn into_diagnostic(self, dcx: &'a DiagCtxt) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
let mut diag = handler.struct_span_err_with_code( let mut diag = dcx.struct_span_err_with_code(
self.span, self.span,
match self.reason { match self.reason {
UnsupportedLiteralReason::Generic => fluent::attr_unsupported_literal_generic, UnsupportedLiteralReason::Generic => fluent::attr_unsupported_literal_generic,

View file

@ -624,7 +624,7 @@ impl UseSpans<'_> {
/// Add a subdiagnostic to the use of the captured variable, if it exists. /// Add a subdiagnostic to the use of the captured variable, if it exists.
pub(super) fn var_subdiag( pub(super) fn var_subdiag(
self, self,
handler: Option<&rustc_errors::DiagCtxt>, dcx: Option<&rustc_errors::DiagCtxt>,
err: &mut Diagnostic, err: &mut Diagnostic,
kind: Option<rustc_middle::mir::BorrowKind>, kind: Option<rustc_middle::mir::BorrowKind>,
f: impl FnOnce(Option<CoroutineKind>, Span) -> CaptureVarCause, f: impl FnOnce(Option<CoroutineKind>, Span) -> CaptureVarCause,
@ -646,7 +646,7 @@ impl UseSpans<'_> {
}); });
}; };
let diag = f(coroutine_kind, path_span); let diag = f(coroutine_kind, path_span);
match handler { match dcx {
Some(hd) => err.eager_subdiagnostic(hd, diag), Some(hd) => err.eager_subdiagnostic(hd, diag),
None => err.subdiagnostic(diag), None => err.subdiagnostic(diag),
}; };

View file

@ -448,12 +448,12 @@ pub(crate) struct EnvNotDefinedWithUserMessage {
// Hand-written implementation to support custom user messages. // Hand-written implementation to support custom user messages.
impl<'a> IntoDiagnostic<'a> for EnvNotDefinedWithUserMessage { impl<'a> IntoDiagnostic<'a> for EnvNotDefinedWithUserMessage {
#[track_caller] #[track_caller]
fn into_diagnostic(self, handler: &'a DiagCtxt) -> DiagnosticBuilder<'a, ErrorGuaranteed> { fn into_diagnostic(self, dcx: &'a DiagCtxt) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
#[expect( #[expect(
rustc::untranslatable_diagnostic, rustc::untranslatable_diagnostic,
reason = "cannot translate user-provided messages" reason = "cannot translate user-provided messages"
)] )]
let mut diag = handler.struct_err(self.msg_from_user.to_string()); let mut diag = dcx.struct_err(self.msg_from_user.to_string());
diag.set_span(self.span); diag.set_span(self.span);
diag diag
} }
@ -802,17 +802,16 @@ pub(crate) struct AsmClobberNoReg {
} }
impl<'a> IntoDiagnostic<'a> for AsmClobberNoReg { impl<'a> IntoDiagnostic<'a> for AsmClobberNoReg {
fn into_diagnostic(self, handler: &'a DiagCtxt) -> DiagnosticBuilder<'a, ErrorGuaranteed> { fn into_diagnostic(self, dcx: &'a DiagCtxt) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
let mut diag = let mut diag = dcx.struct_err(crate::fluent_generated::builtin_macros_asm_clobber_no_reg);
handler.struct_err(crate::fluent_generated::builtin_macros_asm_clobber_no_reg);
diag.set_span(self.spans.clone()); diag.set_span(self.spans.clone());
// eager translation as `span_labels` takes `AsRef<str>` // eager translation as `span_labels` takes `AsRef<str>`
let lbl1 = handler.eagerly_translate_to_string( let lbl1 = dcx.eagerly_translate_to_string(
crate::fluent_generated::builtin_macros_asm_clobber_abi, crate::fluent_generated::builtin_macros_asm_clobber_abi,
[].into_iter(), [].into_iter(),
); );
diag.span_labels(self.clobbers, &lbl1); diag.span_labels(self.clobbers, &lbl1);
let lbl2 = handler.eagerly_translate_to_string( let lbl2 = dcx.eagerly_translate_to_string(
crate::fluent_generated::builtin_macros_asm_clobber_outputs, crate::fluent_generated::builtin_macros_asm_clobber_outputs,
[].into_iter(), [].into_iter(),
); );

View file

@ -52,7 +52,7 @@ pub fn inject(
is_proc_macro_crate: bool, is_proc_macro_crate: bool,
has_proc_macro_decls: bool, has_proc_macro_decls: bool,
is_test_crate: bool, is_test_crate: bool,
handler: &rustc_errors::DiagCtxt, dcx: &rustc_errors::DiagCtxt,
) { ) {
let ecfg = ExpansionConfig::default("proc_macro".to_string(), features); let ecfg = ExpansionConfig::default("proc_macro".to_string(), features);
let mut cx = ExtCtxt::new(sess, ecfg, resolver, None); let mut cx = ExtCtxt::new(sess, ecfg, resolver, None);
@ -60,7 +60,7 @@ pub fn inject(
let mut collect = CollectProcMacros { let mut collect = CollectProcMacros {
macros: Vec::new(), macros: Vec::new(),
in_root: true, in_root: true,
dcx: handler, dcx,
source_map: sess.source_map(), source_map: sess.source_map(),
is_proc_macro_crate, is_proc_macro_crate,
is_test_crate, is_test_crate,

View file

@ -389,7 +389,7 @@ fn get_test_name(i: &ast::Item) -> Option<Symbol> {
attr::first_attr_value_str_by_name(&i.attrs, sym::rustc_test_marker) attr::first_attr_value_str_by_name(&i.attrs, sym::rustc_test_marker)
} }
fn get_test_runner(sd: &rustc_errors::DiagCtxt, krate: &ast::Crate) -> Option<ast::Path> { fn get_test_runner(dcx: &rustc_errors::DiagCtxt, krate: &ast::Crate) -> Option<ast::Path> {
let test_attr = attr::find_by_name(&krate.attrs, sym::test_runner)?; let test_attr = attr::find_by_name(&krate.attrs, sym::test_runner)?;
let meta_list = test_attr.meta_item_list()?; let meta_list = test_attr.meta_item_list()?;
let span = test_attr.span; let span = test_attr.span;
@ -397,11 +397,11 @@ fn get_test_runner(sd: &rustc_errors::DiagCtxt, krate: &ast::Crate) -> Option<as
[single] => match single.meta_item() { [single] => match single.meta_item() {
Some(meta_item) if meta_item.is_word() => return Some(meta_item.path.clone()), Some(meta_item) if meta_item.is_word() => return Some(meta_item.path.clone()),
_ => { _ => {
sd.emit_err(errors::TestRunnerInvalid { span }); dcx.emit_err(errors::TestRunnerInvalid { span });
} }
}, },
_ => { _ => {
sd.emit_err(errors::TestRunnerNargs { span }); dcx.emit_err(errors::TestRunnerNargs { span });
} }
} }
None None

View file

@ -46,7 +46,7 @@ impl ConcurrencyLimiter {
} }
} }
pub(super) fn acquire(&mut self, handler: &rustc_errors::DiagCtxt) -> ConcurrencyLimiterToken { pub(super) fn acquire(&mut self, dcx: &rustc_errors::DiagCtxt) -> ConcurrencyLimiterToken {
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock().unwrap();
loop { loop {
state.assert_invariants(); state.assert_invariants();
@ -64,7 +64,7 @@ impl ConcurrencyLimiter {
// Make sure to drop the mutex guard first to prevent poisoning the mutex. // Make sure to drop the mutex guard first to prevent poisoning the mutex.
drop(state); drop(state);
if let Some(err) = err { if let Some(err) = err {
handler.fatal(err); dcx.fatal(err);
} else { } else {
// The error was already emitted, but compilation continued. Raise a silent // The error was already emitted, but compilation continued. Raise a silent
// fatal error. // fatal error.

View file

@ -61,7 +61,7 @@ struct LtoData {
tmp_path: TempDir, tmp_path: TempDir,
} }
fn prepare_lto(cgcx: &CodegenContext<GccCodegenBackend>, diag_handler: &DiagCtxt) -> Result<LtoData, FatalError> { fn prepare_lto(cgcx: &CodegenContext<GccCodegenBackend>, dcx: &DiagCtxt) -> Result<LtoData, FatalError> {
let export_threshold = match cgcx.lto { let export_threshold = match cgcx.lto {
// We're just doing LTO for our one crate // We're just doing LTO for our one crate
Lto::ThinLocal => SymbolExportLevel::Rust, Lto::ThinLocal => SymbolExportLevel::Rust,
@ -106,18 +106,18 @@ fn prepare_lto(cgcx: &CodegenContext<GccCodegenBackend>, diag_handler: &DiagCtxt
// Make sure we actually can run LTO // Make sure we actually can run LTO
for crate_type in cgcx.crate_types.iter() { for crate_type in cgcx.crate_types.iter() {
if !crate_type_allows_lto(*crate_type) { if !crate_type_allows_lto(*crate_type) {
diag_handler.emit_err(LtoDisallowed); dcx.emit_err(LtoDisallowed);
return Err(FatalError); return Err(FatalError);
} else if *crate_type == CrateType::Dylib { } else if *crate_type == CrateType::Dylib {
if !cgcx.opts.unstable_opts.dylib_lto { if !cgcx.opts.unstable_opts.dylib_lto {
diag_handler.emit_err(LtoDylib); dcx.emit_err(LtoDylib);
return Err(FatalError); return Err(FatalError);
} }
} }
} }
if cgcx.opts.cg.prefer_dynamic && !cgcx.opts.unstable_opts.dylib_lto { if cgcx.opts.cg.prefer_dynamic && !cgcx.opts.unstable_opts.dylib_lto {
diag_handler.emit_err(DynamicLinkingWithLTO); dcx.emit_err(DynamicLinkingWithLTO);
return Err(FatalError); return Err(FatalError);
} }
@ -154,7 +154,7 @@ fn prepare_lto(cgcx: &CodegenContext<GccCodegenBackend>, diag_handler: &DiagCtxt
upstream_modules.push((module, CString::new(name).unwrap())); upstream_modules.push((module, CString::new(name).unwrap()));
} }
Err(e) => { Err(e) => {
diag_handler.emit_err(e); dcx.emit_err(e);
return Err(FatalError); return Err(FatalError);
} }
} }
@ -183,16 +183,16 @@ pub(crate) fn run_fat(
modules: Vec<FatLtoInput<GccCodegenBackend>>, modules: Vec<FatLtoInput<GccCodegenBackend>>,
cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>, cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
) -> Result<LtoModuleCodegen<GccCodegenBackend>, FatalError> { ) -> Result<LtoModuleCodegen<GccCodegenBackend>, FatalError> {
let diag_handler = cgcx.create_dcx(); let dcx = cgcx.create_dcx();
let lto_data = prepare_lto(cgcx, &diag_handler)?; let lto_data = prepare_lto(cgcx, &dcx)?;
/*let symbols_below_threshold = /*let symbols_below_threshold =
lto_data.symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();*/ lto_data.symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();*/
fat_lto(cgcx, &diag_handler, modules, cached_modules, lto_data.upstream_modules, lto_data.tmp_path, fat_lto(cgcx, &dcx, modules, cached_modules, lto_data.upstream_modules, lto_data.tmp_path,
//&symbols_below_threshold, //&symbols_below_threshold,
) )
} }
fn fat_lto(cgcx: &CodegenContext<GccCodegenBackend>, _diag_handler: &DiagCtxt, modules: Vec<FatLtoInput<GccCodegenBackend>>, cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>, mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>, tmp_path: TempDir, fn fat_lto(cgcx: &CodegenContext<GccCodegenBackend>, _dcx: &DiagCtxt, modules: Vec<FatLtoInput<GccCodegenBackend>>, cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>, mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>, tmp_path: TempDir,
//symbols_below_threshold: &[*const libc::c_char], //symbols_below_threshold: &[*const libc::c_char],
) -> Result<LtoModuleCodegen<GccCodegenBackend>, FatalError> { ) -> Result<LtoModuleCodegen<GccCodegenBackend>, FatalError> {
let _timer = cgcx.prof.generic_activity("GCC_fat_lto_build_monolithic_module"); let _timer = cgcx.prof.generic_activity("GCC_fat_lto_build_monolithic_module");
@ -257,7 +257,7 @@ fn fat_lto(cgcx: &CodegenContext<GccCodegenBackend>, _diag_handler: &DiagCtxt, m
let (buffer, name) = serialized_modules.remove(0); let (buffer, name) = serialized_modules.remove(0);
info!("no in-memory regular modules to choose from, parsing {:?}", name); info!("no in-memory regular modules to choose from, parsing {:?}", name);
ModuleCodegen { ModuleCodegen {
module_llvm: GccContext::parse(cgcx, &name, buffer.data(), diag_handler)?, module_llvm: GccContext::parse(cgcx, &name, buffer.data(), dcx)?,
name: name.into_string().unwrap(), name: name.into_string().unwrap(),
kind: ModuleKind::Regular, kind: ModuleKind::Regular,
}*/ }*/

View file

@ -13,7 +13,7 @@ use rustc_target::spec::SplitDebuginfo;
use crate::{GccCodegenBackend, GccContext}; use crate::{GccCodegenBackend, GccContext};
use crate::errors::CopyBitcode; use crate::errors::CopyBitcode;
pub(crate) unsafe fn codegen(cgcx: &CodegenContext<GccCodegenBackend>, diag_handler: &DiagCtxt, module: ModuleCodegen<GccContext>, config: &ModuleConfig) -> Result<CompiledModule, FatalError> { pub(crate) unsafe fn codegen(cgcx: &CodegenContext<GccCodegenBackend>, dcx: &DiagCtxt, module: ModuleCodegen<GccContext>, config: &ModuleConfig) -> Result<CompiledModule, FatalError> {
let _timer = cgcx.prof.generic_activity_with_arg("GCC_module_codegen", &*module.name); let _timer = cgcx.prof.generic_activity_with_arg("GCC_module_codegen", &*module.name);
{ {
let context = &module.module_llvm.context; let context = &module.module_llvm.context;
@ -127,12 +127,12 @@ pub(crate) unsafe fn codegen(cgcx: &CodegenContext<GccCodegenBackend>, diag_hand
EmitObj::Bitcode => { EmitObj::Bitcode => {
debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out); debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
if let Err(err) = link_or_copy(&bc_out, &obj_out) { if let Err(err) = link_or_copy(&bc_out, &obj_out) {
diag_handler.emit_err(CopyBitcode { err }); dcx.emit_err(CopyBitcode { err });
} }
if !config.emit_bc { if !config.emit_bc {
debug!("removing_bitcode {:?}", bc_out); debug!("removing_bitcode {:?}", bc_out);
ensure_removed(diag_handler, &bc_out); ensure_removed(dcx, &bc_out);
} }
} }
@ -148,7 +148,7 @@ pub(crate) unsafe fn codegen(cgcx: &CodegenContext<GccCodegenBackend>, diag_hand
)) ))
} }
pub(crate) fn link(_cgcx: &CodegenContext<GccCodegenBackend>, _diag_handler: &DiagCtxt, mut _modules: Vec<ModuleCodegen<GccContext>>) -> Result<ModuleCodegen<GccContext>, FatalError> { pub(crate) fn link(_cgcx: &CodegenContext<GccCodegenBackend>, _dcx: &DiagCtxt, mut _modules: Vec<ModuleCodegen<GccContext>>) -> Result<ModuleCodegen<GccContext>, FatalError> {
unimplemented!(); unimplemented!();
} }

View file

@ -112,8 +112,8 @@ pub(crate) struct TargetFeatureDisableOrEnable<'a> {
pub(crate) struct MissingFeatures; pub(crate) struct MissingFeatures;
impl IntoDiagnostic<'_, ErrorGuaranteed> for TargetFeatureDisableOrEnable<'_> { impl IntoDiagnostic<'_, ErrorGuaranteed> for TargetFeatureDisableOrEnable<'_> {
fn into_diagnostic(self, handler: &'_ DiagCtxt) -> DiagnosticBuilder<'_, ErrorGuaranteed> { fn into_diagnostic(self, dcx: &'_ DiagCtxt) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
let mut diag = handler.struct_err(fluent::codegen_gcc_target_feature_disable_or_enable); let mut diag = dcx.struct_err(fluent::codegen_gcc_target_feature_disable_or_enable);
if let Some(span) = self.span { if let Some(span) = self.span {
diag.set_span(span); diag.set_span(span);
}; };

View file

@ -330,7 +330,7 @@ impl WriteBackendMethods for GccCodegenBackend {
unimplemented!() unimplemented!()
} }
unsafe fn optimize(_cgcx: &CodegenContext<Self>, _diag_handler: &DiagCtxt, module: &ModuleCodegen<Self::Module>, config: &ModuleConfig) -> Result<(), FatalError> { unsafe fn optimize(_cgcx: &CodegenContext<Self>, _dcx: &DiagCtxt, module: &ModuleCodegen<Self::Module>, config: &ModuleConfig) -> Result<(), FatalError> {
module.module_llvm.context.set_optimization_level(to_gcc_opt_level(config.opt_level)); module.module_llvm.context.set_optimization_level(to_gcc_opt_level(config.opt_level));
Ok(()) Ok(())
} }
@ -344,8 +344,8 @@ impl WriteBackendMethods for GccCodegenBackend {
unimplemented!(); unimplemented!();
} }
unsafe fn codegen(cgcx: &CodegenContext<Self>, diag_handler: &DiagCtxt, module: ModuleCodegen<Self::Module>, config: &ModuleConfig) -> Result<CompiledModule, FatalError> { unsafe fn codegen(cgcx: &CodegenContext<Self>, dcx: &DiagCtxt, module: ModuleCodegen<Self::Module>, config: &ModuleConfig) -> Result<CompiledModule, FatalError> {
back::write::codegen(cgcx, diag_handler, module, config) back::write::codegen(cgcx, dcx, module, config)
} }
fn prepare_thin(_module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) { fn prepare_thin(_module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
@ -356,8 +356,8 @@ impl WriteBackendMethods for GccCodegenBackend {
unimplemented!(); unimplemented!();
} }
fn run_link(cgcx: &CodegenContext<Self>, diag_handler: &DiagCtxt, modules: Vec<ModuleCodegen<Self::Module>>) -> Result<ModuleCodegen<Self::Module>, FatalError> { fn run_link(cgcx: &CodegenContext<Self>, dcx: &DiagCtxt, modules: Vec<ModuleCodegen<Self::Module>>) -> Result<ModuleCodegen<Self::Module>, FatalError> {
back::write::link(cgcx, diag_handler, modules) back::write::link(cgcx, dcx, modules)
} }
} }

View file

@ -47,7 +47,7 @@ pub fn crate_type_allows_lto(crate_type: CrateType) -> bool {
fn prepare_lto( fn prepare_lto(
cgcx: &CodegenContext<LlvmCodegenBackend>, cgcx: &CodegenContext<LlvmCodegenBackend>,
diag_handler: &DiagCtxt, dcx: &DiagCtxt,
) -> Result<(Vec<CString>, Vec<(SerializedModule<ModuleBuffer>, CString)>), FatalError> { ) -> Result<(Vec<CString>, Vec<(SerializedModule<ModuleBuffer>, CString)>), FatalError> {
let export_threshold = match cgcx.lto { let export_threshold = match cgcx.lto {
// We're just doing LTO for our one crate // We're just doing LTO for our one crate
@ -84,23 +84,23 @@ fn prepare_lto(
// Make sure we actually can run LTO // Make sure we actually can run LTO
for crate_type in cgcx.crate_types.iter() { for crate_type in cgcx.crate_types.iter() {
if !crate_type_allows_lto(*crate_type) { if !crate_type_allows_lto(*crate_type) {
diag_handler.emit_err(LtoDisallowed); dcx.emit_err(LtoDisallowed);
return Err(FatalError); return Err(FatalError);
} else if *crate_type == CrateType::Dylib { } else if *crate_type == CrateType::Dylib {
if !cgcx.opts.unstable_opts.dylib_lto { if !cgcx.opts.unstable_opts.dylib_lto {
diag_handler.emit_err(LtoDylib); dcx.emit_err(LtoDylib);
return Err(FatalError); return Err(FatalError);
} }
} else if *crate_type == CrateType::ProcMacro { } else if *crate_type == CrateType::ProcMacro {
if !cgcx.opts.unstable_opts.dylib_lto { if !cgcx.opts.unstable_opts.dylib_lto {
diag_handler.emit_err(LtoProcMacro); dcx.emit_err(LtoProcMacro);
return Err(FatalError); return Err(FatalError);
} }
} }
} }
if cgcx.opts.cg.prefer_dynamic && !cgcx.opts.unstable_opts.dylib_lto { if cgcx.opts.cg.prefer_dynamic && !cgcx.opts.unstable_opts.dylib_lto {
diag_handler.emit_err(DynamicLinkingWithLTO); dcx.emit_err(DynamicLinkingWithLTO);
return Err(FatalError); return Err(FatalError);
} }
@ -138,7 +138,7 @@ fn prepare_lto(
upstream_modules.push((module, CString::new(name).unwrap())); upstream_modules.push((module, CString::new(name).unwrap()));
} }
Err(e) => { Err(e) => {
diag_handler.emit_err(e); dcx.emit_err(e);
return Err(FatalError); return Err(FatalError);
} }
} }
@ -250,7 +250,7 @@ pub(crate) fn prepare_thin(module: ModuleCodegen<ModuleLlvm>) -> (String, ThinBu
fn fat_lto( fn fat_lto(
cgcx: &CodegenContext<LlvmCodegenBackend>, cgcx: &CodegenContext<LlvmCodegenBackend>,
diag_handler: &DiagCtxt, dcx: &DiagCtxt,
modules: Vec<FatLtoInput<LlvmCodegenBackend>>, modules: Vec<FatLtoInput<LlvmCodegenBackend>>,
cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>, cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>, mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
@ -316,7 +316,7 @@ fn fat_lto(
let (buffer, name) = serialized_modules.remove(0); let (buffer, name) = serialized_modules.remove(0);
info!("no in-memory regular modules to choose from, parsing {:?}", name); info!("no in-memory regular modules to choose from, parsing {:?}", name);
ModuleCodegen { ModuleCodegen {
module_llvm: ModuleLlvm::parse(cgcx, &name, buffer.data(), diag_handler)?, module_llvm: ModuleLlvm::parse(cgcx, &name, buffer.data(), dcx)?,
name: name.into_string().unwrap(), name: name.into_string().unwrap(),
kind: ModuleKind::Regular, kind: ModuleKind::Regular,
} }
@ -333,13 +333,8 @@ fn fat_lto(
// The linking steps below may produce errors and diagnostics within LLVM // The linking steps below may produce errors and diagnostics within LLVM
// which we'd like to handle and print, so set up our diagnostic handlers // which we'd like to handle and print, so set up our diagnostic handlers
// (which get unregistered when they go out of scope below). // (which get unregistered when they go out of scope below).
let _handler = DiagnosticHandlers::new( let _handler =
cgcx, DiagnosticHandlers::new(cgcx, dcx, llcx, &module, CodegenDiagnosticsStage::LTO);
diag_handler,
llcx,
&module,
CodegenDiagnosticsStage::LTO,
);
// For all other modules we codegened we'll need to link them into our own // For all other modules we codegened we'll need to link them into our own
// bitcode. All modules were codegened in their own LLVM context, however, // bitcode. All modules were codegened in their own LLVM context, however,
@ -367,9 +362,7 @@ fn fat_lto(
}); });
info!("linking {:?}", name); info!("linking {:?}", name);
let data = bc_decoded.data(); let data = bc_decoded.data();
linker linker.add(data).map_err(|()| write::llvm_err(dcx, LlvmError::LoadBitcode { name }))?;
.add(data)
.map_err(|()| write::llvm_err(diag_handler, LlvmError::LoadBitcode { name }))?;
serialized_bitcode.push(bc_decoded); serialized_bitcode.push(bc_decoded);
} }
drop(linker); drop(linker);
@ -452,7 +445,7 @@ impl Drop for Linker<'_> {
/// they all go out of scope. /// they all go out of scope.
fn thin_lto( fn thin_lto(
cgcx: &CodegenContext<LlvmCodegenBackend>, cgcx: &CodegenContext<LlvmCodegenBackend>,
diag_handler: &DiagCtxt, dcx: &DiagCtxt,
modules: Vec<(String, ThinBuffer)>, modules: Vec<(String, ThinBuffer)>,
serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>, serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>, cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
@ -527,7 +520,7 @@ fn thin_lto(
symbols_below_threshold.as_ptr(), symbols_below_threshold.as_ptr(),
symbols_below_threshold.len() as u32, symbols_below_threshold.len() as u32,
) )
.ok_or_else(|| write::llvm_err(diag_handler, LlvmError::PrepareThinLtoContext))?; .ok_or_else(|| write::llvm_err(dcx, LlvmError::PrepareThinLtoContext))?;
let data = ThinData(data); let data = ThinData(data);
@ -599,7 +592,7 @@ fn thin_lto(
// session, overwriting the previous serialized data (if any). // session, overwriting the previous serialized data (if any).
if let Some(path) = key_map_path { if let Some(path) = key_map_path {
if let Err(err) = curr_key_map.save_to_file(&path) { if let Err(err) = curr_key_map.save_to_file(&path) {
return Err(write::llvm_err(diag_handler, LlvmError::WriteThinLtoKey { err })); return Err(write::llvm_err(dcx, LlvmError::WriteThinLtoKey { err }));
} }
} }
@ -609,7 +602,7 @@ fn thin_lto(
pub(crate) fn run_pass_manager( pub(crate) fn run_pass_manager(
cgcx: &CodegenContext<LlvmCodegenBackend>, cgcx: &CodegenContext<LlvmCodegenBackend>,
diag_handler: &DiagCtxt, dcx: &DiagCtxt,
module: &mut ModuleCodegen<ModuleLlvm>, module: &mut ModuleCodegen<ModuleLlvm>,
thin: bool, thin: bool,
) -> Result<(), FatalError> { ) -> Result<(), FatalError> {
@ -637,7 +630,7 @@ pub(crate) fn run_pass_manager(
} }
let opt_stage = if thin { llvm::OptStage::ThinLTO } else { llvm::OptStage::FatLTO }; let opt_stage = if thin { llvm::OptStage::ThinLTO } else { llvm::OptStage::FatLTO };
let opt_level = config.opt_level.unwrap_or(config::OptLevel::No); let opt_level = config.opt_level.unwrap_or(config::OptLevel::No);
write::llvm_optimize(cgcx, diag_handler, module, config, opt_level, opt_stage)?; write::llvm_optimize(cgcx, dcx, module, config, opt_level, opt_stage)?;
} }
debug!("lto done"); debug!("lto done");
Ok(()) Ok(())
@ -868,10 +861,10 @@ pub fn parse_module<'a>(
cx: &'a llvm::Context, cx: &'a llvm::Context,
name: &CStr, name: &CStr,
data: &[u8], data: &[u8],
diag_handler: &DiagCtxt, dcx: &DiagCtxt,
) -> Result<&'a llvm::Module, FatalError> { ) -> Result<&'a llvm::Module, FatalError> {
unsafe { unsafe {
llvm::LLVMRustParseBitcodeForLTO(cx, data.as_ptr(), data.len(), name.as_ptr()) llvm::LLVMRustParseBitcodeForLTO(cx, data.as_ptr(), data.len(), name.as_ptr())
.ok_or_else(|| write::llvm_err(diag_handler, LlvmError::ParseBitcode)) .ok_or_else(|| write::llvm_err(dcx, LlvmError::ParseBitcode))
} }
} }

View file

@ -45,15 +45,15 @@ use std::slice;
use std::str; use std::str;
use std::sync::Arc; use std::sync::Arc;
pub fn llvm_err<'a>(handler: &rustc_errors::DiagCtxt, err: LlvmError<'a>) -> FatalError { pub fn llvm_err<'a>(dcx: &rustc_errors::DiagCtxt, err: LlvmError<'a>) -> FatalError {
match llvm::last_error() { match llvm::last_error() {
Some(llvm_err) => handler.emit_almost_fatal(WithLlvmError(err, llvm_err)), Some(llvm_err) => dcx.emit_almost_fatal(WithLlvmError(err, llvm_err)),
None => handler.emit_almost_fatal(err), None => dcx.emit_almost_fatal(err),
} }
} }
pub fn write_output_file<'ll>( pub fn write_output_file<'ll>(
handler: &rustc_errors::DiagCtxt, dcx: &rustc_errors::DiagCtxt,
target: &'ll llvm::TargetMachine, target: &'ll llvm::TargetMachine,
pm: &llvm::PassManager<'ll>, pm: &llvm::PassManager<'ll>,
m: &'ll llvm::Module, m: &'ll llvm::Module,
@ -93,9 +93,7 @@ pub fn write_output_file<'ll>(
} }
} }
result result.into_result().map_err(|()| llvm_err(dcx, LlvmError::WriteOutput { path: output }))
.into_result()
.map_err(|()| llvm_err(handler, LlvmError::WriteOutput { path: output }))
} }
} }
@ -340,7 +338,7 @@ pub struct DiagnosticHandlers<'a> {
impl<'a> DiagnosticHandlers<'a> { impl<'a> DiagnosticHandlers<'a> {
pub fn new( pub fn new(
cgcx: &'a CodegenContext<LlvmCodegenBackend>, cgcx: &'a CodegenContext<LlvmCodegenBackend>,
handler: &'a DiagCtxt, dcx: &'a DiagCtxt,
llcx: &'a llvm::Context, llcx: &'a llvm::Context,
module: &ModuleCodegen<ModuleLlvm>, module: &ModuleCodegen<ModuleLlvm>,
stage: CodegenDiagnosticsStage, stage: CodegenDiagnosticsStage,
@ -375,7 +373,7 @@ impl<'a> DiagnosticHandlers<'a> {
.and_then(|dir| dir.to_str().and_then(|p| CString::new(p).ok())); .and_then(|dir| dir.to_str().and_then(|p| CString::new(p).ok()));
let pgo_available = cgcx.opts.cg.profile_use.is_some(); let pgo_available = cgcx.opts.cg.profile_use.is_some();
let data = Box::into_raw(Box::new((cgcx, handler))); let data = Box::into_raw(Box::new((cgcx, dcx)));
unsafe { unsafe {
let old_handler = llvm::LLVMRustContextGetDiagnosticHandler(llcx); let old_handler = llvm::LLVMRustContextGetDiagnosticHandler(llcx);
llvm::LLVMRustContextConfigureDiagnosticHandler( llvm::LLVMRustContextConfigureDiagnosticHandler(
@ -507,7 +505,7 @@ fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
pub(crate) unsafe fn llvm_optimize( pub(crate) unsafe fn llvm_optimize(
cgcx: &CodegenContext<LlvmCodegenBackend>, cgcx: &CodegenContext<LlvmCodegenBackend>,
diag_handler: &DiagCtxt, dcx: &DiagCtxt,
module: &ModuleCodegen<ModuleLlvm>, module: &ModuleCodegen<ModuleLlvm>,
config: &ModuleConfig, config: &ModuleConfig,
opt_level: config::OptLevel, opt_level: config::OptLevel,
@ -588,13 +586,13 @@ pub(crate) unsafe fn llvm_optimize(
llvm_plugins.as_ptr().cast(), llvm_plugins.as_ptr().cast(),
llvm_plugins.len(), llvm_plugins.len(),
); );
result.into_result().map_err(|()| llvm_err(diag_handler, LlvmError::RunLlvmPasses)) result.into_result().map_err(|()| llvm_err(dcx, LlvmError::RunLlvmPasses))
} }
// Unsafe due to LLVM calls. // Unsafe due to LLVM calls.
pub(crate) unsafe fn optimize( pub(crate) unsafe fn optimize(
cgcx: &CodegenContext<LlvmCodegenBackend>, cgcx: &CodegenContext<LlvmCodegenBackend>,
diag_handler: &DiagCtxt, dcx: &DiagCtxt,
module: &ModuleCodegen<ModuleLlvm>, module: &ModuleCodegen<ModuleLlvm>,
config: &ModuleConfig, config: &ModuleConfig,
) -> Result<(), FatalError> { ) -> Result<(), FatalError> {
@ -602,8 +600,7 @@ pub(crate) unsafe fn optimize(
let llmod = module.module_llvm.llmod(); let llmod = module.module_llvm.llmod();
let llcx = &*module.module_llvm.llcx; let llcx = &*module.module_llvm.llcx;
let _handlers = let _handlers = DiagnosticHandlers::new(cgcx, dcx, llcx, module, CodegenDiagnosticsStage::Opt);
DiagnosticHandlers::new(cgcx, diag_handler, llcx, module, CodegenDiagnosticsStage::Opt);
let module_name = module.name.clone(); let module_name = module.name.clone();
let module_name = Some(&module_name[..]); let module_name = Some(&module_name[..]);
@ -621,14 +618,14 @@ pub(crate) unsafe fn optimize(
_ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO, _ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
_ => llvm::OptStage::PreLinkNoLTO, _ => llvm::OptStage::PreLinkNoLTO,
}; };
return llvm_optimize(cgcx, diag_handler, module, config, opt_level, opt_stage); return llvm_optimize(cgcx, dcx, module, config, opt_level, opt_stage);
} }
Ok(()) Ok(())
} }
pub(crate) fn link( pub(crate) fn link(
cgcx: &CodegenContext<LlvmCodegenBackend>, cgcx: &CodegenContext<LlvmCodegenBackend>,
diag_handler: &DiagCtxt, dcx: &DiagCtxt,
mut modules: Vec<ModuleCodegen<ModuleLlvm>>, mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> { ) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
use super::lto::{Linker, ModuleBuffer}; use super::lto::{Linker, ModuleBuffer};
@ -641,9 +638,9 @@ pub(crate) fn link(
for module in elements { for module in elements {
let _timer = cgcx.prof.generic_activity_with_arg("LLVM_link_module", &*module.name); let _timer = cgcx.prof.generic_activity_with_arg("LLVM_link_module", &*module.name);
let buffer = ModuleBuffer::new(module.module_llvm.llmod()); let buffer = ModuleBuffer::new(module.module_llvm.llmod());
linker.add(buffer.data()).map_err(|()| { linker
llvm_err(diag_handler, LlvmError::SerializeModule { name: &module.name }) .add(buffer.data())
})?; .map_err(|()| llvm_err(dcx, LlvmError::SerializeModule { name: &module.name }))?;
} }
drop(linker); drop(linker);
Ok(modules.remove(0)) Ok(modules.remove(0))
@ -651,7 +648,7 @@ pub(crate) fn link(
pub(crate) unsafe fn codegen( pub(crate) unsafe fn codegen(
cgcx: &CodegenContext<LlvmCodegenBackend>, cgcx: &CodegenContext<LlvmCodegenBackend>,
diag_handler: &DiagCtxt, dcx: &DiagCtxt,
module: ModuleCodegen<ModuleLlvm>, module: ModuleCodegen<ModuleLlvm>,
config: &ModuleConfig, config: &ModuleConfig,
) -> Result<CompiledModule, FatalError> { ) -> Result<CompiledModule, FatalError> {
@ -662,13 +659,8 @@ pub(crate) unsafe fn codegen(
let tm = &*module.module_llvm.tm; let tm = &*module.module_llvm.tm;
let module_name = module.name.clone(); let module_name = module.name.clone();
let module_name = Some(&module_name[..]); let module_name = Some(&module_name[..]);
let _handlers = DiagnosticHandlers::new( let _handlers =
cgcx, DiagnosticHandlers::new(cgcx, dcx, llcx, &module, CodegenDiagnosticsStage::Codegen);
diag_handler,
llcx,
&module,
CodegenDiagnosticsStage::Codegen,
);
if cgcx.msvc_imps_needed { if cgcx.msvc_imps_needed {
create_msvc_imps(cgcx, llcx, llmod); create_msvc_imps(cgcx, llcx, llmod);
@ -726,7 +718,7 @@ pub(crate) unsafe fn codegen(
.prof .prof
.generic_activity_with_arg("LLVM_module_codegen_emit_bitcode", &*module.name); .generic_activity_with_arg("LLVM_module_codegen_emit_bitcode", &*module.name);
if let Err(err) = fs::write(&bc_out, data) { if let Err(err) = fs::write(&bc_out, data) {
diag_handler.emit_err(WriteBytecode { path: &bc_out, err }); dcx.emit_err(WriteBytecode { path: &bc_out, err });
} }
} }
@ -776,9 +768,7 @@ pub(crate) unsafe fn codegen(
record_artifact_size(&cgcx.prof, "llvm_ir", &out); record_artifact_size(&cgcx.prof, "llvm_ir", &out);
} }
result result.into_result().map_err(|()| llvm_err(dcx, LlvmError::WriteIr { path: &out }))?;
.into_result()
.map_err(|()| llvm_err(diag_handler, LlvmError::WriteIr { path: &out }))?;
} }
if config.emit_asm { if config.emit_asm {
@ -797,7 +787,7 @@ pub(crate) unsafe fn codegen(
}; };
with_codegen(tm, llmod, |cpm| { with_codegen(tm, llmod, |cpm| {
write_output_file( write_output_file(
diag_handler, dcx,
tm, tm,
cpm, cpm,
llmod, llmod,
@ -832,7 +822,7 @@ pub(crate) unsafe fn codegen(
with_codegen(tm, llmod, |cpm| { with_codegen(tm, llmod, |cpm| {
write_output_file( write_output_file(
diag_handler, dcx,
tm, tm,
cpm, cpm,
llmod, llmod,
@ -847,12 +837,12 @@ pub(crate) unsafe fn codegen(
EmitObj::Bitcode => { EmitObj::Bitcode => {
debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out); debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
if let Err(err) = link_or_copy(&bc_out, &obj_out) { if let Err(err) = link_or_copy(&bc_out, &obj_out) {
diag_handler.emit_err(CopyBitcode { err }); dcx.emit_err(CopyBitcode { err });
} }
if !config.emit_bc { if !config.emit_bc {
debug!("removing_bitcode {:?}", bc_out); debug!("removing_bitcode {:?}", bc_out);
ensure_removed(diag_handler, &bc_out); ensure_removed(dcx, &bc_out);
} }
} }

View file

@ -102,13 +102,12 @@ pub(crate) struct DynamicLinkingWithLTO;
pub(crate) struct ParseTargetMachineConfig<'a>(pub LlvmError<'a>); pub(crate) struct ParseTargetMachineConfig<'a>(pub LlvmError<'a>);
impl IntoDiagnostic<'_, FatalError> for ParseTargetMachineConfig<'_> { impl IntoDiagnostic<'_, FatalError> for ParseTargetMachineConfig<'_> {
fn into_diagnostic(self, handler: &'_ DiagCtxt) -> DiagnosticBuilder<'_, FatalError> { fn into_diagnostic(self, dcx: &'_ DiagCtxt) -> DiagnosticBuilder<'_, FatalError> {
let diag: DiagnosticBuilder<'_, FatalError> = self.0.into_diagnostic(handler); let diag: DiagnosticBuilder<'_, FatalError> = self.0.into_diagnostic(dcx);
let (message, _) = diag.styled_message().first().expect("`LlvmError` with no message"); let (message, _) = diag.styled_message().first().expect("`LlvmError` with no message");
let message = handler.eagerly_translate_to_string(message.clone(), diag.args()); let message = dcx.eagerly_translate_to_string(message.clone(), diag.args());
let mut diag = let mut diag = dcx.struct_almost_fatal(fluent::codegen_llvm_parse_target_machine_config);
handler.struct_almost_fatal(fluent::codegen_llvm_parse_target_machine_config);
diag.set_arg("error", message); diag.set_arg("error", message);
diag diag
} }
@ -125,8 +124,8 @@ pub(crate) struct TargetFeatureDisableOrEnable<'a> {
pub(crate) struct MissingFeatures; pub(crate) struct MissingFeatures;
impl IntoDiagnostic<'_, ErrorGuaranteed> for TargetFeatureDisableOrEnable<'_> { impl IntoDiagnostic<'_, ErrorGuaranteed> for TargetFeatureDisableOrEnable<'_> {
fn into_diagnostic(self, handler: &'_ DiagCtxt) -> DiagnosticBuilder<'_, ErrorGuaranteed> { fn into_diagnostic(self, dcx: &'_ DiagCtxt) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
let mut diag = handler.struct_err(fluent::codegen_llvm_target_feature_disable_or_enable); let mut diag = dcx.struct_err(fluent::codegen_llvm_target_feature_disable_or_enable);
if let Some(span) = self.span { if let Some(span) = self.span {
diag.set_span(span); diag.set_span(span);
}; };
@ -185,7 +184,7 @@ pub enum LlvmError<'a> {
pub(crate) struct WithLlvmError<'a>(pub LlvmError<'a>, pub String); pub(crate) struct WithLlvmError<'a>(pub LlvmError<'a>, pub String);
impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for WithLlvmError<'_> { impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for WithLlvmError<'_> {
fn into_diagnostic(self, handler: &'_ DiagCtxt) -> DiagnosticBuilder<'_, G> { fn into_diagnostic(self, dcx: &'_ DiagCtxt) -> DiagnosticBuilder<'_, G> {
use LlvmError::*; use LlvmError::*;
let msg_with_llvm_err = match &self.0 { let msg_with_llvm_err = match &self.0 {
WriteOutput { .. } => fluent::codegen_llvm_write_output_with_llvm_err, WriteOutput { .. } => fluent::codegen_llvm_write_output_with_llvm_err,
@ -202,7 +201,7 @@ impl<G: EmissionGuarantee> IntoDiagnostic<'_, G> for WithLlvmError<'_> {
PrepareThinLtoModule => fluent::codegen_llvm_prepare_thin_lto_module_with_llvm_err, PrepareThinLtoModule => fluent::codegen_llvm_prepare_thin_lto_module_with_llvm_err,
ParseBitcode => fluent::codegen_llvm_parse_bitcode_with_llvm_err, ParseBitcode => fluent::codegen_llvm_parse_bitcode_with_llvm_err,
}; };
let mut diag = self.0.into_diagnostic(handler); let mut diag = self.0.into_diagnostic(dcx);
diag.set_primary_message(msg_with_llvm_err); diag.set_primary_message(msg_with_llvm_err);
diag.set_arg("llvm_err", self.1); diag.set_arg("llvm_err", self.1);
diag diag

View file

@ -200,10 +200,10 @@ impl WriteBackendMethods for LlvmCodegenBackend {
} }
fn run_link( fn run_link(
cgcx: &CodegenContext<Self>, cgcx: &CodegenContext<Self>,
diag_handler: &DiagCtxt, dcx: &DiagCtxt,
modules: Vec<ModuleCodegen<Self::Module>>, modules: Vec<ModuleCodegen<Self::Module>>,
) -> Result<ModuleCodegen<Self::Module>, FatalError> { ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
back::write::link(cgcx, diag_handler, modules) back::write::link(cgcx, dcx, modules)
} }
fn run_fat_lto( fn run_fat_lto(
cgcx: &CodegenContext<Self>, cgcx: &CodegenContext<Self>,
@ -221,11 +221,11 @@ impl WriteBackendMethods for LlvmCodegenBackend {
} }
unsafe fn optimize( unsafe fn optimize(
cgcx: &CodegenContext<Self>, cgcx: &CodegenContext<Self>,
diag_handler: &DiagCtxt, dcx: &DiagCtxt,
module: &ModuleCodegen<Self::Module>, module: &ModuleCodegen<Self::Module>,
config: &ModuleConfig, config: &ModuleConfig,
) -> Result<(), FatalError> { ) -> Result<(), FatalError> {
back::write::optimize(cgcx, diag_handler, module, config) back::write::optimize(cgcx, dcx, module, config)
} }
fn optimize_fat( fn optimize_fat(
cgcx: &CodegenContext<Self>, cgcx: &CodegenContext<Self>,
@ -242,11 +242,11 @@ impl WriteBackendMethods for LlvmCodegenBackend {
} }
unsafe fn codegen( unsafe fn codegen(
cgcx: &CodegenContext<Self>, cgcx: &CodegenContext<Self>,
diag_handler: &DiagCtxt, dcx: &DiagCtxt,
module: ModuleCodegen<Self::Module>, module: ModuleCodegen<Self::Module>,
config: &ModuleConfig, config: &ModuleConfig,
) -> Result<CompiledModule, FatalError> { ) -> Result<CompiledModule, FatalError> {
back::write::codegen(cgcx, diag_handler, module, config) back::write::codegen(cgcx, dcx, module, config)
} }
fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) { fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
back::lto::prepare_thin(module) back::lto::prepare_thin(module)
@ -447,16 +447,16 @@ impl ModuleLlvm {
cgcx: &CodegenContext<LlvmCodegenBackend>, cgcx: &CodegenContext<LlvmCodegenBackend>,
name: &CStr, name: &CStr,
buffer: &[u8], buffer: &[u8],
handler: &DiagCtxt, dcx: &DiagCtxt,
) -> Result<Self, FatalError> { ) -> Result<Self, FatalError> {
unsafe { unsafe {
let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names); let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?; let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx)?;
let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap()); let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
let tm = match (cgcx.tm_factory)(tm_factory_config) { let tm = match (cgcx.tm_factory)(tm_factory_config) {
Ok(m) => m, Ok(m) => m,
Err(e) => { Err(e) => {
return Err(handler.emit_almost_fatal(ParseTargetMachineConfig(e))); return Err(dcx.emit_almost_fatal(ParseTargetMachineConfig(e)));
} }
}; };

View file

@ -52,10 +52,10 @@ use std::path::{Path, PathBuf};
use std::process::{ExitStatus, Output, Stdio}; use std::process::{ExitStatus, Output, Stdio};
use std::{env, fmt, fs, io, mem, str}; use std::{env, fmt, fs, io, mem, str};
pub fn ensure_removed(diag_handler: &DiagCtxt, path: &Path) { pub fn ensure_removed(dcx: &DiagCtxt, path: &Path) {
if let Err(e) = fs::remove_file(path) { if let Err(e) = fs::remove_file(path) {
if e.kind() != io::ErrorKind::NotFound { if e.kind() != io::ErrorKind::NotFound {
diag_handler.err(format!("failed to remove {}: {}", path.display(), e)); dcx.err(format!("failed to remove {}: {}", path.display(), e));
} }
} }
} }

View file

@ -210,192 +210,191 @@ pub enum LinkRlibError {
pub struct ThorinErrorWrapper(pub thorin::Error); pub struct ThorinErrorWrapper(pub thorin::Error);
impl IntoDiagnostic<'_> for ThorinErrorWrapper { impl IntoDiagnostic<'_> for ThorinErrorWrapper {
fn into_diagnostic(self, handler: &DiagCtxt) -> DiagnosticBuilder<'_, ErrorGuaranteed> { fn into_diagnostic(self, dcx: &DiagCtxt) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
let mut diag; let mut diag;
match self.0 { match self.0 {
thorin::Error::ReadInput(_) => { thorin::Error::ReadInput(_) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_read_input_failure); diag = dcx.struct_err(fluent::codegen_ssa_thorin_read_input_failure);
diag diag
} }
thorin::Error::ParseFileKind(_) => { thorin::Error::ParseFileKind(_) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_parse_input_file_kind); diag = dcx.struct_err(fluent::codegen_ssa_thorin_parse_input_file_kind);
diag diag
} }
thorin::Error::ParseObjectFile(_) => { thorin::Error::ParseObjectFile(_) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_parse_input_object_file); diag = dcx.struct_err(fluent::codegen_ssa_thorin_parse_input_object_file);
diag diag
} }
thorin::Error::ParseArchiveFile(_) => { thorin::Error::ParseArchiveFile(_) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_parse_input_archive_file); diag = dcx.struct_err(fluent::codegen_ssa_thorin_parse_input_archive_file);
diag diag
} }
thorin::Error::ParseArchiveMember(_) => { thorin::Error::ParseArchiveMember(_) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_parse_archive_member); diag = dcx.struct_err(fluent::codegen_ssa_thorin_parse_archive_member);
diag diag
} }
thorin::Error::InvalidInputKind => { thorin::Error::InvalidInputKind => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_invalid_input_kind); diag = dcx.struct_err(fluent::codegen_ssa_thorin_invalid_input_kind);
diag diag
} }
thorin::Error::DecompressData(_) => { thorin::Error::DecompressData(_) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_decompress_data); diag = dcx.struct_err(fluent::codegen_ssa_thorin_decompress_data);
diag diag
} }
thorin::Error::NamelessSection(_, offset) => { thorin::Error::NamelessSection(_, offset) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_section_without_name); diag = dcx.struct_err(fluent::codegen_ssa_thorin_section_without_name);
diag.set_arg("offset", format!("0x{offset:08x}")); diag.set_arg("offset", format!("0x{offset:08x}"));
diag diag
} }
thorin::Error::RelocationWithInvalidSymbol(section, offset) => { thorin::Error::RelocationWithInvalidSymbol(section, offset) => {
diag = diag = dcx.struct_err(fluent::codegen_ssa_thorin_relocation_with_invalid_symbol);
handler.struct_err(fluent::codegen_ssa_thorin_relocation_with_invalid_symbol);
diag.set_arg("section", section); diag.set_arg("section", section);
diag.set_arg("offset", format!("0x{offset:08x}")); diag.set_arg("offset", format!("0x{offset:08x}"));
diag diag
} }
thorin::Error::MultipleRelocations(section, offset) => { thorin::Error::MultipleRelocations(section, offset) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_multiple_relocations); diag = dcx.struct_err(fluent::codegen_ssa_thorin_multiple_relocations);
diag.set_arg("section", section); diag.set_arg("section", section);
diag.set_arg("offset", format!("0x{offset:08x}")); diag.set_arg("offset", format!("0x{offset:08x}"));
diag diag
} }
thorin::Error::UnsupportedRelocation(section, offset) => { thorin::Error::UnsupportedRelocation(section, offset) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_unsupported_relocation); diag = dcx.struct_err(fluent::codegen_ssa_thorin_unsupported_relocation);
diag.set_arg("section", section); diag.set_arg("section", section);
diag.set_arg("offset", format!("0x{offset:08x}")); diag.set_arg("offset", format!("0x{offset:08x}"));
diag diag
} }
thorin::Error::MissingDwoName(id) => { thorin::Error::MissingDwoName(id) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_missing_dwo_name); diag = dcx.struct_err(fluent::codegen_ssa_thorin_missing_dwo_name);
diag.set_arg("id", format!("0x{id:08x}")); diag.set_arg("id", format!("0x{id:08x}"));
diag diag
} }
thorin::Error::NoCompilationUnits => { thorin::Error::NoCompilationUnits => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_no_compilation_units); diag = dcx.struct_err(fluent::codegen_ssa_thorin_no_compilation_units);
diag diag
} }
thorin::Error::NoDie => { thorin::Error::NoDie => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_no_die); diag = dcx.struct_err(fluent::codegen_ssa_thorin_no_die);
diag diag
} }
thorin::Error::TopLevelDieNotUnit => { thorin::Error::TopLevelDieNotUnit => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_top_level_die_not_unit); diag = dcx.struct_err(fluent::codegen_ssa_thorin_top_level_die_not_unit);
diag diag
} }
thorin::Error::MissingRequiredSection(section) => { thorin::Error::MissingRequiredSection(section) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_missing_required_section); diag = dcx.struct_err(fluent::codegen_ssa_thorin_missing_required_section);
diag.set_arg("section", section); diag.set_arg("section", section);
diag diag
} }
thorin::Error::ParseUnitAbbreviations(_) => { thorin::Error::ParseUnitAbbreviations(_) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_parse_unit_abbreviations); diag = dcx.struct_err(fluent::codegen_ssa_thorin_parse_unit_abbreviations);
diag diag
} }
thorin::Error::ParseUnitAttribute(_) => { thorin::Error::ParseUnitAttribute(_) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_parse_unit_attribute); diag = dcx.struct_err(fluent::codegen_ssa_thorin_parse_unit_attribute);
diag diag
} }
thorin::Error::ParseUnitHeader(_) => { thorin::Error::ParseUnitHeader(_) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_parse_unit_header); diag = dcx.struct_err(fluent::codegen_ssa_thorin_parse_unit_header);
diag diag
} }
thorin::Error::ParseUnit(_) => { thorin::Error::ParseUnit(_) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_parse_unit); diag = dcx.struct_err(fluent::codegen_ssa_thorin_parse_unit);
diag diag
} }
thorin::Error::IncompatibleIndexVersion(section, format, actual) => { thorin::Error::IncompatibleIndexVersion(section, format, actual) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_incompatible_index_version); diag = dcx.struct_err(fluent::codegen_ssa_thorin_incompatible_index_version);
diag.set_arg("section", section); diag.set_arg("section", section);
diag.set_arg("actual", actual); diag.set_arg("actual", actual);
diag.set_arg("format", format); diag.set_arg("format", format);
diag diag
} }
thorin::Error::OffsetAtIndex(_, index) => { thorin::Error::OffsetAtIndex(_, index) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_offset_at_index); diag = dcx.struct_err(fluent::codegen_ssa_thorin_offset_at_index);
diag.set_arg("index", index); diag.set_arg("index", index);
diag diag
} }
thorin::Error::StrAtOffset(_, offset) => { thorin::Error::StrAtOffset(_, offset) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_str_at_offset); diag = dcx.struct_err(fluent::codegen_ssa_thorin_str_at_offset);
diag.set_arg("offset", format!("0x{offset:08x}")); diag.set_arg("offset", format!("0x{offset:08x}"));
diag diag
} }
thorin::Error::ParseIndex(_, section) => { thorin::Error::ParseIndex(_, section) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_parse_index); diag = dcx.struct_err(fluent::codegen_ssa_thorin_parse_index);
diag.set_arg("section", section); diag.set_arg("section", section);
diag diag
} }
thorin::Error::UnitNotInIndex(unit) => { thorin::Error::UnitNotInIndex(unit) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_unit_not_in_index); diag = dcx.struct_err(fluent::codegen_ssa_thorin_unit_not_in_index);
diag.set_arg("unit", format!("0x{unit:08x}")); diag.set_arg("unit", format!("0x{unit:08x}"));
diag diag
} }
thorin::Error::RowNotInIndex(_, row) => { thorin::Error::RowNotInIndex(_, row) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_row_not_in_index); diag = dcx.struct_err(fluent::codegen_ssa_thorin_row_not_in_index);
diag.set_arg("row", row); diag.set_arg("row", row);
diag diag
} }
thorin::Error::SectionNotInRow => { thorin::Error::SectionNotInRow => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_section_not_in_row); diag = dcx.struct_err(fluent::codegen_ssa_thorin_section_not_in_row);
diag diag
} }
thorin::Error::EmptyUnit(unit) => { thorin::Error::EmptyUnit(unit) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_empty_unit); diag = dcx.struct_err(fluent::codegen_ssa_thorin_empty_unit);
diag.set_arg("unit", format!("0x{unit:08x}")); diag.set_arg("unit", format!("0x{unit:08x}"));
diag diag
} }
thorin::Error::MultipleDebugInfoSection => { thorin::Error::MultipleDebugInfoSection => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_multiple_debug_info_section); diag = dcx.struct_err(fluent::codegen_ssa_thorin_multiple_debug_info_section);
diag diag
} }
thorin::Error::MultipleDebugTypesSection => { thorin::Error::MultipleDebugTypesSection => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_multiple_debug_types_section); diag = dcx.struct_err(fluent::codegen_ssa_thorin_multiple_debug_types_section);
diag diag
} }
thorin::Error::NotSplitUnit => { thorin::Error::NotSplitUnit => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_not_split_unit); diag = dcx.struct_err(fluent::codegen_ssa_thorin_not_split_unit);
diag diag
} }
thorin::Error::DuplicateUnit(unit) => { thorin::Error::DuplicateUnit(unit) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_duplicate_unit); diag = dcx.struct_err(fluent::codegen_ssa_thorin_duplicate_unit);
diag.set_arg("unit", format!("0x{unit:08x}")); diag.set_arg("unit", format!("0x{unit:08x}"));
diag diag
} }
thorin::Error::MissingReferencedUnit(unit) => { thorin::Error::MissingReferencedUnit(unit) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_missing_referenced_unit); diag = dcx.struct_err(fluent::codegen_ssa_thorin_missing_referenced_unit);
diag.set_arg("unit", format!("0x{unit:08x}")); diag.set_arg("unit", format!("0x{unit:08x}"));
diag diag
} }
thorin::Error::NoOutputObjectCreated => { thorin::Error::NoOutputObjectCreated => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_not_output_object_created); diag = dcx.struct_err(fluent::codegen_ssa_thorin_not_output_object_created);
diag diag
} }
thorin::Error::MixedInputEncodings => { thorin::Error::MixedInputEncodings => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_mixed_input_encodings); diag = dcx.struct_err(fluent::codegen_ssa_thorin_mixed_input_encodings);
diag diag
} }
thorin::Error::Io(e) => { thorin::Error::Io(e) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_io); diag = dcx.struct_err(fluent::codegen_ssa_thorin_io);
diag.set_arg("error", format!("{e}")); diag.set_arg("error", format!("{e}"));
diag diag
} }
thorin::Error::ObjectRead(e) => { thorin::Error::ObjectRead(e) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_object_read); diag = dcx.struct_err(fluent::codegen_ssa_thorin_object_read);
diag.set_arg("error", format!("{e}")); diag.set_arg("error", format!("{e}"));
diag diag
} }
thorin::Error::ObjectWrite(e) => { thorin::Error::ObjectWrite(e) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_object_write); diag = dcx.struct_err(fluent::codegen_ssa_thorin_object_write);
diag.set_arg("error", format!("{e}")); diag.set_arg("error", format!("{e}"));
diag diag
} }
thorin::Error::GimliRead(e) => { thorin::Error::GimliRead(e) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_gimli_read); diag = dcx.struct_err(fluent::codegen_ssa_thorin_gimli_read);
diag.set_arg("error", format!("{e}")); diag.set_arg("error", format!("{e}"));
diag diag
} }
thorin::Error::GimliWrite(e) => { thorin::Error::GimliWrite(e) => {
diag = handler.struct_err(fluent::codegen_ssa_thorin_gimli_write); diag = dcx.struct_err(fluent::codegen_ssa_thorin_gimli_write);
diag.set_arg("error", format!("{e}")); diag.set_arg("error", format!("{e}"));
diag diag
} }
@ -412,8 +411,8 @@ pub struct LinkingFailed<'a> {
} }
impl IntoDiagnostic<'_> for LinkingFailed<'_> { impl IntoDiagnostic<'_> for LinkingFailed<'_> {
fn into_diagnostic(self, handler: &DiagCtxt) -> DiagnosticBuilder<'_, ErrorGuaranteed> { fn into_diagnostic(self, dcx: &DiagCtxt) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
let mut diag = handler.struct_err(fluent::codegen_ssa_linking_failed); let mut diag = dcx.struct_err(fluent::codegen_ssa_linking_failed);
diag.set_arg("linker_path", format!("{}", self.linker_path.display())); diag.set_arg("linker_path", format!("{}", self.linker_path.display()));
diag.set_arg("exit_status", format!("{}", self.exit_status)); diag.set_arg("exit_status", format!("{}", self.exit_status));

View file

@ -16,7 +16,7 @@ pub trait WriteBackendMethods: 'static + Sized + Clone {
/// Merge all modules into main_module and returning it /// Merge all modules into main_module and returning it
fn run_link( fn run_link(
cgcx: &CodegenContext<Self>, cgcx: &CodegenContext<Self>,
diag_handler: &DiagCtxt, dcx: &DiagCtxt,
modules: Vec<ModuleCodegen<Self::Module>>, modules: Vec<ModuleCodegen<Self::Module>>,
) -> Result<ModuleCodegen<Self::Module>, FatalError>; ) -> Result<ModuleCodegen<Self::Module>, FatalError>;
/// Performs fat LTO by merging all modules into a single one and returning it /// Performs fat LTO by merging all modules into a single one and returning it
@ -38,7 +38,7 @@ pub trait WriteBackendMethods: 'static + Sized + Clone {
fn print_statistics(&self); fn print_statistics(&self);
unsafe fn optimize( unsafe fn optimize(
cgcx: &CodegenContext<Self>, cgcx: &CodegenContext<Self>,
diag_handler: &DiagCtxt, dcx: &DiagCtxt,
module: &ModuleCodegen<Self::Module>, module: &ModuleCodegen<Self::Module>,
config: &ModuleConfig, config: &ModuleConfig,
) -> Result<(), FatalError>; ) -> Result<(), FatalError>;
@ -52,7 +52,7 @@ pub trait WriteBackendMethods: 'static + Sized + Clone {
) -> Result<ModuleCodegen<Self::Module>, FatalError>; ) -> Result<ModuleCodegen<Self::Module>, FatalError>;
unsafe fn codegen( unsafe fn codegen(
cgcx: &CodegenContext<Self>, cgcx: &CodegenContext<Self>,
diag_handler: &DiagCtxt, dcx: &DiagCtxt,
module: ModuleCodegen<Self::Module>, module: ModuleCodegen<Self::Module>,
config: &ModuleConfig, config: &ModuleConfig,
) -> Result<CompiledModule, FatalError>; ) -> Result<CompiledModule, FatalError>;

View file

@ -432,11 +432,7 @@ pub struct UndefinedBehavior {
pub trait ReportErrorExt { pub trait ReportErrorExt {
/// Returns the diagnostic message for this error. /// Returns the diagnostic message for this error.
fn diagnostic_message(&self) -> DiagnosticMessage; fn diagnostic_message(&self) -> DiagnosticMessage;
fn add_args<G: EmissionGuarantee>( fn add_args<G: EmissionGuarantee>(self, dcx: &DiagCtxt, builder: &mut DiagnosticBuilder<'_, G>);
self,
handler: &DiagCtxt,
builder: &mut DiagnosticBuilder<'_, G>,
);
fn debug(self) -> String fn debug(self) -> String
where where
@ -454,7 +450,7 @@ pub trait ReportErrorExt {
} }
} }
fn bad_pointer_message(msg: CheckInAllocMsg, handler: &DiagCtxt) -> String { fn bad_pointer_message(msg: CheckInAllocMsg, dcx: &DiagCtxt) -> String {
use crate::fluent_generated::*; use crate::fluent_generated::*;
let msg = match msg { let msg = match msg {
@ -464,7 +460,7 @@ fn bad_pointer_message(msg: CheckInAllocMsg, handler: &DiagCtxt) -> String {
CheckInAllocMsg::InboundsTest => const_eval_in_bounds_test, CheckInAllocMsg::InboundsTest => const_eval_in_bounds_test,
}; };
handler.eagerly_translate_to_string(msg, [].into_iter()) dcx.eagerly_translate_to_string(msg, [].into_iter())
} }
impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> { impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> {
@ -514,7 +510,7 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> {
fn add_args<G: EmissionGuarantee>( fn add_args<G: EmissionGuarantee>(
self, self,
handler: &DiagCtxt, dcx: &DiagCtxt,
builder: &mut DiagnosticBuilder<'_, G>, builder: &mut DiagnosticBuilder<'_, G>,
) { ) {
use UndefinedBehaviorInfo::*; use UndefinedBehaviorInfo::*;
@ -525,7 +521,7 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> {
builder.set_arg(name, value); builder.set_arg(name, value);
}); });
} }
ValidationError(e) => e.add_args(handler, builder), ValidationError(e) => e.add_args(dcx, builder),
Unreachable Unreachable
| DivisionByZero | DivisionByZero
@ -549,7 +545,7 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> {
PointerUseAfterFree(alloc_id, msg) => { PointerUseAfterFree(alloc_id, msg) => {
builder builder
.set_arg("alloc_id", alloc_id) .set_arg("alloc_id", alloc_id)
.set_arg("bad_pointer_message", bad_pointer_message(msg, handler)); .set_arg("bad_pointer_message", bad_pointer_message(msg, dcx));
} }
PointerOutOfBounds { alloc_id, alloc_size, ptr_offset, ptr_size, msg } => { PointerOutOfBounds { alloc_id, alloc_size, ptr_offset, ptr_size, msg } => {
builder builder
@ -557,14 +553,14 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> {
.set_arg("alloc_size", alloc_size.bytes()) .set_arg("alloc_size", alloc_size.bytes())
.set_arg("ptr_offset", ptr_offset) .set_arg("ptr_offset", ptr_offset)
.set_arg("ptr_size", ptr_size.bytes()) .set_arg("ptr_size", ptr_size.bytes())
.set_arg("bad_pointer_message", bad_pointer_message(msg, handler)); .set_arg("bad_pointer_message", bad_pointer_message(msg, dcx));
} }
DanglingIntPointer(ptr, msg) => { DanglingIntPointer(ptr, msg) => {
if ptr != 0 { if ptr != 0 {
builder.set_arg("pointer", format!("{ptr:#x}[noalloc]")); builder.set_arg("pointer", format!("{ptr:#x}[noalloc]"));
} }
builder.set_arg("bad_pointer_message", bad_pointer_message(msg, handler)); builder.set_arg("bad_pointer_message", bad_pointer_message(msg, dcx));
} }
AlignmentCheckFailed(Misalignment { required, has }, msg) => { AlignmentCheckFailed(Misalignment { required, has }, msg) => {
builder.set_arg("required", required.bytes()); builder.set_arg("required", required.bytes());
@ -678,11 +674,7 @@ impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> {
} }
} }
fn add_args<G: EmissionGuarantee>( fn add_args<G: EmissionGuarantee>(self, dcx: &DiagCtxt, err: &mut DiagnosticBuilder<'_, G>) {
self,
handler: &DiagCtxt,
err: &mut DiagnosticBuilder<'_, G>,
) {
use crate::fluent_generated as fluent; use crate::fluent_generated as fluent;
use rustc_middle::mir::interpret::ValidationErrorKind::*; use rustc_middle::mir::interpret::ValidationErrorKind::*;
@ -692,12 +684,12 @@ impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> {
} }
let message = if let Some(path) = self.path { let message = if let Some(path) = self.path {
handler.eagerly_translate_to_string( dcx.eagerly_translate_to_string(
fluent::const_eval_validation_front_matter_invalid_value_with_path, fluent::const_eval_validation_front_matter_invalid_value_with_path,
[("path".into(), DiagnosticArgValue::Str(path.into()))].iter().map(|(a, b)| (a, b)), [("path".into(), DiagnosticArgValue::Str(path.into()))].iter().map(|(a, b)| (a, b)),
) )
} else { } else {
handler.eagerly_translate_to_string( dcx.eagerly_translate_to_string(
fluent::const_eval_validation_front_matter_invalid_value, fluent::const_eval_validation_front_matter_invalid_value,
[].into_iter(), [].into_iter(),
) )
@ -708,7 +700,7 @@ impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> {
fn add_range_arg<G: EmissionGuarantee>( fn add_range_arg<G: EmissionGuarantee>(
r: WrappingRange, r: WrappingRange,
max_hi: u128, max_hi: u128,
handler: &DiagCtxt, dcx: &DiagCtxt,
err: &mut DiagnosticBuilder<'_, G>, err: &mut DiagnosticBuilder<'_, G>,
) { ) {
let WrappingRange { start: lo, end: hi } = r; let WrappingRange { start: lo, end: hi } = r;
@ -732,7 +724,7 @@ impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> {
("hi".into(), DiagnosticArgValue::Str(hi.to_string().into())), ("hi".into(), DiagnosticArgValue::Str(hi.to_string().into())),
]; ];
let args = args.iter().map(|(a, b)| (a, b)); let args = args.iter().map(|(a, b)| (a, b));
let message = handler.eagerly_translate_to_string(msg, args); let message = dcx.eagerly_translate_to_string(msg, args);
err.set_arg("in_range", message); err.set_arg("in_range", message);
} }
@ -754,7 +746,7 @@ impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> {
ExpectedKind::EnumTag => fluent::const_eval_validation_expected_enum_tag, ExpectedKind::EnumTag => fluent::const_eval_validation_expected_enum_tag,
ExpectedKind::Str => fluent::const_eval_validation_expected_str, ExpectedKind::Str => fluent::const_eval_validation_expected_str,
}; };
let msg = handler.eagerly_translate_to_string(msg, [].into_iter()); let msg = dcx.eagerly_translate_to_string(msg, [].into_iter());
err.set_arg("expected", msg); err.set_arg("expected", msg);
} }
InvalidEnumTag { value } InvalidEnumTag { value }
@ -765,11 +757,11 @@ impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> {
err.set_arg("value", value); err.set_arg("value", value);
} }
NullablePtrOutOfRange { range, max_value } | PtrOutOfRange { range, max_value } => { NullablePtrOutOfRange { range, max_value } | PtrOutOfRange { range, max_value } => {
add_range_arg(range, max_value, handler, err) add_range_arg(range, max_value, dcx, err)
} }
OutOfRange { range, max_value, value } => { OutOfRange { range, max_value, value } => {
err.set_arg("value", value); err.set_arg("value", value);
add_range_arg(range, max_value, handler, err); add_range_arg(range, max_value, dcx, err);
} }
UnalignedPtr { required_bytes, found_bytes, .. } => { UnalignedPtr { required_bytes, found_bytes, .. } => {
err.set_arg("required_bytes", required_bytes); err.set_arg("required_bytes", required_bytes);
@ -843,14 +835,14 @@ impl<'tcx> ReportErrorExt for InterpError<'tcx> {
} }
fn add_args<G: EmissionGuarantee>( fn add_args<G: EmissionGuarantee>(
self, self,
handler: &DiagCtxt, dcx: &DiagCtxt,
builder: &mut DiagnosticBuilder<'_, G>, builder: &mut DiagnosticBuilder<'_, G>,
) { ) {
match self { match self {
InterpError::UndefinedBehavior(ub) => ub.add_args(handler, builder), InterpError::UndefinedBehavior(ub) => ub.add_args(dcx, builder),
InterpError::Unsupported(e) => e.add_args(handler, builder), InterpError::Unsupported(e) => e.add_args(dcx, builder),
InterpError::InvalidProgram(e) => e.add_args(handler, builder), InterpError::InvalidProgram(e) => e.add_args(dcx, builder),
InterpError::ResourceExhaustion(e) => e.add_args(handler, builder), InterpError::ResourceExhaustion(e) => e.add_args(dcx, builder),
InterpError::MachineStop(e) => e.add_args(&mut |name, value| { InterpError::MachineStop(e) => e.add_args(&mut |name, value| {
builder.set_arg(name, value); builder.set_arg(name, value);
}), }),
@ -875,7 +867,7 @@ impl<'tcx> ReportErrorExt for InvalidProgramInfo<'tcx> {
} }
fn add_args<G: EmissionGuarantee>( fn add_args<G: EmissionGuarantee>(
self, self,
handler: &DiagCtxt, dcx: &DiagCtxt,
builder: &mut DiagnosticBuilder<'_, G>, builder: &mut DiagnosticBuilder<'_, G>,
) { ) {
match self { match self {
@ -883,7 +875,7 @@ impl<'tcx> ReportErrorExt for InvalidProgramInfo<'tcx> {
| InvalidProgramInfo::AlreadyReported(_) | InvalidProgramInfo::AlreadyReported(_)
| InvalidProgramInfo::ConstPropNonsense => {} | InvalidProgramInfo::ConstPropNonsense => {}
InvalidProgramInfo::Layout(e) => { InvalidProgramInfo::Layout(e) => {
let diag: DiagnosticBuilder<'_, ()> = e.into_diagnostic().into_diagnostic(handler); let diag: DiagnosticBuilder<'_, ()> = e.into_diagnostic().into_diagnostic(dcx);
for (name, val) in diag.args() { for (name, val) in diag.args() {
builder.set_arg(name.clone(), val.clone()); builder.set_arg(name.clone(), val.clone());
} }

View file

@ -886,13 +886,13 @@ impl Diagnostic {
/// interpolated variables). /// interpolated variables).
pub fn eager_subdiagnostic( pub fn eager_subdiagnostic(
&mut self, &mut self,
handler: &crate::DiagCtxt, dcx: &crate::DiagCtxt,
subdiagnostic: impl AddToDiagnostic, subdiagnostic: impl AddToDiagnostic,
) -> &mut Self { ) -> &mut Self {
subdiagnostic.add_to_diagnostic_with(self, |diag, msg| { subdiagnostic.add_to_diagnostic_with(self, |diag, msg| {
let args = diag.args(); let args = diag.args();
let msg = diag.subdiagnostic_message_to_diagnostic_message(msg); let msg = diag.subdiagnostic_message_to_diagnostic_message(msg);
handler.eagerly_translate(msg, args) dcx.eagerly_translate(msg, args)
}); });
self self
} }

View file

@ -21,7 +21,7 @@ use std::thread::panicking;
pub trait IntoDiagnostic<'a, G: EmissionGuarantee = ErrorGuaranteed> { pub trait IntoDiagnostic<'a, G: EmissionGuarantee = ErrorGuaranteed> {
/// Write out as a diagnostic out of `DiagCtxt`. /// Write out as a diagnostic out of `DiagCtxt`.
#[must_use] #[must_use]
fn into_diagnostic(self, handler: &'a DiagCtxt) -> DiagnosticBuilder<'a, G>; fn into_diagnostic(self, dcx: &'a DiagCtxt) -> DiagnosticBuilder<'a, G>;
} }
impl<'a, T, G> IntoDiagnostic<'a, G> for Spanned<T> impl<'a, T, G> IntoDiagnostic<'a, G> for Spanned<T>
@ -29,8 +29,8 @@ where
T: IntoDiagnostic<'a, G>, T: IntoDiagnostic<'a, G>,
G: EmissionGuarantee, G: EmissionGuarantee,
{ {
fn into_diagnostic(self, handler: &'a DiagCtxt) -> DiagnosticBuilder<'a, G> { fn into_diagnostic(self, dcx: &'a DiagCtxt) -> DiagnosticBuilder<'a, G> {
let mut diag = self.node.into_diagnostic(handler); let mut diag = self.node.into_diagnostic(dcx);
diag.set_span(self.span); diag.set_span(self.span);
diag diag
} }
@ -110,7 +110,7 @@ pub trait EmissionGuarantee: Sized {
/// Creates a new `DiagnosticBuilder` that will return this type of guarantee. /// Creates a new `DiagnosticBuilder` that will return this type of guarantee.
#[track_caller] #[track_caller]
fn make_diagnostic_builder( fn make_diagnostic_builder(
handler: &DiagCtxt, dcx: &DiagCtxt,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, Self>; ) -> DiagnosticBuilder<'_, Self>;
} }
@ -166,10 +166,10 @@ impl EmissionGuarantee for ErrorGuaranteed {
#[track_caller] #[track_caller]
fn make_diagnostic_builder( fn make_diagnostic_builder(
handler: &DiagCtxt, dcx: &DiagCtxt,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, Self> { ) -> DiagnosticBuilder<'_, Self> {
DiagnosticBuilder::new(handler, Level::Error { lint: false }, msg) DiagnosticBuilder::new(dcx, Level::Error { lint: false }, msg)
} }
} }
@ -189,10 +189,10 @@ impl EmissionGuarantee for () {
} }
fn make_diagnostic_builder( fn make_diagnostic_builder(
handler: &DiagCtxt, dcx: &DiagCtxt,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, Self> { ) -> DiagnosticBuilder<'_, Self> {
DiagnosticBuilder::new(handler, Level::Warning(None), msg) DiagnosticBuilder::new(dcx, Level::Warning(None), msg)
} }
} }
@ -217,10 +217,10 @@ impl EmissionGuarantee for Noted {
} }
fn make_diagnostic_builder( fn make_diagnostic_builder(
handler: &DiagCtxt, dcx: &DiagCtxt,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, Self> { ) -> DiagnosticBuilder<'_, Self> {
DiagnosticBuilder::new(handler, Level::Note, msg) DiagnosticBuilder::new(dcx, Level::Note, msg)
} }
} }
@ -246,10 +246,10 @@ impl EmissionGuarantee for Bug {
} }
fn make_diagnostic_builder( fn make_diagnostic_builder(
handler: &DiagCtxt, dcx: &DiagCtxt,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, Self> { ) -> DiagnosticBuilder<'_, Self> {
DiagnosticBuilder::new(handler, Level::Bug, msg) DiagnosticBuilder::new(dcx, Level::Bug, msg)
} }
} }
@ -270,10 +270,10 @@ impl EmissionGuarantee for ! {
} }
fn make_diagnostic_builder( fn make_diagnostic_builder(
handler: &DiagCtxt, dcx: &DiagCtxt,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, Self> { ) -> DiagnosticBuilder<'_, Self> {
DiagnosticBuilder::new(handler, Level::Fatal, msg) DiagnosticBuilder::new(dcx, Level::Fatal, msg)
} }
} }
@ -294,10 +294,10 @@ impl EmissionGuarantee for rustc_span::fatal_error::FatalError {
} }
fn make_diagnostic_builder( fn make_diagnostic_builder(
handler: &DiagCtxt, dcx: &DiagCtxt,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, Self> { ) -> DiagnosticBuilder<'_, Self> {
DiagnosticBuilder::new(handler, Level::Fatal, msg) DiagnosticBuilder::new(dcx, Level::Fatal, msg)
} }
} }
@ -343,22 +343,22 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
/// `struct_*` methods on [`DiagCtxt`]. /// `struct_*` methods on [`DiagCtxt`].
#[track_caller] #[track_caller]
pub(crate) fn new<M: Into<DiagnosticMessage>>( pub(crate) fn new<M: Into<DiagnosticMessage>>(
handler: &'a DiagCtxt, dcx: &'a DiagCtxt,
level: Level, level: Level,
message: M, message: M,
) -> Self { ) -> Self {
let diagnostic = Diagnostic::new(level, message); let diagnostic = Diagnostic::new(level, message);
Self::new_diagnostic(handler, diagnostic) Self::new_diagnostic(dcx, diagnostic)
} }
/// Creates a new `DiagnosticBuilder` with an already constructed /// Creates a new `DiagnosticBuilder` with an already constructed
/// diagnostic. /// diagnostic.
#[track_caller] #[track_caller]
pub(crate) fn new_diagnostic(handler: &'a DiagCtxt, diagnostic: Diagnostic) -> Self { pub(crate) fn new_diagnostic(dcx: &'a DiagCtxt, diagnostic: Diagnostic) -> Self {
debug!("Created new diagnostic"); debug!("Created new diagnostic");
Self { Self {
inner: DiagnosticBuilderInner { inner: DiagnosticBuilderInner {
state: DiagnosticBuilderState::Emittable(handler), state: DiagnosticBuilderState::Emittable(dcx),
diagnostic: Box::new(diagnostic), diagnostic: Box::new(diagnostic),
}, },
_marker: PhantomData, _marker: PhantomData,

View file

@ -246,18 +246,18 @@ impl<Id> IntoDiagnosticArg for hir::def::Res<Id> {
} }
impl IntoDiagnostic<'_, !> for TargetDataLayoutErrors<'_> { impl IntoDiagnostic<'_, !> for TargetDataLayoutErrors<'_> {
fn into_diagnostic(self, handler: &DiagCtxt) -> DiagnosticBuilder<'_, !> { fn into_diagnostic(self, dcx: &DiagCtxt) -> DiagnosticBuilder<'_, !> {
let mut diag; let mut diag;
match self { match self {
TargetDataLayoutErrors::InvalidAddressSpace { addr_space, err, cause } => { TargetDataLayoutErrors::InvalidAddressSpace { addr_space, err, cause } => {
diag = handler.struct_fatal(fluent::errors_target_invalid_address_space); diag = dcx.struct_fatal(fluent::errors_target_invalid_address_space);
diag.set_arg("addr_space", addr_space); diag.set_arg("addr_space", addr_space);
diag.set_arg("cause", cause); diag.set_arg("cause", cause);
diag.set_arg("err", err); diag.set_arg("err", err);
diag diag
} }
TargetDataLayoutErrors::InvalidBits { kind, bit, cause, err } => { TargetDataLayoutErrors::InvalidBits { kind, bit, cause, err } => {
diag = handler.struct_fatal(fluent::errors_target_invalid_bits); diag = dcx.struct_fatal(fluent::errors_target_invalid_bits);
diag.set_arg("kind", kind); diag.set_arg("kind", kind);
diag.set_arg("bit", bit); diag.set_arg("bit", bit);
diag.set_arg("cause", cause); diag.set_arg("cause", cause);
@ -265,31 +265,31 @@ impl IntoDiagnostic<'_, !> for TargetDataLayoutErrors<'_> {
diag diag
} }
TargetDataLayoutErrors::MissingAlignment { cause } => { TargetDataLayoutErrors::MissingAlignment { cause } => {
diag = handler.struct_fatal(fluent::errors_target_missing_alignment); diag = dcx.struct_fatal(fluent::errors_target_missing_alignment);
diag.set_arg("cause", cause); diag.set_arg("cause", cause);
diag diag
} }
TargetDataLayoutErrors::InvalidAlignment { cause, err } => { TargetDataLayoutErrors::InvalidAlignment { cause, err } => {
diag = handler.struct_fatal(fluent::errors_target_invalid_alignment); diag = dcx.struct_fatal(fluent::errors_target_invalid_alignment);
diag.set_arg("cause", cause); diag.set_arg("cause", cause);
diag.set_arg("err_kind", err.diag_ident()); diag.set_arg("err_kind", err.diag_ident());
diag.set_arg("align", err.align()); diag.set_arg("align", err.align());
diag diag
} }
TargetDataLayoutErrors::InconsistentTargetArchitecture { dl, target } => { TargetDataLayoutErrors::InconsistentTargetArchitecture { dl, target } => {
diag = handler.struct_fatal(fluent::errors_target_inconsistent_architecture); diag = dcx.struct_fatal(fluent::errors_target_inconsistent_architecture);
diag.set_arg("dl", dl); diag.set_arg("dl", dl);
diag.set_arg("target", target); diag.set_arg("target", target);
diag diag
} }
TargetDataLayoutErrors::InconsistentTargetPointerWidth { pointer_size, target } => { TargetDataLayoutErrors::InconsistentTargetPointerWidth { pointer_size, target } => {
diag = handler.struct_fatal(fluent::errors_target_inconsistent_pointer_width); diag = dcx.struct_fatal(fluent::errors_target_inconsistent_pointer_width);
diag.set_arg("pointer_size", pointer_size); diag.set_arg("pointer_size", pointer_size);
diag.set_arg("target", target); diag.set_arg("target", target);
diag diag
} }
TargetDataLayoutErrors::InvalidBitsSize { err } => { TargetDataLayoutErrors::InvalidBitsSize { err } => {
diag = handler.struct_fatal(fluent::errors_target_invalid_bits_size); diag = dcx.struct_fatal(fluent::errors_target_invalid_bits_size);
diag.set_arg("err", err); diag.set_arg("err", err);
diag diag
} }

View file

@ -1350,7 +1350,7 @@ pub fn get_exprs_from_tts(cx: &mut ExtCtxt<'_>, tts: TokenStream) -> Option<Vec<
} }
pub fn parse_macro_name_and_helper_attrs( pub fn parse_macro_name_and_helper_attrs(
diag: &rustc_errors::DiagCtxt, dcx: &rustc_errors::DiagCtxt,
attr: &Attribute, attr: &Attribute,
macro_type: &str, macro_type: &str,
) -> Option<(Symbol, Vec<Symbol>)> { ) -> Option<(Symbol, Vec<Symbol>)> {
@ -1359,23 +1359,23 @@ pub fn parse_macro_name_and_helper_attrs(
// `#[proc_macro_derive(Foo, attributes(A, ..))]` // `#[proc_macro_derive(Foo, attributes(A, ..))]`
let list = attr.meta_item_list()?; let list = attr.meta_item_list()?;
if list.len() != 1 && list.len() != 2 { if list.len() != 1 && list.len() != 2 {
diag.emit_err(errors::AttrNoArguments { span: attr.span }); dcx.emit_err(errors::AttrNoArguments { span: attr.span });
return None; return None;
} }
let Some(trait_attr) = list[0].meta_item() else { let Some(trait_attr) = list[0].meta_item() else {
diag.emit_err(errors::NotAMetaItem { span: list[0].span() }); dcx.emit_err(errors::NotAMetaItem { span: list[0].span() });
return None; return None;
}; };
let trait_ident = match trait_attr.ident() { let trait_ident = match trait_attr.ident() {
Some(trait_ident) if trait_attr.is_word() => trait_ident, Some(trait_ident) if trait_attr.is_word() => trait_ident,
_ => { _ => {
diag.emit_err(errors::OnlyOneWord { span: trait_attr.span }); dcx.emit_err(errors::OnlyOneWord { span: trait_attr.span });
return None; return None;
} }
}; };
if !trait_ident.name.can_be_raw() { if !trait_ident.name.can_be_raw() {
diag.emit_err(errors::CannotBeNameOfMacro { dcx.emit_err(errors::CannotBeNameOfMacro {
span: trait_attr.span, span: trait_attr.span,
trait_ident, trait_ident,
macro_type, macro_type,
@ -1385,29 +1385,29 @@ pub fn parse_macro_name_and_helper_attrs(
let attributes_attr = list.get(1); let attributes_attr = list.get(1);
let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr { let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
if !attr.has_name(sym::attributes) { if !attr.has_name(sym::attributes) {
diag.emit_err(errors::ArgumentNotAttributes { span: attr.span() }); dcx.emit_err(errors::ArgumentNotAttributes { span: attr.span() });
} }
attr.meta_item_list() attr.meta_item_list()
.unwrap_or_else(|| { .unwrap_or_else(|| {
diag.emit_err(errors::AttributesWrongForm { span: attr.span() }); dcx.emit_err(errors::AttributesWrongForm { span: attr.span() });
&[] &[]
}) })
.iter() .iter()
.filter_map(|attr| { .filter_map(|attr| {
let Some(attr) = attr.meta_item() else { let Some(attr) = attr.meta_item() else {
diag.emit_err(errors::AttributeMetaItem { span: attr.span() }); dcx.emit_err(errors::AttributeMetaItem { span: attr.span() });
return None; return None;
}; };
let ident = match attr.ident() { let ident = match attr.ident() {
Some(ident) if attr.is_word() => ident, Some(ident) if attr.is_word() => ident,
_ => { _ => {
diag.emit_err(errors::AttributeSingleWord { span: attr.span }); dcx.emit_err(errors::AttributeSingleWord { span: attr.span });
return None; return None;
} }
}; };
if !ident.name.can_be_raw() { if !ident.name.can_be_raw() {
diag.emit_err(errors::HelperAttributeNameInvalid { dcx.emit_err(errors::HelperAttributeNameInvalid {
span: attr.span, span: attr.span,
name: ident, name: ident,
}); });

View file

@ -317,8 +317,8 @@ pub struct MissingTypeParams {
// Manual implementation of `IntoDiagnostic` to be able to call `span_to_snippet`. // Manual implementation of `IntoDiagnostic` to be able to call `span_to_snippet`.
impl<'a> IntoDiagnostic<'a> for MissingTypeParams { impl<'a> IntoDiagnostic<'a> for MissingTypeParams {
#[track_caller] #[track_caller]
fn into_diagnostic(self, handler: &'a DiagCtxt) -> DiagnosticBuilder<'a, ErrorGuaranteed> { fn into_diagnostic(self, dcx: &'a DiagCtxt) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
let mut err = handler.struct_span_err_with_code( let mut err = dcx.struct_span_err_with_code(
self.span, self.span,
fluent::hir_analysis_missing_type_params, fluent::hir_analysis_missing_type_params,
error_code!(E0393), error_code!(E0393),

View file

@ -42,7 +42,7 @@ pub struct Compiler {
} }
/// Converts strings provided as `--cfg [cfgspec]` into a `Cfg`. /// Converts strings provided as `--cfg [cfgspec]` into a `Cfg`.
pub(crate) fn parse_cfg(handler: &DiagCtxt, cfgs: Vec<String>) -> Cfg { pub(crate) fn parse_cfg(dcx: &DiagCtxt, cfgs: Vec<String>) -> Cfg {
cfgs.into_iter() cfgs.into_iter()
.map(|s| { .map(|s| {
let sess = ParseSess::with_silent_emitter(Some(format!( let sess = ParseSess::with_silent_emitter(Some(format!(
@ -54,8 +54,7 @@ pub(crate) fn parse_cfg(handler: &DiagCtxt, cfgs: Vec<String>) -> Cfg {
($reason: expr) => { ($reason: expr) => {
#[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::untranslatable_diagnostic)]
#[allow(rustc::diagnostic_outside_of_impl)] #[allow(rustc::diagnostic_outside_of_impl)]
handler dcx.struct_fatal(format!(
.struct_fatal(format!(
concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), concat!("invalid `--cfg` argument: `{}` (", $reason, ")"),
s s
)) ))
@ -101,7 +100,7 @@ pub(crate) fn parse_cfg(handler: &DiagCtxt, cfgs: Vec<String>) -> Cfg {
} }
/// Converts strings provided as `--check-cfg [specs]` into a `CheckCfg`. /// Converts strings provided as `--check-cfg [specs]` into a `CheckCfg`.
pub(crate) fn parse_check_cfg(handler: &DiagCtxt, specs: Vec<String>) -> CheckCfg { pub(crate) fn parse_check_cfg(dcx: &DiagCtxt, specs: Vec<String>) -> CheckCfg {
// If any --check-cfg is passed then exhaustive_values and exhaustive_names // If any --check-cfg is passed then exhaustive_values and exhaustive_names
// are enabled by default. // are enabled by default.
let exhaustive_names = !specs.is_empty(); let exhaustive_names = !specs.is_empty();
@ -118,8 +117,7 @@ pub(crate) fn parse_check_cfg(handler: &DiagCtxt, specs: Vec<String>) -> CheckCf
($reason:expr) => { ($reason:expr) => {
#[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::untranslatable_diagnostic)]
#[allow(rustc::diagnostic_outside_of_impl)] #[allow(rustc::diagnostic_outside_of_impl)]
handler dcx.struct_fatal(format!(
.struct_fatal(format!(
concat!("invalid `--check-cfg` argument: `{}` (", $reason, ")"), concat!("invalid `--check-cfg` argument: `{}` (", $reason, ")"),
s s
)) ))
@ -433,7 +431,7 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
} }
pub fn try_print_query_stack( pub fn try_print_query_stack(
handler: &DiagCtxt, dcx: &DiagCtxt,
num_frames: Option<usize>, num_frames: Option<usize>,
file: Option<std::fs::File>, file: Option<std::fs::File>,
) { ) {
@ -447,7 +445,7 @@ pub fn try_print_query_stack(
ty::print::with_no_queries!(print_query_stack( ty::print::with_no_queries!(print_query_stack(
QueryCtxt::new(icx.tcx), QueryCtxt::new(icx.tcx),
icx.query, icx.query,
handler, dcx,
num_frames, num_frames,
file, file,
)) ))

View file

@ -498,9 +498,9 @@ pub(crate) struct MultipleCandidates {
impl IntoDiagnostic<'_> for MultipleCandidates { impl IntoDiagnostic<'_> for MultipleCandidates {
fn into_diagnostic( fn into_diagnostic(
self, self,
handler: &'_ rustc_errors::DiagCtxt, dcx: &'_ rustc_errors::DiagCtxt,
) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> {
let mut diag = handler.struct_err(fluent::metadata_multiple_candidates); let mut diag = dcx.struct_err(fluent::metadata_multiple_candidates);
diag.set_arg("crate_name", self.crate_name); diag.set_arg("crate_name", self.crate_name);
diag.set_arg("flavor", self.flavor); diag.set_arg("flavor", self.flavor);
diag.code(error_code!(E0464)); diag.code(error_code!(E0464));
@ -597,9 +597,9 @@ impl IntoDiagnostic<'_> for InvalidMetadataFiles {
#[track_caller] #[track_caller]
fn into_diagnostic( fn into_diagnostic(
self, self,
handler: &'_ rustc_errors::DiagCtxt, dcx: &'_ rustc_errors::DiagCtxt,
) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> {
let mut diag = handler.struct_err(fluent::metadata_invalid_meta_files); let mut diag = dcx.struct_err(fluent::metadata_invalid_meta_files);
diag.set_arg("crate_name", self.crate_name); diag.set_arg("crate_name", self.crate_name);
diag.set_arg("add_info", self.add_info); diag.set_arg("add_info", self.add_info);
diag.code(error_code!(E0786)); diag.code(error_code!(E0786));
@ -627,9 +627,9 @@ impl IntoDiagnostic<'_> for CannotFindCrate {
#[track_caller] #[track_caller]
fn into_diagnostic( fn into_diagnostic(
self, self,
handler: &'_ rustc_errors::DiagCtxt, dcx: &'_ rustc_errors::DiagCtxt,
) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> {
let mut diag = handler.struct_err(fluent::metadata_cannot_find_crate); let mut diag = dcx.struct_err(fluent::metadata_cannot_find_crate);
diag.set_arg("crate_name", self.crate_name); diag.set_arg("crate_name", self.crate_name);
diag.set_arg("current_crate", self.current_crate); diag.set_arg("current_crate", self.current_crate);
diag.set_arg("add_info", self.add_info); diag.set_arg("add_info", self.add_info);

View file

@ -1273,13 +1273,13 @@ pub enum FnAbiError<'tcx> {
} }
impl<'a, 'b> IntoDiagnostic<'a, !> for FnAbiError<'b> { impl<'a, 'b> IntoDiagnostic<'a, !> for FnAbiError<'b> {
fn into_diagnostic(self, handler: &'a DiagCtxt) -> DiagnosticBuilder<'a, !> { fn into_diagnostic(self, dcx: &'a DiagCtxt) -> DiagnosticBuilder<'a, !> {
match self { match self {
Self::Layout(e) => e.into_diagnostic().into_diagnostic(handler), Self::Layout(e) => e.into_diagnostic().into_diagnostic(dcx),
Self::AdjustForForeignAbi(call::AdjustForForeignAbiError::Unsupported { Self::AdjustForForeignAbi(call::AdjustForForeignAbiError::Unsupported {
arch, arch,
abi, abi,
}) => UnsupportedFnAbi { arch, abi: abi.name() }.into_diagnostic(handler), }) => UnsupportedFnAbi { arch, abi: abi.name() }.into_diagnostic(dcx),
} }
} }
} }

View file

@ -461,8 +461,8 @@ pub(crate) struct NonExhaustivePatternsTypeNotEmpty<'p, 'tcx, 'm> {
} }
impl<'a> IntoDiagnostic<'a> for NonExhaustivePatternsTypeNotEmpty<'_, '_, '_> { impl<'a> IntoDiagnostic<'a> for NonExhaustivePatternsTypeNotEmpty<'_, '_, '_> {
fn into_diagnostic(self, handler: &'a DiagCtxt) -> DiagnosticBuilder<'_, ErrorGuaranteed> { fn into_diagnostic(self, dcx: &'a DiagCtxt) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
let mut diag = handler.struct_span_err_with_code( let mut diag = dcx.struct_span_err_with_code(
self.span, self.span,
fluent::mir_build_non_exhaustive_patterns_type_not_empty, fluent::mir_build_non_exhaustive_patterns_type_not_empty,
error_code!(E0004), error_code!(E0004),

View file

@ -64,15 +64,12 @@ pub(crate) struct RequiresUnsafe {
// but this would result in a lot of duplication. // but this would result in a lot of duplication.
impl<'sess> IntoDiagnostic<'sess> for RequiresUnsafe { impl<'sess> IntoDiagnostic<'sess> for RequiresUnsafe {
#[track_caller] #[track_caller]
fn into_diagnostic( fn into_diagnostic(self, dcx: &'sess DiagCtxt) -> DiagnosticBuilder<'sess, ErrorGuaranteed> {
self, let mut diag = dcx.struct_err(fluent::mir_transform_requires_unsafe);
handler: &'sess DiagCtxt,
) -> DiagnosticBuilder<'sess, ErrorGuaranteed> {
let mut diag = handler.struct_err(fluent::mir_transform_requires_unsafe);
diag.code(rustc_errors::DiagnosticId::Error("E0133".to_string())); diag.code(rustc_errors::DiagnosticId::Error("E0133".to_string()));
diag.set_span(self.span); diag.set_span(self.span);
diag.span_label(self.span, self.details.label()); diag.span_label(self.span, self.details.label());
let desc = handler.eagerly_translate_to_string(self.details.label(), [].into_iter()); let desc = dcx.eagerly_translate_to_string(self.details.label(), [].into_iter());
diag.set_arg("details", desc); diag.set_arg("details", desc);
diag.set_arg("op_in_unsafe_fn_allowed", self.op_in_unsafe_fn_allowed); diag.set_arg("op_in_unsafe_fn_allowed", self.op_in_unsafe_fn_allowed);
self.details.add_subdiagnostics(&mut diag); self.details.add_subdiagnostics(&mut diag);

View file

@ -51,9 +51,9 @@ impl IntoDiagnostic<'_> for UnusedGenericParamsHint {
#[track_caller] #[track_caller]
fn into_diagnostic( fn into_diagnostic(
self, self,
handler: &'_ rustc_errors::DiagCtxt, dcx: &'_ rustc_errors::DiagCtxt,
) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> {
let mut diag = handler.struct_err(fluent::monomorphize_unused_generic_params); let mut diag = dcx.struct_err(fluent::monomorphize_unused_generic_params);
diag.set_span(self.span); diag.set_span(self.span);
for (span, name) in self.param_spans.into_iter().zip(self.param_names) { for (span, name) in self.param_spans.into_iter().zip(self.param_names) {
// FIXME: I can figure out how to do a label with a fluent string with a fixed message, // FIXME: I can figure out how to do a label with a fluent string with a fixed message,

View file

@ -1042,11 +1042,11 @@ impl<'a> IntoDiagnostic<'a> for ExpectedIdentifier {
#[track_caller] #[track_caller]
fn into_diagnostic( fn into_diagnostic(
self, self,
handler: &'a rustc_errors::DiagCtxt, dcx: &'a rustc_errors::DiagCtxt,
) -> rustc_errors::DiagnosticBuilder<'a, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'a, ErrorGuaranteed> {
let token_descr = TokenDescription::from_token(&self.token); let token_descr = TokenDescription::from_token(&self.token);
let mut diag = handler.struct_err(match token_descr { let mut diag = dcx.struct_err(match token_descr {
Some(TokenDescription::ReservedIdentifier) => { Some(TokenDescription::ReservedIdentifier) => {
fluent::parse_expected_identifier_found_reserved_identifier_str fluent::parse_expected_identifier_found_reserved_identifier_str
} }
@ -1099,11 +1099,11 @@ impl<'a> IntoDiagnostic<'a> for ExpectedSemi {
#[track_caller] #[track_caller]
fn into_diagnostic( fn into_diagnostic(
self, self,
handler: &'a rustc_errors::DiagCtxt, dcx: &'a rustc_errors::DiagCtxt,
) -> rustc_errors::DiagnosticBuilder<'a, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'a, ErrorGuaranteed> {
let token_descr = TokenDescription::from_token(&self.token); let token_descr = TokenDescription::from_token(&self.token);
let mut diag = handler.struct_err(match token_descr { let mut diag = dcx.struct_err(match token_descr {
Some(TokenDescription::ReservedIdentifier) => { Some(TokenDescription::ReservedIdentifier) => {
fluent::parse_expected_semi_found_reserved_identifier_str fluent::parse_expected_semi_found_reserved_identifier_str
} }

View file

@ -10,7 +10,7 @@ use rustc_span::{BytePos, Span};
use crate::errors::{MoreThanOneCharNote, MoreThanOneCharSugg, NoBraceUnicodeSub, UnescapeError}; use crate::errors::{MoreThanOneCharNote, MoreThanOneCharSugg, NoBraceUnicodeSub, UnescapeError};
pub(crate) fn emit_unescape_error( pub(crate) fn emit_unescape_error(
handler: &DiagCtxt, dcx: &DiagCtxt,
// interior part of the literal, between quotes // interior part of the literal, between quotes
lit: &str, lit: &str,
// full span of the literal, including quotes and any prefix // full span of the literal, including quotes and any prefix
@ -33,12 +33,10 @@ pub(crate) fn emit_unescape_error(
}; };
match error { match error {
EscapeError::LoneSurrogateUnicodeEscape => { EscapeError::LoneSurrogateUnicodeEscape => {
handler dcx.emit_err(UnescapeError::InvalidUnicodeEscape { span: err_span, surrogate: true });
.emit_err(UnescapeError::InvalidUnicodeEscape { span: err_span, surrogate: true });
} }
EscapeError::OutOfRangeUnicodeEscape => { EscapeError::OutOfRangeUnicodeEscape => {
handler dcx.emit_err(UnescapeError::InvalidUnicodeEscape { span: err_span, surrogate: false });
.emit_err(UnescapeError::InvalidUnicodeEscape { span: err_span, surrogate: false });
} }
EscapeError::MoreThanOneChar => { EscapeError::MoreThanOneChar => {
use unicode_normalization::{char::is_combining_mark, UnicodeNormalization}; use unicode_normalization::{char::is_combining_mark, UnicodeNormalization};
@ -104,7 +102,7 @@ pub(crate) fn emit_unescape_error(
sugg, sugg,
} }
}); });
handler.emit_err(UnescapeError::MoreThanOneChar { dcx.emit_err(UnescapeError::MoreThanOneChar {
span: full_lit_span, span: full_lit_span,
note, note,
suggestion: sugg, suggestion: sugg,
@ -112,7 +110,7 @@ pub(crate) fn emit_unescape_error(
} }
EscapeError::EscapeOnlyChar => { EscapeError::EscapeOnlyChar => {
let (c, char_span) = last_char(); let (c, char_span) = last_char();
handler.emit_err(UnescapeError::EscapeOnlyChar { dcx.emit_err(UnescapeError::EscapeOnlyChar {
span: err_span, span: err_span,
char_span, char_span,
escaped_sugg: c.escape_default().to_string(), escaped_sugg: c.escape_default().to_string(),
@ -122,11 +120,11 @@ pub(crate) fn emit_unescape_error(
} }
EscapeError::BareCarriageReturn => { EscapeError::BareCarriageReturn => {
let double_quotes = mode.in_double_quotes(); let double_quotes = mode.in_double_quotes();
handler.emit_err(UnescapeError::BareCr { span: err_span, double_quotes }); dcx.emit_err(UnescapeError::BareCr { span: err_span, double_quotes });
} }
EscapeError::BareCarriageReturnInRawString => { EscapeError::BareCarriageReturnInRawString => {
assert!(mode.in_double_quotes()); assert!(mode.in_double_quotes());
handler.emit_err(UnescapeError::BareCrRawString(err_span)); dcx.emit_err(UnescapeError::BareCrRawString(err_span));
} }
EscapeError::InvalidEscape => { EscapeError::InvalidEscape => {
let (c, span) = last_char(); let (c, span) = last_char();
@ -137,7 +135,7 @@ pub(crate) fn emit_unescape_error(
"unknown character escape" "unknown character escape"
}; };
let ec = escaped_char(c); let ec = escaped_char(c);
let mut diag = handler.struct_span_err(span, format!("{label}: `{ec}`")); let mut diag = dcx.struct_span_err(span, format!("{label}: `{ec}`"));
diag.span_label(span, label); diag.span_label(span, label);
if c == '{' || c == '}' && matches!(mode, Mode::Str | Mode::RawStr) { if c == '{' || c == '}' && matches!(mode, Mode::Str | Mode::RawStr) {
diag.help( diag.help(
@ -166,13 +164,13 @@ pub(crate) fn emit_unescape_error(
diag.emit(); diag.emit();
} }
EscapeError::TooShortHexEscape => { EscapeError::TooShortHexEscape => {
handler.emit_err(UnescapeError::TooShortHexEscape(err_span)); dcx.emit_err(UnescapeError::TooShortHexEscape(err_span));
} }
EscapeError::InvalidCharInHexEscape | EscapeError::InvalidCharInUnicodeEscape => { EscapeError::InvalidCharInHexEscape | EscapeError::InvalidCharInUnicodeEscape => {
let (c, span) = last_char(); let (c, span) = last_char();
let is_hex = error == EscapeError::InvalidCharInHexEscape; let is_hex = error == EscapeError::InvalidCharInHexEscape;
let ch = escaped_char(c); let ch = escaped_char(c);
handler.emit_err(UnescapeError::InvalidCharInEscape { span, is_hex, ch }); dcx.emit_err(UnescapeError::InvalidCharInEscape { span, is_hex, ch });
} }
EscapeError::NonAsciiCharInByte => { EscapeError::NonAsciiCharInByte => {
let (c, span) = last_char(); let (c, span) = last_char();
@ -182,7 +180,7 @@ pub(crate) fn emit_unescape_error(
Mode::RawByteStr => "raw byte string literal", Mode::RawByteStr => "raw byte string literal",
_ => panic!("non-is_byte literal paired with NonAsciiCharInByte"), _ => panic!("non-is_byte literal paired with NonAsciiCharInByte"),
}; };
let mut err = handler.struct_span_err(span, format!("non-ASCII character in {desc}")); let mut err = dcx.struct_span_err(span, format!("non-ASCII character in {desc}"));
let postfix = if unicode_width::UnicodeWidthChar::width(c).unwrap_or(1) == 0 { let postfix = if unicode_width::UnicodeWidthChar::width(c).unwrap_or(1) == 0 {
format!(" but is {c:?}") format!(" but is {c:?}")
} else { } else {
@ -218,21 +216,20 @@ pub(crate) fn emit_unescape_error(
err.emit(); err.emit();
} }
EscapeError::OutOfRangeHexEscape => { EscapeError::OutOfRangeHexEscape => {
handler.emit_err(UnescapeError::OutOfRangeHexEscape(err_span)); dcx.emit_err(UnescapeError::OutOfRangeHexEscape(err_span));
} }
EscapeError::LeadingUnderscoreUnicodeEscape => { EscapeError::LeadingUnderscoreUnicodeEscape => {
let (c, span) = last_char(); let (c, span) = last_char();
handler.emit_err(UnescapeError::LeadingUnderscoreUnicodeEscape { dcx.emit_err(UnescapeError::LeadingUnderscoreUnicodeEscape {
span, span,
ch: escaped_char(c), ch: escaped_char(c),
}); });
} }
EscapeError::OverlongUnicodeEscape => { EscapeError::OverlongUnicodeEscape => {
handler.emit_err(UnescapeError::OverlongUnicodeEscape(err_span)); dcx.emit_err(UnescapeError::OverlongUnicodeEscape(err_span));
} }
EscapeError::UnclosedUnicodeEscape => { EscapeError::UnclosedUnicodeEscape => {
handler dcx.emit_err(UnescapeError::UnclosedUnicodeEscape(err_span, err_span.shrink_to_hi()));
.emit_err(UnescapeError::UnclosedUnicodeEscape(err_span, err_span.shrink_to_hi()));
} }
EscapeError::NoBraceInUnicodeEscape => { EscapeError::NoBraceInUnicodeEscape => {
let mut suggestion = "\\u{".to_owned(); let mut suggestion = "\\u{".to_owned();
@ -251,30 +248,30 @@ pub(crate) fn emit_unescape_error(
} else { } else {
(Some(err_span), NoBraceUnicodeSub::Help) (Some(err_span), NoBraceUnicodeSub::Help)
}; };
handler.emit_err(UnescapeError::NoBraceInUnicodeEscape { span: err_span, label, sub }); dcx.emit_err(UnescapeError::NoBraceInUnicodeEscape { span: err_span, label, sub });
} }
EscapeError::UnicodeEscapeInByte => { EscapeError::UnicodeEscapeInByte => {
handler.emit_err(UnescapeError::UnicodeEscapeInByte(err_span)); dcx.emit_err(UnescapeError::UnicodeEscapeInByte(err_span));
} }
EscapeError::EmptyUnicodeEscape => { EscapeError::EmptyUnicodeEscape => {
handler.emit_err(UnescapeError::EmptyUnicodeEscape(err_span)); dcx.emit_err(UnescapeError::EmptyUnicodeEscape(err_span));
} }
EscapeError::ZeroChars => { EscapeError::ZeroChars => {
handler.emit_err(UnescapeError::ZeroChars(err_span)); dcx.emit_err(UnescapeError::ZeroChars(err_span));
} }
EscapeError::LoneSlash => { EscapeError::LoneSlash => {
handler.emit_err(UnescapeError::LoneSlash(err_span)); dcx.emit_err(UnescapeError::LoneSlash(err_span));
} }
EscapeError::UnskippedWhitespaceWarning => { EscapeError::UnskippedWhitespaceWarning => {
let (c, char_span) = last_char(); let (c, char_span) = last_char();
handler.emit_warning(UnescapeError::UnskippedWhitespace { dcx.emit_warning(UnescapeError::UnskippedWhitespace {
span: err_span, span: err_span,
ch: escaped_char(c), ch: escaped_char(c),
char_span, char_span,
}); });
} }
EscapeError::MultipleSkippedLinesWarning => { EscapeError::MultipleSkippedLinesWarning => {
handler.emit_warning(UnescapeError::MultipleSkippedLinesWarning(err_span)); dcx.emit_warning(UnescapeError::MultipleSkippedLinesWarning(err_span));
} }
} }
} }

View file

@ -867,9 +867,9 @@ impl IntoDiagnostic<'_> for InvalidAttrAtCrateLevel {
#[track_caller] #[track_caller]
fn into_diagnostic( fn into_diagnostic(
self, self,
handler: &'_ rustc_errors::DiagCtxt, dcx: &'_ rustc_errors::DiagCtxt,
) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> {
let mut diag = handler.struct_err(fluent::passes_invalid_attr_at_crate_level); let mut diag = dcx.struct_err(fluent::passes_invalid_attr_at_crate_level);
diag.set_span(self.span); diag.set_span(self.span);
diag.set_arg("name", self.name); diag.set_arg("name", self.name);
// Only emit an error with a suggestion if we can create a string out // Only emit an error with a suggestion if we can create a string out
@ -1020,9 +1020,9 @@ impl<'a> IntoDiagnostic<'_> for BreakNonLoop<'a> {
#[track_caller] #[track_caller]
fn into_diagnostic( fn into_diagnostic(
self, self,
handler: &rustc_errors::DiagCtxt, dcx: &rustc_errors::DiagCtxt,
) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> {
let mut diag = handler.struct_span_err_with_code( let mut diag = dcx.struct_span_err_with_code(
self.span, self.span,
fluent::passes_break_non_loop, fluent::passes_break_non_loop,
error_code!(E0571), error_code!(E0571),
@ -1169,9 +1169,9 @@ impl IntoDiagnostic<'_> for NakedFunctionsAsmBlock {
#[track_caller] #[track_caller]
fn into_diagnostic( fn into_diagnostic(
self, self,
handler: &rustc_errors::DiagCtxt, dcx: &rustc_errors::DiagCtxt,
) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> {
let mut diag = handler.struct_span_err_with_code( let mut diag = dcx.struct_span_err_with_code(
self.span, self.span,
fluent::passes_naked_functions_asm_block, fluent::passes_naked_functions_asm_block,
error_code!(E0787), error_code!(E0787),
@ -1285,9 +1285,9 @@ impl<'a> IntoDiagnostic<'a> for NoMainErr {
#[track_caller] #[track_caller]
fn into_diagnostic( fn into_diagnostic(
self, self,
handler: &'a rustc_errors::DiagCtxt, dcx: &'a rustc_errors::DiagCtxt,
) -> rustc_errors::DiagnosticBuilder<'a, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'a, ErrorGuaranteed> {
let mut diag = handler.struct_span_err_with_code( let mut diag = dcx.struct_span_err_with_code(
DUMMY_SP, DUMMY_SP,
fluent::passes_no_main_function, fluent::passes_no_main_function,
error_code!(E0601), error_code!(E0601),
@ -1348,9 +1348,9 @@ impl IntoDiagnostic<'_> for DuplicateLangItem {
#[track_caller] #[track_caller]
fn into_diagnostic( fn into_diagnostic(
self, self,
handler: &rustc_errors::DiagCtxt, dcx: &rustc_errors::DiagCtxt,
) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> {
let mut diag = handler.struct_err_with_code( let mut diag = dcx.struct_err_with_code(
match self.duplicate { match self.duplicate {
Duplicate::Plain => fluent::passes_duplicate_lang_item, Duplicate::Plain => fluent::passes_duplicate_lang_item,
Duplicate::Crate => fluent::passes_duplicate_lang_item_crate, Duplicate::Crate => fluent::passes_duplicate_lang_item_crate,

View file

@ -610,7 +610,7 @@ pub(crate) fn report_cycle<'a>(
pub fn print_query_stack<Qcx: QueryContext>( pub fn print_query_stack<Qcx: QueryContext>(
qcx: Qcx, qcx: Qcx,
mut current_query: Option<QueryJobId>, mut current_query: Option<QueryJobId>,
handler: &DiagCtxt, dcx: &DiagCtxt,
num_frames: Option<usize>, num_frames: Option<usize>,
mut file: Option<std::fs::File>, mut file: Option<std::fs::File>,
) -> usize { ) -> usize {
@ -638,7 +638,7 @@ pub fn print_query_stack<Qcx: QueryContext>(
), ),
); );
diag.span = query_info.job.span.into(); diag.span = query_info.job.span.into();
handler.force_print_diagnostic(diag); dcx.force_print_diagnostic(diag);
count_printed += 1; count_printed += 1;
} }

View file

@ -17,9 +17,9 @@ impl<'a> IntoDiagnostic<'a> for FeatureGateError {
#[track_caller] #[track_caller]
fn into_diagnostic( fn into_diagnostic(
self, self,
handler: &'a rustc_errors::DiagCtxt, dcx: &'a rustc_errors::DiagCtxt,
) -> rustc_errors::DiagnosticBuilder<'a, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'a, ErrorGuaranteed> {
let mut diag = handler.struct_err(self.explain); let mut diag = dcx.struct_err(self.explain);
diag.set_span(self.span); diag.set_span(self.span);
diag.code(error_code!(E0658)); diag.code(error_code!(E0658));
diag diag

View file

@ -230,9 +230,9 @@ impl ParseSess {
ParseSess::with_dcx(handler, sm) ParseSess::with_dcx(handler, sm)
} }
pub fn with_dcx(handler: DiagCtxt, source_map: Lrc<SourceMap>) -> Self { pub fn with_dcx(dcx: DiagCtxt, source_map: Lrc<SourceMap>) -> Self {
Self { Self {
dcx: handler, dcx,
unstable_features: UnstableFeatures::from_environment(None), unstable_features: UnstableFeatures::from_environment(None),
config: Cfg::default(), config: Cfg::default(),
check_config: CheckCfg::default(), check_config: CheckCfg::default(),

View file

@ -16,12 +16,12 @@ pub struct TestOutput {
impl IntoDiagnostic<'_> for TestOutput { impl IntoDiagnostic<'_> for TestOutput {
fn into_diagnostic( fn into_diagnostic(
self, self,
handler: &'_ rustc_errors::DiagCtxt, dcx: &'_ rustc_errors::DiagCtxt,
) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> {
let TestOutput { span, kind, content } = self; let TestOutput { span, kind, content } = self;
#[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::untranslatable_diagnostic)]
let mut diag = handler.struct_err(format!("{kind}({content})")); let mut diag = dcx.struct_err(format!("{kind}({content})"));
diag.set_span(span); diag.set_span(span);
diag diag
} }

View file

@ -61,9 +61,9 @@ impl IntoDiagnostic<'_> for NegativePositiveConflict<'_> {
#[track_caller] #[track_caller]
fn into_diagnostic( fn into_diagnostic(
self, self,
handler: &DiagCtxt, dcx: &DiagCtxt,
) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> { ) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> {
let mut diag = handler.struct_err(fluent::trait_selection_negative_positive_conflict); let mut diag = dcx.struct_err(fluent::trait_selection_negative_positive_conflict);
diag.set_arg("trait_desc", self.trait_desc.print_only_trait_path().to_string()); diag.set_arg("trait_desc", self.trait_desc.print_only_trait_path().to_string());
diag.set_arg( diag.set_arg(
"self_desc", "self_desc",

View file

@ -803,12 +803,12 @@ impl Options {
} }
/// Prints deprecation warnings for deprecated options /// Prints deprecation warnings for deprecated options
fn check_deprecated_options(matches: &getopts::Matches, diag: &rustc_errors::DiagCtxt) { fn check_deprecated_options(matches: &getopts::Matches, dcx: &rustc_errors::DiagCtxt) {
let deprecated_flags = []; let deprecated_flags = [];
for &flag in deprecated_flags.iter() { for &flag in deprecated_flags.iter() {
if matches.opt_present(flag) { if matches.opt_present(flag) {
diag.struct_warn(format!("the `{flag}` flag is deprecated")) dcx.struct_warn(format!("the `{flag}` flag is deprecated"))
.note( .note(
"see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \ "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
for more information", for more information",
@ -821,7 +821,7 @@ fn check_deprecated_options(matches: &getopts::Matches, diag: &rustc_errors::Dia
for &flag in removed_flags.iter() { for &flag in removed_flags.iter() {
if matches.opt_present(flag) { if matches.opt_present(flag) {
let mut err = diag.struct_warn(format!("the `{flag}` flag no longer functions")); let mut err = dcx.struct_warn(format!("the `{flag}` flag no longer functions"));
err.note( err.note(
"see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \ "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
for more information", for more information",

View file

@ -385,9 +385,9 @@ pub(crate) fn run_global_ctxt(
); );
} }
fn report_deprecated_attr(name: &str, diag: &rustc_errors::DiagCtxt, sp: Span) { fn report_deprecated_attr(name: &str, dcx: &rustc_errors::DiagCtxt, sp: Span) {
let mut msg = let mut msg =
diag.struct_span_warn(sp, format!("the `#![doc({name})]` attribute is deprecated")); dcx.struct_span_warn(sp, format!("the `#![doc({name})]` attribute is deprecated"));
msg.note( msg.note(
"see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \ "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
for more information", for more information",

View file

@ -27,15 +27,15 @@ impl ExternalHtml {
md_before_content: &[String], md_before_content: &[String],
md_after_content: &[String], md_after_content: &[String],
nightly_build: bool, nightly_build: bool,
diag: &rustc_errors::DiagCtxt, dcx: &rustc_errors::DiagCtxt,
id_map: &mut IdMap, id_map: &mut IdMap,
edition: Edition, edition: Edition,
playground: &Option<Playground>, playground: &Option<Playground>,
) -> Option<ExternalHtml> { ) -> Option<ExternalHtml> {
let codes = ErrorCodes::from(nightly_build); let codes = ErrorCodes::from(nightly_build);
let ih = load_external_files(in_header, diag)?; let ih = load_external_files(in_header, dcx)?;
let bc = load_external_files(before_content, diag)?; let bc = load_external_files(before_content, dcx)?;
let m_bc = load_external_files(md_before_content, diag)?; let m_bc = load_external_files(md_before_content, dcx)?;
let bc = format!( let bc = format!(
"{bc}{}", "{bc}{}",
Markdown { Markdown {
@ -51,8 +51,8 @@ impl ExternalHtml {
} }
.into_string() .into_string()
); );
let ac = load_external_files(after_content, diag)?; let ac = load_external_files(after_content, dcx)?;
let m_ac = load_external_files(md_after_content, diag)?; let m_ac = load_external_files(md_after_content, dcx)?;
let ac = format!( let ac = format!(
"{ac}{}", "{ac}{}",
Markdown { Markdown {
@ -79,13 +79,13 @@ pub(crate) enum LoadStringError {
pub(crate) fn load_string<P: AsRef<Path>>( pub(crate) fn load_string<P: AsRef<Path>>(
file_path: P, file_path: P,
diag: &rustc_errors::DiagCtxt, dcx: &rustc_errors::DiagCtxt,
) -> Result<String, LoadStringError> { ) -> Result<String, LoadStringError> {
let file_path = file_path.as_ref(); let file_path = file_path.as_ref();
let contents = match fs::read(file_path) { let contents = match fs::read(file_path) {
Ok(bytes) => bytes, Ok(bytes) => bytes,
Err(e) => { Err(e) => {
diag.struct_err(format!( dcx.struct_err(format!(
"error reading `{file_path}`: {e}", "error reading `{file_path}`: {e}",
file_path = file_path.display() file_path = file_path.display()
)) ))
@ -96,16 +96,16 @@ pub(crate) fn load_string<P: AsRef<Path>>(
match str::from_utf8(&contents) { match str::from_utf8(&contents) {
Ok(s) => Ok(s.to_string()), Ok(s) => Ok(s.to_string()),
Err(_) => { Err(_) => {
diag.struct_err(format!("error reading `{}`: not UTF-8", file_path.display())).emit(); dcx.struct_err(format!("error reading `{}`: not UTF-8", file_path.display())).emit();
Err(LoadStringError::BadUtf8) Err(LoadStringError::BadUtf8)
} }
} }
} }
fn load_external_files(names: &[String], diag: &rustc_errors::DiagCtxt) -> Option<String> { fn load_external_files(names: &[String], dcx: &rustc_errors::DiagCtxt) -> Option<String> {
let mut out = String::new(); let mut out = String::new();
for name in names { for name in names {
let Ok(s) = load_string(name, diag) else { return None }; let Ok(s) = load_string(name, dcx) else { return None };
out.push_str(&s); out.push_str(&s);
out.push('\n'); out.push('\n');
} }

View file

@ -673,11 +673,11 @@ fn usage(argv0: &str) {
/// A result type used by several functions under `main()`. /// A result type used by several functions under `main()`.
type MainResult = Result<(), ErrorGuaranteed>; type MainResult = Result<(), ErrorGuaranteed>;
fn wrap_return(diag: &rustc_errors::DiagCtxt, res: Result<(), String>) -> MainResult { fn wrap_return(dcx: &rustc_errors::DiagCtxt, res: Result<(), String>) -> MainResult {
match res { match res {
Ok(()) => diag.has_errors().map_or(Ok(()), Err), Ok(()) => dcx.has_errors().map_or(Ok(()), Err),
Err(err) => { Err(err) => {
let reported = diag.struct_err(err).emit(); let reported = dcx.struct_err(err).emit();
Err(reported) Err(reported)
} }
} }

View file

@ -40,7 +40,7 @@ pub(crate) struct ScrapeExamplesOptions {
impl ScrapeExamplesOptions { impl ScrapeExamplesOptions {
pub(crate) fn new( pub(crate) fn new(
matches: &getopts::Matches, matches: &getopts::Matches,
diag: &rustc_errors::DiagCtxt, dcx: &rustc_errors::DiagCtxt,
) -> Result<Option<Self>, i32> { ) -> Result<Option<Self>, i32> {
let output_path = matches.opt_str("scrape-examples-output-path"); let output_path = matches.opt_str("scrape-examples-output-path");
let target_crates = matches.opt_strs("scrape-examples-target-crate"); let target_crates = matches.opt_strs("scrape-examples-target-crate");
@ -52,11 +52,11 @@ impl ScrapeExamplesOptions {
scrape_tests, scrape_tests,
})), })),
(Some(_), false, _) | (None, true, _) => { (Some(_), false, _) | (None, true, _) => {
diag.err("must use --scrape-examples-output-path and --scrape-examples-target-crate together"); dcx.err("must use --scrape-examples-output-path and --scrape-examples-target-crate together");
Err(1) Err(1)
} }
(None, false, true) => { (None, false, true) => {
diag.err("must use --scrape-examples-output-path and --scrape-examples-target-crate with --scrape-tests"); dcx.err("must use --scrape-examples-output-path and --scrape-examples-target-crate with --scrape-tests");
Err(1) Err(1)
} }
(None, false, false) => Ok(None), (None, false, false) => Ok(None),
@ -341,7 +341,7 @@ pub(crate) fn run(
// options. // options.
pub(crate) fn load_call_locations( pub(crate) fn load_call_locations(
with_examples: Vec<String>, with_examples: Vec<String>,
diag: &rustc_errors::DiagCtxt, dcx: &rustc_errors::DiagCtxt,
) -> Result<AllCallLocations, i32> { ) -> Result<AllCallLocations, i32> {
let inner = || { let inner = || {
let mut all_calls: AllCallLocations = FxHashMap::default(); let mut all_calls: AllCallLocations = FxHashMap::default();
@ -359,7 +359,7 @@ pub(crate) fn load_call_locations(
}; };
inner().map_err(|e: String| { inner().map_err(|e: String| {
diag.err(format!("failed to load examples: {e}")); dcx.err(format!("failed to load examples: {e}"));
1 1
}) })
} }

View file

@ -236,7 +236,7 @@ pub(crate) fn get_differences(
pub(crate) fn test_theme_against<P: AsRef<Path>>( pub(crate) fn test_theme_against<P: AsRef<Path>>(
f: &P, f: &P,
origin: &FxHashMap<String, CssPath>, origin: &FxHashMap<String, CssPath>,
diag: &DiagCtxt, dcx: &DiagCtxt,
) -> (bool, Vec<String>) { ) -> (bool, Vec<String>) {
let against = match fs::read_to_string(f) let against = match fs::read_to_string(f)
.map_err(|e| e.to_string()) .map_err(|e| e.to_string())
@ -244,7 +244,7 @@ pub(crate) fn test_theme_against<P: AsRef<Path>>(
{ {
Ok(c) => c, Ok(c) => c,
Err(e) => { Err(e) => {
diag.struct_err(e).emit(); dcx.struct_err(e).emit();
return (false, vec![]); return (false, vec![]);
} }
}; };