Rename many `DiagCtxt` and `EarlyDiagCtxt` locals.

This commit is contained in:
Nicholas Nethercote 2023-12-18 11:15:13 +11:00
parent d58e372853
commit f6aa418c9f
33 changed files with 250 additions and 258 deletions

View File

@ -47,10 +47,10 @@ pub fn parse_asm_args<'a>(
sp: Span, sp: Span,
is_global_asm: bool, is_global_asm: bool,
) -> PResult<'a, AsmArgs> { ) -> PResult<'a, AsmArgs> {
let diag = &sess.dcx; let dcx = &sess.dcx;
if p.token == token::Eof { if p.token == token::Eof {
return Err(diag.create_err(errors::AsmRequiresTemplate { span: sp })); return Err(dcx.create_err(errors::AsmRequiresTemplate { span: sp }));
} }
let first_template = p.parse_expr()?; let first_template = p.parse_expr()?;
@ -69,7 +69,7 @@ pub fn parse_asm_args<'a>(
if !p.eat(&token::Comma) { if !p.eat(&token::Comma) {
if allow_templates { if allow_templates {
// After a template string, we always expect *only* a comma... // After a template string, we always expect *only* a comma...
return Err(diag.create_err(errors::AsmExpectedComma { span: p.token.span })); return Err(dcx.create_err(errors::AsmExpectedComma { span: p.token.span }));
} else { } else {
// ...after that delegate to `expect` to also include the other expected tokens. // ...after that delegate to `expect` to also include the other expected tokens.
return Err(p.expect(&token::Comma).err().unwrap()); return Err(p.expect(&token::Comma).err().unwrap());
@ -110,7 +110,7 @@ pub fn parse_asm_args<'a>(
let op = if !is_global_asm && p.eat_keyword(kw::In) { let op = if !is_global_asm && p.eat_keyword(kw::In) {
let reg = parse_reg(p, &mut explicit_reg)?; let reg = parse_reg(p, &mut explicit_reg)?;
if p.eat_keyword(kw::Underscore) { if p.eat_keyword(kw::Underscore) {
let err = diag.create_err(errors::AsmUnderscoreInput { span: p.token.span }); let err = dcx.create_err(errors::AsmUnderscoreInput { span: p.token.span });
return Err(err); return Err(err);
} }
let expr = p.parse_expr()?; let expr = p.parse_expr()?;
@ -126,7 +126,7 @@ pub fn parse_asm_args<'a>(
} else if !is_global_asm && p.eat_keyword(sym::inout) { } else if !is_global_asm && p.eat_keyword(sym::inout) {
let reg = parse_reg(p, &mut explicit_reg)?; let reg = parse_reg(p, &mut explicit_reg)?;
if p.eat_keyword(kw::Underscore) { if p.eat_keyword(kw::Underscore) {
let err = diag.create_err(errors::AsmUnderscoreInput { span: p.token.span }); let err = dcx.create_err(errors::AsmUnderscoreInput { span: p.token.span });
return Err(err); return Err(err);
} }
let expr = p.parse_expr()?; let expr = p.parse_expr()?;
@ -140,7 +140,7 @@ pub fn parse_asm_args<'a>(
} else if !is_global_asm && p.eat_keyword(sym::inlateout) { } else if !is_global_asm && p.eat_keyword(sym::inlateout) {
let reg = parse_reg(p, &mut explicit_reg)?; let reg = parse_reg(p, &mut explicit_reg)?;
if p.eat_keyword(kw::Underscore) { if p.eat_keyword(kw::Underscore) {
let err = diag.create_err(errors::AsmUnderscoreInput { span: p.token.span }); let err = dcx.create_err(errors::AsmUnderscoreInput { span: p.token.span });
return Err(err); return Err(err);
} }
let expr = p.parse_expr()?; let expr = p.parse_expr()?;
@ -157,7 +157,7 @@ pub fn parse_asm_args<'a>(
} else if p.eat_keyword(sym::sym) { } else if p.eat_keyword(sym::sym) {
let expr = p.parse_expr()?; let expr = p.parse_expr()?;
let ast::ExprKind::Path(qself, path) = &expr.kind else { let ast::ExprKind::Path(qself, path) = &expr.kind else {
let err = diag.create_err(errors::AsmSymNoPath { span: expr.span }); let err = dcx.create_err(errors::AsmSymNoPath { span: expr.span });
return Err(err); return Err(err);
}; };
let sym = ast::InlineAsmSym { let sym = ast::InlineAsmSym {
@ -178,7 +178,7 @@ pub fn parse_asm_args<'a>(
) => {} ) => {}
ast::ExprKind::MacCall(..) => {} ast::ExprKind::MacCall(..) => {}
_ => { _ => {
let err = diag.create_err(errors::AsmExpectedOther { let err = dcx.create_err(errors::AsmExpectedOther {
span: template.span, span: template.span,
is_global_asm, is_global_asm,
}); });
@ -201,12 +201,12 @@ pub fn parse_asm_args<'a>(
// of the argument available. // of the argument available.
if explicit_reg { if explicit_reg {
if name.is_some() { if name.is_some() {
diag.emit_err(errors::AsmExplicitRegisterName { span }); dcx.emit_err(errors::AsmExplicitRegisterName { span });
} }
args.reg_args.insert(slot); args.reg_args.insert(slot);
} else if let Some(name) = name { } else if let Some(name) = name {
if let Some(&prev) = args.named_args.get(&name) { if let Some(&prev) = args.named_args.get(&name) {
diag.emit_err(errors::AsmDuplicateArg { span, name, prev: args.operands[prev].1 }); dcx.emit_err(errors::AsmDuplicateArg { span, name, prev: args.operands[prev].1 });
continue; continue;
} }
args.named_args.insert(name, slot); args.named_args.insert(name, slot);
@ -215,7 +215,7 @@ pub fn parse_asm_args<'a>(
let named = args.named_args.values().map(|p| args.operands[*p].1).collect(); let named = args.named_args.values().map(|p| args.operands[*p].1).collect();
let explicit = args.reg_args.iter().map(|p| args.operands[p].1).collect(); let explicit = args.reg_args.iter().map(|p| args.operands[p].1).collect();
diag.emit_err(errors::AsmPositionalAfter { span, named, explicit }); dcx.emit_err(errors::AsmPositionalAfter { span, named, explicit });
} }
} }
} }
@ -224,19 +224,19 @@ pub fn parse_asm_args<'a>(
&& args.options.contains(ast::InlineAsmOptions::READONLY) && args.options.contains(ast::InlineAsmOptions::READONLY)
{ {
let spans = args.options_spans.clone(); let spans = args.options_spans.clone();
diag.emit_err(errors::AsmMutuallyExclusive { spans, opt1: "nomem", opt2: "readonly" }); dcx.emit_err(errors::AsmMutuallyExclusive { spans, opt1: "nomem", opt2: "readonly" });
} }
if args.options.contains(ast::InlineAsmOptions::PURE) if args.options.contains(ast::InlineAsmOptions::PURE)
&& args.options.contains(ast::InlineAsmOptions::NORETURN) && args.options.contains(ast::InlineAsmOptions::NORETURN)
{ {
let spans = args.options_spans.clone(); let spans = args.options_spans.clone();
diag.emit_err(errors::AsmMutuallyExclusive { spans, opt1: "pure", opt2: "noreturn" }); dcx.emit_err(errors::AsmMutuallyExclusive { spans, opt1: "pure", opt2: "noreturn" });
} }
if args.options.contains(ast::InlineAsmOptions::PURE) if args.options.contains(ast::InlineAsmOptions::PURE)
&& !args.options.intersects(ast::InlineAsmOptions::NOMEM | ast::InlineAsmOptions::READONLY) && !args.options.intersects(ast::InlineAsmOptions::NOMEM | ast::InlineAsmOptions::READONLY)
{ {
let spans = args.options_spans.clone(); let spans = args.options_spans.clone();
diag.emit_err(errors::AsmPureCombine { spans }); dcx.emit_err(errors::AsmPureCombine { spans });
} }
let mut have_real_output = false; let mut have_real_output = false;
@ -263,17 +263,17 @@ pub fn parse_asm_args<'a>(
} }
} }
if args.options.contains(ast::InlineAsmOptions::PURE) && !have_real_output { if args.options.contains(ast::InlineAsmOptions::PURE) && !have_real_output {
diag.emit_err(errors::AsmPureNoOutput { spans: args.options_spans.clone() }); dcx.emit_err(errors::AsmPureNoOutput { spans: args.options_spans.clone() });
} }
if args.options.contains(ast::InlineAsmOptions::NORETURN) && !outputs_sp.is_empty() { if args.options.contains(ast::InlineAsmOptions::NORETURN) && !outputs_sp.is_empty() {
let err = diag.create_err(errors::AsmNoReturn { outputs_sp }); let err = dcx.create_err(errors::AsmNoReturn { outputs_sp });
// Bail out now since this is likely to confuse MIR // Bail out now since this is likely to confuse MIR
return Err(err); return Err(err);
} }
if args.clobber_abis.len() > 0 { if args.clobber_abis.len() > 0 {
if is_global_asm { if is_global_asm {
let err = diag.create_err(errors::GlobalAsmClobberAbi { let err = dcx.create_err(errors::GlobalAsmClobberAbi {
spans: args.clobber_abis.iter().map(|(_, span)| *span).collect(), spans: args.clobber_abis.iter().map(|(_, span)| *span).collect(),
}); });
@ -281,7 +281,7 @@ pub fn parse_asm_args<'a>(
return Err(err); return Err(err);
} }
if !regclass_outputs.is_empty() { if !regclass_outputs.is_empty() {
diag.emit_err(errors::AsmClobberNoReg { dcx.emit_err(errors::AsmClobberNoReg {
spans: regclass_outputs, spans: regclass_outputs,
clobbers: args.clobber_abis.iter().map(|(_, span)| *span).collect(), clobbers: args.clobber_abis.iter().map(|(_, span)| *span).collect(),
}); });

View File

@ -389,16 +389,16 @@ pub fn expand_test_or_bench(
} }
fn not_testable_error(cx: &ExtCtxt<'_>, attr_sp: Span, item: Option<&ast::Item>) { fn not_testable_error(cx: &ExtCtxt<'_>, attr_sp: Span, item: Option<&ast::Item>) {
let diag = cx.sess.dcx(); let dcx = cx.sess.dcx();
let msg = "the `#[test]` attribute may only be used on a non-associated function"; let msg = "the `#[test]` attribute may only be used on a non-associated function";
let mut err = match item.map(|i| &i.kind) { let mut err = match item.map(|i| &i.kind) {
// These were a warning before #92959 and need to continue being that to avoid breaking // These were a warning before #92959 and need to continue being that to avoid breaking
// stable user code (#94508). // stable user code (#94508).
Some(ast::ItemKind::MacCall(_)) => diag.struct_span_warn(attr_sp, msg), Some(ast::ItemKind::MacCall(_)) => dcx.struct_span_warn(attr_sp, msg),
// `.forget_guarantee()` needed to get these two arms to match types. Because of how // `.forget_guarantee()` needed to get these two arms to match types. Because of how
// locally close the `.emit()` call is I'm comfortable with it, but if it can be // locally close the `.emit()` call is I'm comfortable with it, but if it can be
// reworked in the future to not need it, it'd be nice. // reworked in the future to not need it, it'd be nice.
_ => diag.struct_span_err(attr_sp, msg).forget_guarantee(), _ => dcx.struct_span_err(attr_sp, msg).forget_guarantee(),
}; };
if let Some(item) = item { if let Some(item) = item {
err.span_label( err.span_label(
@ -466,7 +466,7 @@ fn should_ignore_message(i: &ast::Item) -> Option<Symbol> {
fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic { fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic {
match attr::find_by_name(&i.attrs, sym::should_panic) { match attr::find_by_name(&i.attrs, sym::should_panic) {
Some(attr) => { Some(attr) => {
let sd = cx.sess.dcx(); let dcx = cx.sess.dcx();
match attr.meta_item_list() { match attr.meta_item_list() {
// Handle #[should_panic(expected = "foo")] // Handle #[should_panic(expected = "foo")]
@ -477,7 +477,7 @@ fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic {
.and_then(|mi| mi.meta_item()) .and_then(|mi| mi.meta_item())
.and_then(|mi| mi.value_str()); .and_then(|mi| mi.value_str());
if list.len() != 1 || msg.is_none() { if list.len() != 1 || msg.is_none() {
sd.struct_span_warn( dcx.struct_span_warn(
attr.span, attr.span,
"argument must be of the form: \ "argument must be of the form: \
`expected = \"error message\"`", `expected = \"error message\"`",
@ -535,30 +535,30 @@ fn check_test_signature(
f: &ast::Fn, f: &ast::Fn,
) -> Result<(), ErrorGuaranteed> { ) -> Result<(), ErrorGuaranteed> {
let has_should_panic_attr = attr::contains_name(&i.attrs, sym::should_panic); let has_should_panic_attr = attr::contains_name(&i.attrs, sym::should_panic);
let sd = cx.sess.dcx(); let dcx = cx.sess.dcx();
if let ast::Unsafe::Yes(span) = f.sig.header.unsafety { if let ast::Unsafe::Yes(span) = f.sig.header.unsafety {
return Err(sd.emit_err(errors::TestBadFn { span: i.span, cause: span, kind: "unsafe" })); return Err(dcx.emit_err(errors::TestBadFn { span: i.span, cause: span, kind: "unsafe" }));
} }
if let Some(coroutine_kind) = f.sig.header.coroutine_kind { if let Some(coroutine_kind) = f.sig.header.coroutine_kind {
match coroutine_kind { match coroutine_kind {
ast::CoroutineKind::Async { span, .. } => { ast::CoroutineKind::Async { span, .. } => {
return Err(sd.emit_err(errors::TestBadFn { return Err(dcx.emit_err(errors::TestBadFn {
span: i.span, span: i.span,
cause: span, cause: span,
kind: "async", kind: "async",
})); }));
} }
ast::CoroutineKind::Gen { span, .. } => { ast::CoroutineKind::Gen { span, .. } => {
return Err(sd.emit_err(errors::TestBadFn { return Err(dcx.emit_err(errors::TestBadFn {
span: i.span, span: i.span,
cause: span, cause: span,
kind: "gen", kind: "gen",
})); }));
} }
ast::CoroutineKind::AsyncGen { span, .. } => { ast::CoroutineKind::AsyncGen { span, .. } => {
return Err(sd.emit_err(errors::TestBadFn { return Err(dcx.emit_err(errors::TestBadFn {
span: i.span, span: i.span,
cause: span, cause: span,
kind: "async gen", kind: "async gen",
@ -576,15 +576,15 @@ fn check_test_signature(
}; };
if !f.sig.decl.inputs.is_empty() { if !f.sig.decl.inputs.is_empty() {
return Err(sd.span_err(i.span, "functions used as tests can not have any arguments")); return Err(dcx.span_err(i.span, "functions used as tests can not have any arguments"));
} }
if has_should_panic_attr && has_output { if has_should_panic_attr && has_output {
return Err(sd.span_err(i.span, "functions using `#[should_panic]` must return `()`")); return Err(dcx.span_err(i.span, "functions using `#[should_panic]` must return `()`"));
} }
if f.generics.params.iter().any(|param| !matches!(param.kind, GenericParamKind::Lifetime)) { if f.generics.params.iter().any(|param| !matches!(param.kind, GenericParamKind::Lifetime)) {
return Err(sd.span_err( return Err(dcx.span_err(
i.span, i.span,
"functions used as tests can not have any non-lifetime generic parameters", "functions used as tests can not have any non-lifetime generic parameters",
)); ));

View File

@ -47,7 +47,7 @@ pub fn inject(
features: &Features, features: &Features,
resolver: &mut dyn ResolverExpand, resolver: &mut dyn ResolverExpand,
) { ) {
let span_diagnostic = sess.dcx(); let dcx = sess.dcx();
let panic_strategy = sess.panic_strategy(); let panic_strategy = sess.panic_strategy();
let platform_panic_strategy = sess.target.panic_strategy; let platform_panic_strategy = sess.target.panic_strategy;
@ -60,7 +60,7 @@ pub fn inject(
// Do this here so that the test_runner crate attribute gets marked as used // Do this here so that the test_runner crate attribute gets marked as used
// even in non-test builds // even in non-test builds
let test_runner = get_test_runner(span_diagnostic, krate); let test_runner = get_test_runner(dcx, krate);
if sess.is_test_crate() { if sess.is_test_crate() {
let panic_strategy = match (panic_strategy, sess.opts.unstable_opts.panic_abort_tests) { let panic_strategy = match (panic_strategy, sess.opts.unstable_opts.panic_abort_tests) {
@ -70,7 +70,7 @@ pub fn inject(
// Silently allow compiling with panic=abort on these platforms, // Silently allow compiling with panic=abort on these platforms,
// but with old behavior (abort if a test fails). // but with old behavior (abort if a test fails).
} else { } else {
span_diagnostic.emit_err(errors::TestsNotSupport {}); dcx.emit_err(errors::TestsNotSupport {});
} }
PanicStrategy::Unwind PanicStrategy::Unwind
} }

View File

@ -176,10 +176,10 @@ pub(crate) fn compile_fn(
match module.define_function(codegened_func.func_id, context) { match module.define_function(codegened_func.func_id, context) {
Ok(()) => {} Ok(()) => {}
Err(ModuleError::Compilation(CodegenError::ImplLimitExceeded)) => { Err(ModuleError::Compilation(CodegenError::ImplLimitExceeded)) => {
let handler = rustc_session::EarlyDiagCtxt::new( let early_dcx = rustc_session::EarlyDiagCtxt::new(
rustc_session::config::ErrorOutputType::default(), rustc_session::config::ErrorOutputType::default(),
); );
handler.early_error(format!( early_dcx.early_error(format!(
"backend implementation limit exceeded while compiling {name}", "backend implementation limit exceeded while compiling {name}",
name = codegened_func.symbol_name name = codegened_func.symbol_name
)); ));

View File

@ -200,18 +200,11 @@ pub(crate) fn run_fat(
modules: Vec<FatLtoInput<LlvmCodegenBackend>>, modules: Vec<FatLtoInput<LlvmCodegenBackend>>,
cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>, cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
) -> Result<LtoModuleCodegen<LlvmCodegenBackend>, FatalError> { ) -> Result<LtoModuleCodegen<LlvmCodegenBackend>, FatalError> {
let diag_handler = cgcx.create_dcx(); let dcx = cgcx.create_dcx();
let (symbols_below_threshold, upstream_modules) = prepare_lto(cgcx, &diag_handler)?; let (symbols_below_threshold, upstream_modules) = prepare_lto(cgcx, &dcx)?;
let symbols_below_threshold = let symbols_below_threshold =
symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>(); symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
fat_lto( fat_lto(cgcx, &dcx, modules, cached_modules, upstream_modules, &symbols_below_threshold)
cgcx,
&diag_handler,
modules,
cached_modules,
upstream_modules,
&symbols_below_threshold,
)
} }
/// Performs thin LTO by performing necessary global analysis and returning two /// Performs thin LTO by performing necessary global analysis and returning two
@ -222,8 +215,8 @@ pub(crate) fn run_thin(
modules: Vec<(String, ThinBuffer)>, modules: Vec<(String, ThinBuffer)>,
cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>, cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
) -> Result<(Vec<LtoModuleCodegen<LlvmCodegenBackend>>, Vec<WorkProduct>), FatalError> { ) -> Result<(Vec<LtoModuleCodegen<LlvmCodegenBackend>>, Vec<WorkProduct>), FatalError> {
let diag_handler = cgcx.create_dcx(); let dcx = cgcx.create_dcx();
let (symbols_below_threshold, upstream_modules) = prepare_lto(cgcx, &diag_handler)?; let (symbols_below_threshold, upstream_modules) = prepare_lto(cgcx, &dcx)?;
let symbols_below_threshold = let symbols_below_threshold =
symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>(); symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
if cgcx.opts.cg.linker_plugin_lto.enabled() { if cgcx.opts.cg.linker_plugin_lto.enabled() {
@ -232,14 +225,7 @@ pub(crate) fn run_thin(
is deferred to the linker" is deferred to the linker"
); );
} }
thin_lto( thin_lto(cgcx, &dcx, modules, upstream_modules, cached_modules, &symbols_below_threshold)
cgcx,
&diag_handler,
modules,
upstream_modules,
cached_modules,
&symbols_below_threshold,
)
} }
pub(crate) fn prepare_thin(module: ModuleCodegen<ModuleLlvm>) -> (String, ThinBuffer) { pub(crate) fn prepare_thin(module: ModuleCodegen<ModuleLlvm>) -> (String, ThinBuffer) {
@ -714,11 +700,11 @@ pub unsafe fn optimize_thin_module(
thin_module: ThinModule<LlvmCodegenBackend>, thin_module: ThinModule<LlvmCodegenBackend>,
cgcx: &CodegenContext<LlvmCodegenBackend>, cgcx: &CodegenContext<LlvmCodegenBackend>,
) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> { ) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
let diag_handler = cgcx.create_dcx(); let dcx = cgcx.create_dcx();
let module_name = &thin_module.shared.module_names[thin_module.idx]; let module_name = &thin_module.shared.module_names[thin_module.idx];
let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, module_name.to_str().unwrap()); let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, module_name.to_str().unwrap());
let tm = (cgcx.tm_factory)(tm_factory_config).map_err(|e| write::llvm_err(&diag_handler, e))?; let tm = (cgcx.tm_factory)(tm_factory_config).map_err(|e| write::llvm_err(&dcx, e))?;
// Right now the implementation we've got only works over serialized // Right now the implementation we've got only works over serialized
// modules, so we create a fresh new LLVM context and parse the module // modules, so we create a fresh new LLVM context and parse the module
@ -726,7 +712,7 @@ pub unsafe fn optimize_thin_module(
// crates but for locally codegened modules we may be able to reuse // crates but for locally codegened modules we may be able to reuse
// that LLVM Context and Module. // that LLVM Context and Module.
let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names); let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
let llmod_raw = parse_module(llcx, module_name, thin_module.data(), &diag_handler)? as *const _; let llmod_raw = parse_module(llcx, module_name, thin_module.data(), &dcx)? as *const _;
let mut module = ModuleCodegen { let mut module = ModuleCodegen {
module_llvm: ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }, module_llvm: ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) },
name: thin_module.name().to_string(), name: thin_module.name().to_string(),
@ -749,7 +735,7 @@ pub unsafe fn optimize_thin_module(
let _timer = let _timer =
cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_rename", thin_module.name()); cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_rename", thin_module.name());
if !llvm::LLVMRustPrepareThinLTORename(thin_module.shared.data.0, llmod, target) { if !llvm::LLVMRustPrepareThinLTORename(thin_module.shared.data.0, llmod, target) {
return Err(write::llvm_err(&diag_handler, LlvmError::PrepareThinLtoModule)); return Err(write::llvm_err(&dcx, LlvmError::PrepareThinLtoModule));
} }
save_temp_bitcode(cgcx, &module, "thin-lto-after-rename"); save_temp_bitcode(cgcx, &module, "thin-lto-after-rename");
} }
@ -759,7 +745,7 @@ pub unsafe fn optimize_thin_module(
.prof .prof
.generic_activity_with_arg("LLVM_thin_lto_resolve_weak", thin_module.name()); .generic_activity_with_arg("LLVM_thin_lto_resolve_weak", thin_module.name());
if !llvm::LLVMRustPrepareThinLTOResolveWeak(thin_module.shared.data.0, llmod) { if !llvm::LLVMRustPrepareThinLTOResolveWeak(thin_module.shared.data.0, llmod) {
return Err(write::llvm_err(&diag_handler, LlvmError::PrepareThinLtoModule)); return Err(write::llvm_err(&dcx, LlvmError::PrepareThinLtoModule));
} }
save_temp_bitcode(cgcx, &module, "thin-lto-after-resolve"); save_temp_bitcode(cgcx, &module, "thin-lto-after-resolve");
} }
@ -769,7 +755,7 @@ pub unsafe fn optimize_thin_module(
.prof .prof
.generic_activity_with_arg("LLVM_thin_lto_internalize", thin_module.name()); .generic_activity_with_arg("LLVM_thin_lto_internalize", thin_module.name());
if !llvm::LLVMRustPrepareThinLTOInternalize(thin_module.shared.data.0, llmod) { if !llvm::LLVMRustPrepareThinLTOInternalize(thin_module.shared.data.0, llmod) {
return Err(write::llvm_err(&diag_handler, LlvmError::PrepareThinLtoModule)); return Err(write::llvm_err(&dcx, LlvmError::PrepareThinLtoModule));
} }
save_temp_bitcode(cgcx, &module, "thin-lto-after-internalize"); save_temp_bitcode(cgcx, &module, "thin-lto-after-internalize");
} }
@ -778,7 +764,7 @@ pub unsafe fn optimize_thin_module(
let _timer = let _timer =
cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_import", thin_module.name()); cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_import", thin_module.name());
if !llvm::LLVMRustPrepareThinLTOImport(thin_module.shared.data.0, llmod, target) { if !llvm::LLVMRustPrepareThinLTOImport(thin_module.shared.data.0, llmod, target) {
return Err(write::llvm_err(&diag_handler, LlvmError::PrepareThinLtoModule)); return Err(write::llvm_err(&dcx, LlvmError::PrepareThinLtoModule));
} }
save_temp_bitcode(cgcx, &module, "thin-lto-after-import"); save_temp_bitcode(cgcx, &module, "thin-lto-after-import");
} }
@ -790,7 +776,7 @@ pub unsafe fn optimize_thin_module(
// little differently. // little differently.
{ {
info!("running thin lto passes over {}", module.name); info!("running thin lto passes over {}", module.name);
run_pass_manager(cgcx, &diag_handler, &mut module, true)?; run_pass_manager(cgcx, &dcx, &mut module, true)?;
save_temp_bitcode(cgcx, &module, "thin-lto-after-pm"); save_temp_bitcode(cgcx, &module, "thin-lto-after-pm");
} }
} }

View File

@ -427,7 +427,7 @@ unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void
if user.is_null() { if user.is_null() {
return; return;
} }
let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &DiagCtxt)); let (cgcx, dcx) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &DiagCtxt));
match llvm::diagnostic::Diagnostic::unpack(info) { match llvm::diagnostic::Diagnostic::unpack(info) {
llvm::diagnostic::InlineAsm(inline) => { llvm::diagnostic::InlineAsm(inline) => {
@ -435,7 +435,7 @@ unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void
} }
llvm::diagnostic::Optimization(opt) => { llvm::diagnostic::Optimization(opt) => {
diag_handler.emit_note(FromLlvmOptimizationDiag { dcx.emit_note(FromLlvmOptimizationDiag {
filename: &opt.filename, filename: &opt.filename,
line: opt.line, line: opt.line,
column: opt.column, column: opt.column,
@ -457,14 +457,14 @@ unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void
llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s) llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
}) })
.expect("non-UTF8 diagnostic"); .expect("non-UTF8 diagnostic");
diag_handler.emit_warning(FromLlvmDiag { message }); dcx.emit_warning(FromLlvmDiag { message });
} }
llvm::diagnostic::Unsupported(diagnostic_ref) => { llvm::diagnostic::Unsupported(diagnostic_ref) => {
let message = llvm::build_string(|s| { let message = llvm::build_string(|s| {
llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s) llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
}) })
.expect("non-UTF8 diagnostic"); .expect("non-UTF8 diagnostic");
diag_handler.emit_err(FromLlvmDiag { message }); dcx.emit_err(FromLlvmDiag { message });
} }
llvm::diagnostic::UnknownDiagnostic(..) => {} llvm::diagnostic::UnknownDiagnostic(..) => {}
} }

View File

@ -231,8 +231,8 @@ impl WriteBackendMethods for LlvmCodegenBackend {
cgcx: &CodegenContext<Self>, cgcx: &CodegenContext<Self>,
module: &mut ModuleCodegen<Self::Module>, module: &mut ModuleCodegen<Self::Module>,
) -> Result<(), FatalError> { ) -> Result<(), FatalError> {
let diag_handler = cgcx.create_dcx(); let dcx = cgcx.create_dcx();
back::lto::run_pass_manager(cgcx, &diag_handler, module, false) back::lto::run_pass_manager(cgcx, &dcx, module, false)
} }
unsafe fn optimize_thin( unsafe fn optimize_thin(
cgcx: &CodegenContext<Self>, cgcx: &CodegenContext<Self>,

View File

@ -825,10 +825,10 @@ fn execute_optimize_work_item<B: ExtraBackendMethods>(
module: ModuleCodegen<B::Module>, module: ModuleCodegen<B::Module>,
module_config: &ModuleConfig, module_config: &ModuleConfig,
) -> Result<WorkItemResult<B>, FatalError> { ) -> Result<WorkItemResult<B>, FatalError> {
let diag_handler = cgcx.create_dcx(); let dcx = cgcx.create_dcx();
unsafe { unsafe {
B::optimize(cgcx, &diag_handler, &module, module_config)?; B::optimize(cgcx, &dcx, &module, module_config)?;
} }
// After we've done the initial round of optimizations we need to // After we've done the initial round of optimizations we need to
@ -935,13 +935,13 @@ fn finish_intra_module_work<B: ExtraBackendMethods>(
module: ModuleCodegen<B::Module>, module: ModuleCodegen<B::Module>,
module_config: &ModuleConfig, module_config: &ModuleConfig,
) -> Result<WorkItemResult<B>, FatalError> { ) -> Result<WorkItemResult<B>, FatalError> {
let diag_handler = cgcx.create_dcx(); let dcx = cgcx.create_dcx();
if !cgcx.opts.unstable_opts.combine_cgu if !cgcx.opts.unstable_opts.combine_cgu
|| module.kind == ModuleKind::Metadata || module.kind == ModuleKind::Metadata
|| module.kind == ModuleKind::Allocator || module.kind == ModuleKind::Allocator
{ {
let module = unsafe { B::codegen(cgcx, &diag_handler, module, module_config)? }; let module = unsafe { B::codegen(cgcx, &dcx, module, module_config)? };
Ok(WorkItemResult::Finished(module)) Ok(WorkItemResult::Finished(module))
} else { } else {
Ok(WorkItemResult::NeedsLink(module)) Ok(WorkItemResult::NeedsLink(module))
@ -1591,11 +1591,10 @@ fn start_executing_work<B: ExtraBackendMethods>(
let needs_link = mem::take(&mut needs_link); let needs_link = mem::take(&mut needs_link);
if !needs_link.is_empty() { if !needs_link.is_empty() {
assert!(compiled_modules.is_empty()); assert!(compiled_modules.is_empty());
let diag_handler = cgcx.create_dcx(); let dcx = cgcx.create_dcx();
let module = B::run_link(&cgcx, &diag_handler, needs_link).map_err(|_| ())?; let module = B::run_link(&cgcx, &dcx, needs_link).map_err(|_| ())?;
let module = unsafe { let module = unsafe {
B::codegen(&cgcx, &diag_handler, module, cgcx.config(ModuleKind::Regular)) B::codegen(&cgcx, &dcx, module, cgcx.config(ModuleKind::Regular)).map_err(|_| ())?
.map_err(|_| ())?
}; };
compiled_modules.push(module); compiled_modules.push(module);
} }
@ -1838,13 +1837,13 @@ impl SharedEmitterMain {
match message { match message {
Ok(SharedEmitterMessage::Diagnostic(diag)) => { Ok(SharedEmitterMessage::Diagnostic(diag)) => {
let handler = sess.dcx(); let dcx = sess.dcx();
let mut d = rustc_errors::Diagnostic::new_with_messages(diag.lvl, diag.msg); let mut d = rustc_errors::Diagnostic::new_with_messages(diag.lvl, diag.msg);
if let Some(code) = diag.code { if let Some(code) = diag.code {
d.code(code); d.code(code);
} }
d.replace_args(diag.args); d.replace_args(diag.args);
handler.emit_diagnostic(d); dcx.emit_diagnostic(d);
} }
Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => { Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
let msg = msg.strip_prefix("error: ").unwrap_or(&msg).to_string(); let msg = msg.strip_prefix("error: ").unwrap_or(&msg).to_string();

View File

@ -440,10 +440,10 @@ pub trait ReportErrorExt {
{ {
ty::tls::with(move |tcx| { ty::tls::with(move |tcx| {
let mut builder = tcx.sess.struct_allow(DiagnosticMessage::Str(String::new().into())); let mut builder = tcx.sess.struct_allow(DiagnosticMessage::Str(String::new().into()));
let handler = tcx.sess.dcx(); let dcx = tcx.sess.dcx();
let message = self.diagnostic_message(); let message = self.diagnostic_message();
self.add_args(handler, &mut builder); self.add_args(dcx, &mut builder);
let s = handler.eagerly_translate_to_string(message, builder.args()); let s = dcx.eagerly_translate_to_string(message, builder.args());
builder.cancel(); builder.cancel();
s s
}) })

View File

@ -473,12 +473,12 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
backtrace.print_backtrace(); backtrace.print_backtrace();
// FIXME(fee1-dead), HACK: we want to use the error as title therefore we can just extract the // FIXME(fee1-dead), HACK: we want to use the error as title therefore we can just extract the
// label and arguments from the InterpError. // label and arguments from the InterpError.
let handler = self.tcx.sess.dcx(); let dcx = self.tcx.sess.dcx();
#[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::untranslatable_diagnostic)]
let mut diag = self.tcx.sess.struct_allow(""); let mut diag = self.tcx.sess.struct_allow("");
let msg = e.diagnostic_message(); let msg = e.diagnostic_message();
e.add_args(handler, &mut diag); e.add_args(dcx, &mut diag);
let s = handler.eagerly_translate_to_string(msg, diag.args()); let s = dcx.eagerly_translate_to_string(msg, diag.args());
diag.cancel(); diag.cancel();
s s
} }

View File

@ -291,7 +291,7 @@ fn run_compiler(
>, >,
using_internal_features: Arc<std::sync::atomic::AtomicBool>, using_internal_features: Arc<std::sync::atomic::AtomicBool>,
) -> interface::Result<()> { ) -> interface::Result<()> {
let mut default_handler = EarlyDiagCtxt::new(ErrorOutputType::default()); let mut default_early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
// Throw away the first argument, the name of the binary. // Throw away the first argument, the name of the binary.
// In case of at_args being empty, as might be the case by // In case of at_args being empty, as might be the case by
@ -303,14 +303,14 @@ fn run_compiler(
// the compiler with @empty_file as argv[0] and no more arguments. // the compiler with @empty_file as argv[0] and no more arguments.
let at_args = at_args.get(1..).unwrap_or_default(); let at_args = at_args.get(1..).unwrap_or_default();
let args = args::arg_expand_all(&default_handler, at_args); let args = args::arg_expand_all(&default_early_dcx, at_args);
let Some(matches) = handle_options(&default_handler, &args) else { return Ok(()) }; let Some(matches) = handle_options(&default_early_dcx, &args) else { return Ok(()) };
let sopts = config::build_session_options(&mut default_handler, &matches); let sopts = config::build_session_options(&mut default_early_dcx, &matches);
if let Some(ref code) = matches.opt_str("explain") { if let Some(ref code) = matches.opt_str("explain") {
handle_explain(&default_handler, diagnostics_registry(), code, sopts.color); handle_explain(&default_early_dcx, diagnostics_registry(), code, sopts.color);
return Ok(()); return Ok(());
} }
@ -336,7 +336,7 @@ fn run_compiler(
expanded_args: args, expanded_args: args,
}; };
let has_input = match make_input(&default_handler, &matches.free) { let has_input = match make_input(&default_early_dcx, &matches.free) {
Err(reported) => return Err(reported), Err(reported) => return Err(reported),
Ok(Some(input)) => { Ok(Some(input)) => {
config.input = input; config.input = input;
@ -345,7 +345,7 @@ fn run_compiler(
Ok(None) => match matches.free.len() { Ok(None) => match matches.free.len() {
0 => false, // no input: we will exit early 0 => false, // no input: we will exit early
1 => panic!("make_input should have provided valid inputs"), 1 => panic!("make_input should have provided valid inputs"),
_ => default_handler.early_error(format!( _ => default_early_dcx.early_error(format!(
"multiple input filenames provided (first two filenames are `{}` and `{}`)", "multiple input filenames provided (first two filenames are `{}` and `{}`)",
matches.free[0], matches.free[1], matches.free[0], matches.free[1],
)), )),
@ -354,8 +354,8 @@ fn run_compiler(
callbacks.config(&mut config); callbacks.config(&mut config);
default_handler.abort_if_errors(); default_early_dcx.abort_if_errors();
drop(default_handler); drop(default_early_dcx);
interface::run_compiler(config, |compiler| { interface::run_compiler(config, |compiler| {
let sess = &compiler.sess; let sess = &compiler.sess;
@ -369,18 +369,18 @@ fn run_compiler(
return sess.compile_status(); return sess.compile_status();
} }
let handler = EarlyDiagCtxt::new(sess.opts.error_format); let early_dcx = EarlyDiagCtxt::new(sess.opts.error_format);
if print_crate_info(&handler, codegen_backend, sess, has_input) == Compilation::Stop { if print_crate_info(&early_dcx, codegen_backend, sess, has_input) == Compilation::Stop {
return sess.compile_status(); return sess.compile_status();
} }
if !has_input { if !has_input {
handler.early_error("no input filename given"); // this is fatal early_dcx.early_error("no input filename given"); // this is fatal
} }
if !sess.opts.unstable_opts.ls.is_empty() { if !sess.opts.unstable_opts.ls.is_empty() {
list_metadata(&handler, sess, &*codegen_backend.metadata_loader()); list_metadata(&early_dcx, sess, &*codegen_backend.metadata_loader());
return sess.compile_status(); return sess.compile_status();
} }
@ -852,12 +852,12 @@ fn print_crate_info(
/// Prints version information /// Prints version information
/// ///
/// NOTE: this is a macro to support drivers built at a different time than the main `rustc_driver` crate. /// NOTE: this is a macro to support drivers built at a different time than the main `rustc_driver` crate.
pub macro version($handler: expr, $binary: literal, $matches: expr) { pub macro version($early_dcx: expr, $binary: literal, $matches: expr) {
fn unw(x: Option<&str>) -> &str { fn unw(x: Option<&str>) -> &str {
x.unwrap_or("unknown") x.unwrap_or("unknown")
} }
$crate::version_at_macro_invocation( $crate::version_at_macro_invocation(
$handler, $early_dcx,
$binary, $binary,
$matches, $matches,
unw(option_env!("CFG_VERSION")), unw(option_env!("CFG_VERSION")),
@ -1332,8 +1332,8 @@ pub fn install_ice_hook(
if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)") if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)")
{ {
// the error code is already going to be reported when the panic unwinds up the stack // the error code is already going to be reported when the panic unwinds up the stack
let handler = EarlyDiagCtxt::new(ErrorOutputType::default()); let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
let _ = handler.early_error_no_abort(msg.clone()); let _ = early_dcx.early_error_no_abort(msg.clone());
return; return;
} }
}; };
@ -1396,20 +1396,20 @@ fn report_ice(
rustc_errors::ColorConfig::Auto, rustc_errors::ColorConfig::Auto,
fallback_bundle, fallback_bundle,
)); ));
let handler = rustc_errors::DiagCtxt::with_emitter(emitter); let dcx = rustc_errors::DiagCtxt::with_emitter(emitter);
// a .span_bug or .bug call has already printed what // a .span_bug or .bug call has already printed what
// it wants to print. // it wants to print.
if !info.payload().is::<rustc_errors::ExplicitBug>() if !info.payload().is::<rustc_errors::ExplicitBug>()
&& !info.payload().is::<rustc_errors::DelayedBugPanic>() && !info.payload().is::<rustc_errors::DelayedBugPanic>()
{ {
handler.emit_err(session_diagnostics::Ice); dcx.emit_err(session_diagnostics::Ice);
} }
if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) { if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
handler.emit_note(session_diagnostics::IceBugReportInternalFeature); dcx.emit_note(session_diagnostics::IceBugReportInternalFeature);
} else { } else {
handler.emit_note(session_diagnostics::IceBugReport { bug_report_url }); dcx.emit_note(session_diagnostics::IceBugReport { bug_report_url });
} }
let version = util::version_str!().unwrap_or("unknown_version"); let version = util::version_str!().unwrap_or("unknown_version");
@ -1421,7 +1421,7 @@ fn report_ice(
// Create the ICE dump target file. // Create the ICE dump target file.
match crate::fs::File::options().create(true).append(true).open(&path) { match crate::fs::File::options().create(true).append(true).open(&path) {
Ok(mut file) => { Ok(mut file) => {
handler.emit_note(session_diagnostics::IcePath { path: path.clone() }); dcx.emit_note(session_diagnostics::IcePath { path: path.clone() });
if FIRST_PANIC.swap(false, Ordering::SeqCst) { if FIRST_PANIC.swap(false, Ordering::SeqCst) {
let _ = write!(file, "\n\nrustc version: {version}\nplatform: {triple}"); let _ = write!(file, "\n\nrustc version: {version}\nplatform: {triple}");
} }
@ -1429,26 +1429,26 @@ fn report_ice(
} }
Err(err) => { Err(err) => {
// The path ICE couldn't be written to disk, provide feedback to the user as to why. // The path ICE couldn't be written to disk, provide feedback to the user as to why.
handler.emit_warning(session_diagnostics::IcePathError { dcx.emit_warning(session_diagnostics::IcePathError {
path: path.clone(), path: path.clone(),
error: err.to_string(), error: err.to_string(),
env_var: std::env::var_os("RUSTC_ICE") env_var: std::env::var_os("RUSTC_ICE")
.map(PathBuf::from) .map(PathBuf::from)
.map(|env_var| session_diagnostics::IcePathErrorEnv { env_var }), .map(|env_var| session_diagnostics::IcePathErrorEnv { env_var }),
}); });
handler.emit_note(session_diagnostics::IceVersion { version, triple }); dcx.emit_note(session_diagnostics::IceVersion { version, triple });
None None
} }
} }
} else { } else {
handler.emit_note(session_diagnostics::IceVersion { version, triple }); dcx.emit_note(session_diagnostics::IceVersion { version, triple });
None None
}; };
if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() { if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
handler.emit_note(session_diagnostics::IceFlags { flags: flags.join(" ") }); dcx.emit_note(session_diagnostics::IceFlags { flags: flags.join(" ") });
if excluded_cargo_defaults { if excluded_cargo_defaults {
handler.emit_note(session_diagnostics::IceExcludeCargoDefaults); dcx.emit_note(session_diagnostics::IceExcludeCargoDefaults);
} }
} }
@ -1457,11 +1457,11 @@ fn report_ice(
let num_frames = if backtrace { None } else { Some(2) }; let num_frames = if backtrace { None } else { Some(2) };
interface::try_print_query_stack(&handler, num_frames, file); interface::try_print_query_stack(&dcx, num_frames, file);
// We don't trust this callback not to panic itself, so run it at the end after we're sure we've // We don't trust this callback not to panic itself, so run it at the end after we're sure we've
// printed all the relevant info. // printed all the relevant info.
extra_info(&handler); extra_info(&dcx);
#[cfg(windows)] #[cfg(windows)]
if env::var("RUSTC_BREAK_ON_ICE").is_ok() { if env::var("RUSTC_BREAK_ON_ICE").is_ok() {
@ -1489,9 +1489,9 @@ pub fn main() -> ! {
let start_time = Instant::now(); let start_time = Instant::now();
let start_rss = get_resident_set_size(); let start_rss = get_resident_set_size();
let handler = EarlyDiagCtxt::new(ErrorOutputType::default()); let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
init_rustc_env_logger(&handler); init_rustc_env_logger(&early_dcx);
signal_handler::install(); signal_handler::install();
let mut callbacks = TimePassesCallbacks::default(); let mut callbacks = TimePassesCallbacks::default();
let using_internal_features = install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ()); let using_internal_features = install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
@ -1500,7 +1500,7 @@ pub fn main() -> ! {
.enumerate() .enumerate()
.map(|(i, arg)| { .map(|(i, arg)| {
arg.into_string().unwrap_or_else(|arg| { arg.into_string().unwrap_or_else(|arg| {
handler.early_error(format!("argument {i} is not valid Unicode: {arg:?}")) early_dcx.early_error(format!("argument {i} is not valid Unicode: {arg:?}"))
}) })
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();

View File

@ -129,10 +129,10 @@ impl EmissionGuarantee for ErrorGuaranteed {
fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self { fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
match db.inner.state { match db.inner.state {
// First `.emit()` call, the `&DiagCtxt` is still available. // First `.emit()` call, the `&DiagCtxt` is still available.
DiagnosticBuilderState::Emittable(handler) => { DiagnosticBuilderState::Emittable(dcx) => {
db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation; db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
let guar = handler.emit_diagnostic_without_consuming(&mut db.inner.diagnostic); let guar = dcx.emit_diagnostic_without_consuming(&mut db.inner.diagnostic);
// Only allow a guarantee if the `level` wasn't switched to a // Only allow a guarantee if the `level` wasn't switched to a
// non-error - the field isn't `pub`, but the whole `Diagnostic` // non-error - the field isn't `pub`, but the whole `Diagnostic`
@ -178,10 +178,10 @@ impl EmissionGuarantee for () {
fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self { fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
match db.inner.state { match db.inner.state {
// First `.emit()` call, the `&DiagCtxt` is still available. // First `.emit()` call, the `&DiagCtxt` is still available.
DiagnosticBuilderState::Emittable(handler) => { DiagnosticBuilderState::Emittable(dcx) => {
db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation; db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
handler.emit_diagnostic_without_consuming(&mut db.inner.diagnostic); dcx.emit_diagnostic_without_consuming(&mut db.inner.diagnostic);
} }
// `.emit()` was previously called, disallowed from repeating it. // `.emit()` was previously called, disallowed from repeating it.
DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {} DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
@ -205,9 +205,9 @@ impl EmissionGuarantee for Noted {
fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self { fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
match db.inner.state { match db.inner.state {
// First `.emit()` call, the `&DiagCtxt` is still available. // First `.emit()` call, the `&DiagCtxt` is still available.
DiagnosticBuilderState::Emittable(handler) => { DiagnosticBuilderState::Emittable(dcx) => {
db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation; db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
handler.emit_diagnostic_without_consuming(&mut db.inner.diagnostic); dcx.emit_diagnostic_without_consuming(&mut db.inner.diagnostic);
} }
// `.emit()` was previously called, disallowed from repeating it. // `.emit()` was previously called, disallowed from repeating it.
DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {} DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
@ -233,10 +233,10 @@ impl EmissionGuarantee for Bug {
fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self { fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
match db.inner.state { match db.inner.state {
// First `.emit()` call, the `&DiagCtxt` is still available. // First `.emit()` call, the `&DiagCtxt` is still available.
DiagnosticBuilderState::Emittable(handler) => { DiagnosticBuilderState::Emittable(dcx) => {
db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation; db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
handler.emit_diagnostic_without_consuming(&mut db.inner.diagnostic); dcx.emit_diagnostic_without_consuming(&mut db.inner.diagnostic);
} }
// `.emit()` was previously called, disallowed from repeating it. // `.emit()` was previously called, disallowed from repeating it.
DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {} DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
@ -257,10 +257,10 @@ impl EmissionGuarantee for ! {
fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self { fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
match db.inner.state { match db.inner.state {
// First `.emit()` call, the `&DiagCtxt` is still available. // First `.emit()` call, the `&DiagCtxt` is still available.
DiagnosticBuilderState::Emittable(handler) => { DiagnosticBuilderState::Emittable(dcx) => {
db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation; db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
handler.emit_diagnostic_without_consuming(&mut db.inner.diagnostic); dcx.emit_diagnostic_without_consuming(&mut db.inner.diagnostic);
} }
// `.emit()` was previously called, disallowed from repeating it. // `.emit()` was previously called, disallowed from repeating it.
DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {} DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
@ -281,10 +281,10 @@ impl EmissionGuarantee for rustc_span::fatal_error::FatalError {
fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self { fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self {
match db.inner.state { match db.inner.state {
// First `.emit()` call, the `&DiagCtxt` is still available. // First `.emit()` call, the `&DiagCtxt` is still available.
DiagnosticBuilderState::Emittable(handler) => { DiagnosticBuilderState::Emittable(dcx) => {
db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation; db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation;
handler.emit_diagnostic_without_consuming(&mut db.inner.diagnostic); dcx.emit_diagnostic_without_consuming(&mut db.inner.diagnostic);
} }
// `.emit()` was previously called, disallowed from repeating it. // `.emit()` was previously called, disallowed from repeating it.
DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {} DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {}
@ -410,17 +410,17 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
/// Converts the builder to a `Diagnostic` for later emission, /// Converts the builder to a `Diagnostic` for later emission,
/// unless handler has disabled such buffering, or `.emit()` was called. /// unless handler has disabled such buffering, or `.emit()` was called.
pub fn into_diagnostic(mut self) -> Option<(Diagnostic, &'a DiagCtxt)> { pub fn into_diagnostic(mut self) -> Option<(Diagnostic, &'a DiagCtxt)> {
let handler = match self.inner.state { let dcx = match self.inner.state {
// No `.emit()` calls, the `&DiagCtxt` is still available. // No `.emit()` calls, the `&DiagCtxt` is still available.
DiagnosticBuilderState::Emittable(handler) => handler, DiagnosticBuilderState::Emittable(dcx) => dcx,
// `.emit()` was previously called, nothing we can do. // `.emit()` was previously called, nothing we can do.
DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => { DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {
return None; return None;
} }
}; };
if handler.inner.lock().flags.dont_buffer_diagnostics if dcx.inner.lock().flags.dont_buffer_diagnostics
|| handler.inner.lock().flags.treat_err_as_bug.is_some() || dcx.inner.lock().flags.treat_err_as_bug.is_some()
{ {
self.emit(); self.emit();
return None; return None;
@ -437,13 +437,13 @@ impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
// actually emitted. // actually emitted.
debug!("buffer: diagnostic={:?}", diagnostic); debug!("buffer: diagnostic={:?}", diagnostic);
Some((diagnostic, handler)) Some((diagnostic, dcx))
} }
/// Retrieves the [`DiagCtxt`] if available /// Retrieves the [`DiagCtxt`] if available
pub fn dcx(&self) -> Option<&DiagCtxt> { pub fn dcx(&self) -> Option<&DiagCtxt> {
match self.inner.state { match self.inner.state {
DiagnosticBuilderState::Emittable(handler) => Some(handler), DiagnosticBuilderState::Emittable(dcx) => Some(dcx),
DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => None, DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => None,
} }
} }
@ -640,15 +640,15 @@ impl Drop for DiagnosticBuilderInner<'_> {
fn drop(&mut self) { fn drop(&mut self) {
match self.state { match self.state {
// No `.emit()` or `.cancel()` calls. // No `.emit()` or `.cancel()` calls.
DiagnosticBuilderState::Emittable(handler) => { DiagnosticBuilderState::Emittable(dcx) => {
if !panicking() { if !panicking() {
handler.emit_diagnostic(Diagnostic::new( dcx.emit_diagnostic(Diagnostic::new(
Level::Bug, Level::Bug,
DiagnosticMessage::from( DiagnosticMessage::from(
"the following error was constructed but not emitted", "the following error was constructed but not emitted",
), ),
)); ));
handler.emit_diagnostic_without_consuming(&mut self.diagnostic); dcx.emit_diagnostic_without_consuming(&mut self.diagnostic);
panic!("error was constructed but not emitted"); panic!("error was constructed but not emitted");
} }
} }

View File

@ -61,8 +61,8 @@ fn test_positions(code: &str, span: (u32, u32), expected_output: SpanTestData) {
); );
let span = Span::with_root_ctxt(BytePos(span.0), BytePos(span.1)); let span = Span::with_root_ctxt(BytePos(span.0), BytePos(span.1));
let handler = DiagCtxt::with_emitter(Box::new(je)); let dcx = DiagCtxt::with_emitter(Box::new(je));
handler.span_err(span, "foo"); dcx.span_err(span, "foo");
let bytes = output.lock().unwrap(); let bytes = output.lock().unwrap();
let actual_output = str::from_utf8(&bytes).unwrap(); let actual_output = str::from_utf8(&bytes).unwrap();

View File

@ -402,7 +402,7 @@ pub fn compile_declarative_macro(
}; };
let dummy_syn_ext = || (mk_syn_ext(Box::new(macro_rules_dummy_expander)), Vec::new()); let dummy_syn_ext = || (mk_syn_ext(Box::new(macro_rules_dummy_expander)), Vec::new());
let diag = &sess.parse_sess.dcx; let dcx = &sess.parse_sess.dcx;
let lhs_nm = Ident::new(sym::lhs, def.span); let lhs_nm = Ident::new(sym::lhs, def.span);
let rhs_nm = Ident::new(sym::rhs, def.span); let rhs_nm = Ident::new(sym::rhs, def.span);
let tt_spec = Some(NonterminalKind::TT); let tt_spec = Some(NonterminalKind::TT);
@ -560,10 +560,10 @@ pub fn compile_declarative_macro(
let (transparency, transparency_error) = attr::find_transparency(&def.attrs, macro_rules); let (transparency, transparency_error) = attr::find_transparency(&def.attrs, macro_rules);
match transparency_error { match transparency_error {
Some(TransparencyError::UnknownTransparency(value, span)) => { Some(TransparencyError::UnknownTransparency(value, span)) => {
diag.span_err(span, format!("unknown macro transparency: `{value}`")); dcx.span_err(span, format!("unknown macro transparency: `{value}`"));
} }
Some(TransparencyError::MultipleTransparencyAttrs(old_span, new_span)) => { Some(TransparencyError::MultipleTransparencyAttrs(old_span, new_span)) => {
diag.span_err(vec![old_span, new_span], "multiple macro transparency attributes"); dcx.span_err(vec![old_span, new_span], "multiple macro transparency attributes");
} }
None => {} None => {}
} }

View File

@ -33,8 +33,8 @@ fn create_test_handler() -> (DiagCtxt, Lrc<SourceMap>, Arc<Mutex<Vec<u8>>>) {
let emitter = EmitterWriter::new(Box::new(Shared { data: output.clone() }), fallback_bundle) let emitter = EmitterWriter::new(Box::new(Shared { data: output.clone() }), fallback_bundle)
.sm(Some(source_map.clone())) .sm(Some(source_map.clone()))
.diagnostic_width(Some(140)); .diagnostic_width(Some(140));
let handler = DiagCtxt::with_emitter(Box::new(emitter)); let dcx = DiagCtxt::with_emitter(Box::new(emitter));
(handler, source_map, output) (dcx, source_map, output)
} }
/// Returns the result of parsing the given string via the given callback. /// Returns the result of parsing the given string via the given callback.

View File

@ -413,21 +413,21 @@ enum TupleArgumentsFlag {
} }
fn fatally_break_rust(tcx: TyCtxt<'_>) { fn fatally_break_rust(tcx: TyCtxt<'_>) {
let handler = tcx.sess.dcx(); let dcx = tcx.sess.dcx();
handler.span_bug_no_panic( dcx.span_bug_no_panic(
MultiSpan::new(), MultiSpan::new(),
"It looks like you're trying to break rust; would you like some ICE?", "It looks like you're trying to break rust; would you like some ICE?",
); );
handler.note("the compiler expectedly panicked. this is a feature."); dcx.note("the compiler expectedly panicked. this is a feature.");
handler.note( dcx.note(
"we would appreciate a joke overview: \ "we would appreciate a joke overview: \
https://github.com/rust-lang/rust/issues/43162#issuecomment-320764675", https://github.com/rust-lang/rust/issues/43162#issuecomment-320764675",
); );
handler.note(format!("rustc {} running on {}", tcx.sess.cfg_version, config::host_triple(),)); dcx.note(format!("rustc {} running on {}", tcx.sess.cfg_version, config::host_triple(),));
if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() { if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
handler.note(format!("compiler flags: {}", flags.join(" "))); dcx.note(format!("compiler flags: {}", flags.join(" ")));
if excluded_cargo_defaults { if excluded_cargo_defaults {
handler.note("some of the compiler flags provided by cargo are hidden"); dcx.note("some of the compiler flags provided by cargo are hidden");
} }
} }
} }

View File

@ -315,8 +315,8 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
rustc_data_structures::sync::set_dyn_thread_safe_mode(config.opts.unstable_opts.threads > 1); rustc_data_structures::sync::set_dyn_thread_safe_mode(config.opts.unstable_opts.threads > 1);
// Check jobserver before run_in_thread_pool_with_globals, which call jobserver::acquire_thread // Check jobserver before run_in_thread_pool_with_globals, which call jobserver::acquire_thread
let early_handler = EarlyDiagCtxt::new(config.opts.error_format); let early_dcx = EarlyDiagCtxt::new(config.opts.error_format);
early_handler.initialize_checked_jobserver(); early_dcx.initialize_checked_jobserver();
util::run_in_thread_pool_with_globals( util::run_in_thread_pool_with_globals(
config.opts.edition, config.opts.edition,
@ -324,13 +324,13 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
|| { || {
crate::callbacks::setup_callbacks(); crate::callbacks::setup_callbacks();
let early_handler = EarlyDiagCtxt::new(config.opts.error_format); let early_dcx = EarlyDiagCtxt::new(config.opts.error_format);
let codegen_backend = if let Some(make_codegen_backend) = config.make_codegen_backend { let codegen_backend = if let Some(make_codegen_backend) = config.make_codegen_backend {
make_codegen_backend(&config.opts) make_codegen_backend(&config.opts)
} else { } else {
util::get_codegen_backend( util::get_codegen_backend(
&early_handler, &early_dcx,
&config.opts.maybe_sysroot, &config.opts.maybe_sysroot,
config.opts.unstable_opts.codegen_backend.as_deref(), config.opts.unstable_opts.codegen_backend.as_deref(),
) )
@ -347,7 +347,7 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
) { ) {
Ok(bundle) => bundle, Ok(bundle) => bundle,
Err(e) => { Err(e) => {
early_handler.early_error(format!("failed to load fluent bundle: {e}")); early_dcx.early_error(format!("failed to load fluent bundle: {e}"));
} }
}; };
@ -358,7 +358,7 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
let target_override = codegen_backend.target_override(&config.opts); let target_override = codegen_backend.target_override(&config.opts);
let mut sess = rustc_session::build_session( let mut sess = rustc_session::build_session(
early_handler, early_dcx,
config.opts, config.opts,
CompilerIO { CompilerIO {
input: config.input, input: config.input,

View File

@ -25,11 +25,11 @@ use std::path::{Path, PathBuf};
use std::sync::Arc; use std::sync::Arc;
fn mk_session(matches: getopts::Matches) -> (Session, Cfg) { fn mk_session(matches: getopts::Matches) -> (Session, Cfg) {
let mut early_handler = EarlyDiagCtxt::new(ErrorOutputType::default()); let mut early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
early_handler.initialize_checked_jobserver(); early_dcx.initialize_checked_jobserver();
let registry = registry::Registry::new(&[]); let registry = registry::Registry::new(&[]);
let sessopts = build_session_options(&mut early_handler, &matches); let sessopts = build_session_options(&mut early_dcx, &matches);
let temps_dir = sessopts.unstable_opts.temps_dir.as_deref().map(PathBuf::from); let temps_dir = sessopts.unstable_opts.temps_dir.as_deref().map(PathBuf::from);
let io = CompilerIO { let io = CompilerIO {
input: Input::Str { name: FileName::Custom(String::new()), input: String::new() }, input: Input::Str { name: FileName::Custom(String::new()), input: String::new() },
@ -38,7 +38,7 @@ fn mk_session(matches: getopts::Matches) -> (Session, Cfg) {
temps_dir, temps_dir,
}; };
let sess = build_session( let sess = build_session(
early_handler, early_dcx,
sessopts, sessopts,
io, io,
None, None,
@ -301,36 +301,36 @@ fn test_search_paths_tracking_hash_different_order() {
let mut v3 = Options::default(); let mut v3 = Options::default();
let mut v4 = Options::default(); let mut v4 = Options::default();
let handler = EarlyDiagCtxt::new(JSON); let early_dcx = EarlyDiagCtxt::new(JSON);
const JSON: ErrorOutputType = ErrorOutputType::Json { const JSON: ErrorOutputType = ErrorOutputType::Json {
pretty: false, pretty: false,
json_rendered: HumanReadableErrorType::Default(ColorConfig::Never), json_rendered: HumanReadableErrorType::Default(ColorConfig::Never),
}; };
// Reference // Reference
v1.search_paths.push(SearchPath::from_cli_opt(&handler, "native=abc")); v1.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "native=abc"));
v1.search_paths.push(SearchPath::from_cli_opt(&handler, "crate=def")); v1.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "crate=def"));
v1.search_paths.push(SearchPath::from_cli_opt(&handler, "dependency=ghi")); v1.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "dependency=ghi"));
v1.search_paths.push(SearchPath::from_cli_opt(&handler, "framework=jkl")); v1.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "framework=jkl"));
v1.search_paths.push(SearchPath::from_cli_opt(&handler, "all=mno")); v1.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "all=mno"));
v2.search_paths.push(SearchPath::from_cli_opt(&handler, "native=abc")); v2.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "native=abc"));
v2.search_paths.push(SearchPath::from_cli_opt(&handler, "dependency=ghi")); v2.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "dependency=ghi"));
v2.search_paths.push(SearchPath::from_cli_opt(&handler, "crate=def")); v2.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "crate=def"));
v2.search_paths.push(SearchPath::from_cli_opt(&handler, "framework=jkl")); v2.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "framework=jkl"));
v2.search_paths.push(SearchPath::from_cli_opt(&handler, "all=mno")); v2.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "all=mno"));
v3.search_paths.push(SearchPath::from_cli_opt(&handler, "crate=def")); v3.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "crate=def"));
v3.search_paths.push(SearchPath::from_cli_opt(&handler, "framework=jkl")); v3.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "framework=jkl"));
v3.search_paths.push(SearchPath::from_cli_opt(&handler, "native=abc")); v3.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "native=abc"));
v3.search_paths.push(SearchPath::from_cli_opt(&handler, "dependency=ghi")); v3.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "dependency=ghi"));
v3.search_paths.push(SearchPath::from_cli_opt(&handler, "all=mno")); v3.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "all=mno"));
v4.search_paths.push(SearchPath::from_cli_opt(&handler, "all=mno")); v4.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "all=mno"));
v4.search_paths.push(SearchPath::from_cli_opt(&handler, "native=abc")); v4.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "native=abc"));
v4.search_paths.push(SearchPath::from_cli_opt(&handler, "crate=def")); v4.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "crate=def"));
v4.search_paths.push(SearchPath::from_cli_opt(&handler, "dependency=ghi")); v4.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "dependency=ghi"));
v4.search_paths.push(SearchPath::from_cli_opt(&handler, "framework=jkl")); v4.search_paths.push(SearchPath::from_cli_opt(&early_dcx, "framework=jkl"));
assert_same_hash(&v1, &v2); assert_same_hash(&v1, &v2);
assert_same_hash(&v1, &v3); assert_same_hash(&v1, &v3);
@ -854,9 +854,9 @@ fn test_edition_parsing() {
let options = Options::default(); let options = Options::default();
assert!(options.edition == DEFAULT_EDITION); assert!(options.edition == DEFAULT_EDITION);
let mut handler = EarlyDiagCtxt::new(ErrorOutputType::default()); let mut early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
let matches = optgroups().parse(&["--edition=2018".to_string()]).unwrap(); let matches = optgroups().parse(&["--edition=2018".to_string()]).unwrap();
let sessopts = build_session_options(&mut handler, &matches); let sessopts = build_session_options(&mut early_dcx, &matches);
assert!(sessopts.edition == Edition::Edition2018) assert!(sessopts.edition == Edition::Edition2018)
} }

View File

@ -376,7 +376,7 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> {
return Ok(quote! {}); return Ok(quote! {});
} }
let handler = match &self.parent.kind { let dcx = match &self.parent.kind {
DiagnosticDeriveKind::Diagnostic { dcx } => dcx, DiagnosticDeriveKind::Diagnostic { dcx } => dcx,
DiagnosticDeriveKind::LintDiagnostic => { DiagnosticDeriveKind::LintDiagnostic => {
throw_invalid_attr!(attr, |diag| { throw_invalid_attr!(attr, |diag| {
@ -384,7 +384,7 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> {
}) })
} }
}; };
return Ok(quote! { #diag.eager_subdiagnostic(#handler, #binding); }); return Ok(quote! { #diag.eager_subdiagnostic(#dcx, #binding); });
} }
_ => (), _ => (),
} }

View File

@ -181,8 +181,8 @@ pub(crate) struct UnsafeOpInUnsafeFn {
impl<'a> DecorateLint<'a, ()> for UnsafeOpInUnsafeFn { impl<'a> DecorateLint<'a, ()> for UnsafeOpInUnsafeFn {
#[track_caller] #[track_caller]
fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) { fn decorate_lint<'b>(self, diag: &'b mut DiagnosticBuilder<'a, ()>) {
let handler = diag.dcx().expect("lint should not yet be emitted"); let dcx = diag.dcx().expect("lint should not yet be emitted");
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.span_label(self.details.span, self.details.label()); diag.span_label(self.details.span, self.details.label());
self.details.add_subdiagnostics(diag); self.details.add_subdiagnostics(diag);

View File

@ -924,10 +924,10 @@ impl<D: Deps> DepGraphData<D> {
// Promote the previous diagnostics to the current session. // Promote the previous diagnostics to the current session.
qcx.store_side_effects(dep_node_index, side_effects.clone()); qcx.store_side_effects(dep_node_index, side_effects.clone());
let handle = qcx.dep_context().sess().dcx(); let dcx = qcx.dep_context().sess().dcx();
for diagnostic in side_effects.diagnostics { for diagnostic in side_effects.diagnostics {
handle.emit_diagnostic(diagnostic); dcx.emit_diagnostic(diagnostic);
} }
} }
} }

View File

@ -2601,7 +2601,9 @@ fn parse_remap_path_prefix(
.opt_strs("remap-path-prefix") .opt_strs("remap-path-prefix")
.into_iter() .into_iter()
.map(|remap| match remap.rsplit_once('=') { .map(|remap| match remap.rsplit_once('=') {
None => early_dcx.early_error("--remap-path-prefix must contain '=' between FROM and TO"), None => {
early_dcx.early_error("--remap-path-prefix must contain '=' between FROM and TO")
}
Some((from, to)) => (PathBuf::from(from), PathBuf::from(to)), Some((from, to)) => (PathBuf::from(from), PathBuf::from(to)),
}) })
.collect(); .collect();
@ -2673,8 +2675,12 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
let output_types = parse_output_types(early_dcx, &unstable_opts, matches); let output_types = parse_output_types(early_dcx, &unstable_opts, matches);
let mut cg = CodegenOptions::build(early_dcx, matches); let mut cg = CodegenOptions::build(early_dcx, matches);
let (disable_local_thinlto, mut codegen_units) = let (disable_local_thinlto, mut codegen_units) = should_override_cgus_and_disable_thinlto(
should_override_cgus_and_disable_thinlto(early_dcx, &output_types, matches, cg.codegen_units); early_dcx,
&output_types,
matches,
cg.codegen_units,
);
if unstable_opts.threads == 0 { if unstable_opts.threads == 0 {
early_dcx.early_error("value for threads must be a positive non-zero integer"); early_dcx.early_error("value for threads must be a positive non-zero integer");
@ -2851,7 +2857,8 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
} }
if cg.remark.is_empty() && unstable_opts.remark_dir.is_some() { if cg.remark.is_empty() && unstable_opts.remark_dir.is_some() {
early_dcx.early_warn("using -Z remark-dir without enabling remarks using e.g. -C remark=all"); early_dcx
.early_warn("using -Z remark-dir without enabling remarks using e.g. -C remark=all");
} }
let externs = parse_externs(early_dcx, matches, &unstable_opts); let externs = parse_externs(early_dcx, matches, &unstable_opts);

View File

@ -226,8 +226,8 @@ impl ParseSess {
pub fn new(locale_resources: Vec<&'static str>, file_path_mapping: FilePathMapping) -> Self { pub fn new(locale_resources: Vec<&'static str>, file_path_mapping: FilePathMapping) -> Self {
let fallback_bundle = fallback_fluent_bundle(locale_resources, false); let fallback_bundle = fallback_fluent_bundle(locale_resources, false);
let sm = Lrc::new(SourceMap::new(file_path_mapping)); let sm = Lrc::new(SourceMap::new(file_path_mapping));
let handler = DiagCtxt::with_tty_emitter(Some(sm.clone()), fallback_bundle); let dcx = DiagCtxt::with_tty_emitter(Some(sm.clone()), fallback_bundle);
ParseSess::with_dcx(handler, sm) ParseSess::with_dcx(dcx, sm)
} }
pub fn with_dcx(dcx: DiagCtxt, source_map: Lrc<SourceMap>) -> Self { pub fn with_dcx(dcx: DiagCtxt, source_map: Lrc<SourceMap>) -> Self {
@ -256,9 +256,9 @@ impl ParseSess {
let fallback_bundle = fallback_fluent_bundle(Vec::new(), false); let fallback_bundle = fallback_fluent_bundle(Vec::new(), false);
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let fatal_dcx = DiagCtxt::with_tty_emitter(None, fallback_bundle).disable_warnings(); let fatal_dcx = DiagCtxt::with_tty_emitter(None, fallback_bundle).disable_warnings();
let handler = DiagCtxt::with_emitter(Box::new(SilentEmitter { fatal_dcx, fatal_note })) let dcx = DiagCtxt::with_emitter(Box::new(SilentEmitter { fatal_dcx, fatal_note }))
.disable_warnings(); .disable_warnings();
ParseSess::with_dcx(handler, sm) ParseSess::with_dcx(dcx, sm)
} }
#[inline] #[inline]

View File

@ -1416,10 +1416,10 @@ pub fn build_session(
); );
let emitter = default_emitter(&sopts, registry, source_map.clone(), bundle, fallback_bundle); let emitter = default_emitter(&sopts, registry, source_map.clone(), bundle, fallback_bundle);
let mut span_diagnostic = DiagCtxt::with_emitter(emitter) let mut dcx = DiagCtxt::with_emitter(emitter)
.with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings)); .with_flags(sopts.unstable_opts.dcx_flags(can_emit_warnings));
if let Some(ice_file) = ice_file { if let Some(ice_file) = ice_file {
span_diagnostic = span_diagnostic.with_ice_file(ice_file); dcx = dcx.with_ice_file(ice_file);
} }
// Now that the proper handler has been constructed, drop early_dcx to // Now that the proper handler has been constructed, drop early_dcx to
@ -1440,7 +1440,7 @@ pub fn build_session(
match profiler { match profiler {
Ok(profiler) => Some(Arc::new(profiler)), Ok(profiler) => Some(Arc::new(profiler)),
Err(e) => { Err(e) => {
span_diagnostic.emit_warning(errors::FailedToCreateProfiler { err: e.to_string() }); dcx.emit_warning(errors::FailedToCreateProfiler { err: e.to_string() });
None None
} }
} }
@ -1448,7 +1448,7 @@ pub fn build_session(
None None
}; };
let mut parse_sess = ParseSess::with_dcx(span_diagnostic, source_map); let mut parse_sess = ParseSess::with_dcx(dcx, source_map);
parse_sess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release; parse_sess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release;
let host_triple = config::host_triple(); let host_triple = config::host_triple();

View File

@ -348,10 +348,10 @@ impl Options {
let codegen_options = CodegenOptions::build(early_dcx, matches); let codegen_options = CodegenOptions::build(early_dcx, matches);
let unstable_opts = UnstableOptions::build(early_dcx, matches); let unstable_opts = UnstableOptions::build(early_dcx, matches);
let diag = new_dcx(error_format, None, diagnostic_width, &unstable_opts); let dcx = new_dcx(error_format, None, diagnostic_width, &unstable_opts);
// check for deprecated options // check for deprecated options
check_deprecated_options(matches, &diag); check_deprecated_options(matches, &dcx);
if matches.opt_strs("passes") == ["list"] { if matches.opt_strs("passes") == ["list"] {
println!("Available passes for running rustdoc:"); println!("Available passes for running rustdoc:");
@ -391,7 +391,7 @@ impl Options {
match kind.parse() { match kind.parse() {
Ok(kind) => emit.push(kind), Ok(kind) => emit.push(kind),
Err(()) => { Err(()) => {
diag.err(format!("unrecognized emission type: {kind}")); dcx.err(format!("unrecognized emission type: {kind}"));
return Err(1); return Err(1);
} }
} }
@ -421,7 +421,7 @@ impl Options {
let paths = match theme::load_css_paths(content) { let paths = match theme::load_css_paths(content) {
Ok(p) => p, Ok(p) => p,
Err(e) => { Err(e) => {
diag.struct_err(e).emit(); dcx.struct_err(e).emit();
return Err(1); return Err(1);
} }
}; };
@ -430,7 +430,7 @@ impl Options {
println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)"); println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
for theme_file in to_check.iter() { for theme_file in to_check.iter() {
print!(" - Checking \"{theme_file}\"..."); print!(" - Checking \"{theme_file}\"...");
let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag); let (success, differences) = theme::test_theme_against(theme_file, &paths, &dcx);
if !differences.is_empty() || !success { if !differences.is_empty() || !success {
println!(" FAILED"); println!(" FAILED");
errors += 1; errors += 1;
@ -452,10 +452,10 @@ impl Options {
let input = PathBuf::from(if describe_lints { let input = PathBuf::from(if describe_lints {
"" // dummy, this won't be used "" // dummy, this won't be used
} else if matches.free.is_empty() { } else if matches.free.is_empty() {
diag.struct_err("missing file operand").emit(); dcx.struct_err("missing file operand").emit();
return Err(1); return Err(1);
} else if matches.free.len() > 1 { } else if matches.free.len() > 1 {
diag.struct_err("too many file operands").emit(); dcx.struct_err("too many file operands").emit();
return Err(1); return Err(1);
} else { } else {
&matches.free[0] &matches.free[0]
@ -467,7 +467,7 @@ impl Options {
let extern_html_root_urls = match parse_extern_html_roots(matches) { let extern_html_root_urls = match parse_extern_html_roots(matches) {
Ok(ex) => ex, Ok(ex) => ex,
Err(err) => { Err(err) => {
diag.struct_err(err).emit(); dcx.struct_err(err).emit();
return Err(1); return Err(1);
} }
}; };
@ -526,7 +526,7 @@ impl Options {
let no_run = matches.opt_present("no-run"); let no_run = matches.opt_present("no-run");
if !should_test && no_run { if !should_test && no_run {
diag.err("the `--test` flag must be passed to enable `--no-run`"); dcx.err("the `--test` flag must be passed to enable `--no-run`");
return Err(1); return Err(1);
} }
@ -534,7 +534,7 @@ impl Options {
let output = matches.opt_str("output").map(|s| PathBuf::from(&s)); let output = matches.opt_str("output").map(|s| PathBuf::from(&s));
let output = match (out_dir, output) { let output = match (out_dir, output) {
(Some(_), Some(_)) => { (Some(_), Some(_)) => {
diag.struct_err("cannot use both 'out-dir' and 'output' at once").emit(); dcx.struct_err("cannot use both 'out-dir' and 'output' at once").emit();
return Err(1); return Err(1);
} }
(Some(out_dir), None) => out_dir, (Some(out_dir), None) => out_dir,
@ -549,7 +549,7 @@ impl Options {
if let Some(ref p) = extension_css { if let Some(ref p) = extension_css {
if !p.is_file() { if !p.is_file() {
diag.struct_err("option --extend-css argument must be a file").emit(); dcx.struct_err("option --extend-css argument must be a file").emit();
return Err(1); return Err(1);
} }
} }
@ -567,7 +567,7 @@ impl Options {
let paths = match theme::load_css_paths(content) { let paths = match theme::load_css_paths(content) {
Ok(p) => p, Ok(p) => p,
Err(e) => { Err(e) => {
diag.struct_err(e).emit(); dcx.struct_err(e).emit();
return Err(1); return Err(1);
} }
}; };
@ -576,23 +576,23 @@ impl Options {
matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned())) matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
{ {
if !theme_file.is_file() { if !theme_file.is_file() {
diag.struct_err(format!("invalid argument: \"{theme_s}\"")) dcx.struct_err(format!("invalid argument: \"{theme_s}\""))
.help("arguments to --theme must be files") .help("arguments to --theme must be files")
.emit(); .emit();
return Err(1); return Err(1);
} }
if theme_file.extension() != Some(OsStr::new("css")) { if theme_file.extension() != Some(OsStr::new("css")) {
diag.struct_err(format!("invalid argument: \"{theme_s}\"")) dcx.struct_err(format!("invalid argument: \"{theme_s}\""))
.help("arguments to --theme must have a .css extension") .help("arguments to --theme must have a .css extension")
.emit(); .emit();
return Err(1); return Err(1);
} }
let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag); let (success, ret) = theme::test_theme_against(&theme_file, &paths, &dcx);
if !success { if !success {
diag.struct_err(format!("error loading theme file: \"{theme_s}\"")).emit(); dcx.struct_err(format!("error loading theme file: \"{theme_s}\"")).emit();
return Err(1); return Err(1);
} else if !ret.is_empty() { } else if !ret.is_empty() {
diag.struct_warn(format!( dcx.struct_warn(format!(
"theme file \"{theme_s}\" is missing CSS rules from the default theme", "theme file \"{theme_s}\" is missing CSS rules from the default theme",
)) ))
.warn("the theme may appear incorrect when loaded") .warn("the theme may appear incorrect when loaded")
@ -615,7 +615,7 @@ impl Options {
&matches.opt_strs("markdown-before-content"), &matches.opt_strs("markdown-before-content"),
&matches.opt_strs("markdown-after-content"), &matches.opt_strs("markdown-after-content"),
nightly_options::match_is_nightly_build(matches), nightly_options::match_is_nightly_build(matches),
&diag, &dcx,
&mut id_map, &mut id_map,
edition, edition,
&None, &None,
@ -626,7 +626,7 @@ impl Options {
match matches.opt_str("r").as_deref() { match matches.opt_str("r").as_deref() {
Some("rust") | None => {} Some("rust") | None => {}
Some(s) => { Some(s) => {
diag.struct_err(format!("unknown input format: {s}")).emit(); dcx.struct_err(format!("unknown input format: {s}")).emit();
return Err(1); return Err(1);
} }
} }
@ -634,7 +634,7 @@ impl Options {
let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s)); let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
if let Some(ref index_page) = index_page { if let Some(ref index_page) = index_page {
if !index_page.is_file() { if !index_page.is_file() {
diag.struct_err("option `--index-page` argument must be a file").emit(); dcx.struct_err("option `--index-page` argument must be a file").emit();
return Err(1); return Err(1);
} }
} }
@ -646,7 +646,7 @@ impl Options {
let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) { let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
Ok(types) => types, Ok(types) => types,
Err(e) => { Err(e) => {
diag.struct_err(format!("unknown crate type: {e}")).emit(); dcx.struct_err(format!("unknown crate type: {e}")).emit();
return Err(1); return Err(1);
} }
}; };
@ -655,7 +655,7 @@ impl Options {
Some(s) => match OutputFormat::try_from(s.as_str()) { Some(s) => match OutputFormat::try_from(s.as_str()) {
Ok(out_fmt) => { Ok(out_fmt) => {
if !out_fmt.is_json() && show_coverage { if !out_fmt.is_json() && show_coverage {
diag.struct_err( dcx.struct_err(
"html output format isn't supported for the --show-coverage option", "html output format isn't supported for the --show-coverage option",
) )
.emit(); .emit();
@ -664,7 +664,7 @@ impl Options {
out_fmt out_fmt
} }
Err(e) => { Err(e) => {
diag.struct_err(e).emit(); dcx.struct_err(e).emit();
return Err(1); return Err(1);
} }
}, },
@ -709,16 +709,16 @@ impl Options {
let html_no_source = matches.opt_present("html-no-source"); let html_no_source = matches.opt_present("html-no-source");
if generate_link_to_definition && (show_coverage || output_format != OutputFormat::Html) { if generate_link_to_definition && (show_coverage || output_format != OutputFormat::Html) {
diag.struct_err( dcx.struct_err(
"--generate-link-to-definition option can only be used with HTML output format", "--generate-link-to-definition option can only be used with HTML output format",
) )
.emit(); .emit();
return Err(1); return Err(1);
} }
let scrape_examples_options = ScrapeExamplesOptions::new(matches, &diag)?; let scrape_examples_options = ScrapeExamplesOptions::new(matches, &dcx)?;
let with_examples = matches.opt_strs("with-examples"); let with_examples = matches.opt_strs("with-examples");
let call_locations = crate::scrape_examples::load_call_locations(with_examples, &diag)?; let call_locations = crate::scrape_examples::load_call_locations(with_examples, &dcx)?;
let unstable_features = let unstable_features =
rustc_feature::UnstableFeatures::from_environment(crate_name.as_deref()); rustc_feature::UnstableFeatures::from_environment(crate_name.as_deref());

View File

@ -407,19 +407,19 @@ pub(crate) fn run_global_ctxt(
// Process all of the crate attributes, extracting plugin metadata along // Process all of the crate attributes, extracting plugin metadata along
// with the passes which we are supposed to run. // with the passes which we are supposed to run.
for attr in krate.module.attrs.lists(sym::doc) { for attr in krate.module.attrs.lists(sym::doc) {
let diag = ctxt.sess().dcx(); let dcx = ctxt.sess().dcx();
let name = attr.name_or_empty(); let name = attr.name_or_empty();
// `plugins = "..."`, `no_default_passes`, and `passes = "..."` have no effect // `plugins = "..."`, `no_default_passes`, and `passes = "..."` have no effect
if attr.is_word() && name == sym::no_default_passes { if attr.is_word() && name == sym::no_default_passes {
report_deprecated_attr("no_default_passes", diag, attr.span()); report_deprecated_attr("no_default_passes", dcx, attr.span());
} else if attr.value_str().is_some() { } else if attr.value_str().is_some() {
match name { match name {
sym::passes => { sym::passes => {
report_deprecated_attr("passes = \"...\"", diag, attr.span()); report_deprecated_attr("passes = \"...\"", dcx, attr.span());
} }
sym::plugins => { sym::plugins => {
report_deprecated_attr("plugins = \"...\"", diag, attr.span()); report_deprecated_attr("plugins = \"...\"", dcx, attr.span());
} }
_ => (), _ => (),
} }

View File

@ -579,8 +579,8 @@ pub(crate) fn make_test(
let emitter = EmitterWriter::new(Box::new(io::sink()), fallback_bundle); let emitter = EmitterWriter::new(Box::new(io::sink()), fallback_bundle);
// FIXME(misdreavus): pass `-Z treat-err-as-bug` to the doctest parser // FIXME(misdreavus): pass `-Z treat-err-as-bug` to the doctest parser
let handler = DiagCtxt::with_emitter(Box::new(emitter)).disable_warnings(); let dcx = DiagCtxt::with_emitter(Box::new(emitter)).disable_warnings();
let sess = ParseSess::with_dcx(handler, sm); let sess = ParseSess::with_dcx(dcx, sm);
let mut found_main = false; let mut found_main = false;
let mut found_extern_crate = crate_name.is_none(); let mut found_extern_crate = crate_name.is_none();
@ -638,7 +638,7 @@ pub(crate) fn make_test(
} }
// Reset errors so that they won't be reported as compiler bugs when dropping the // Reset errors so that they won't be reported as compiler bugs when dropping the
// handler. Any errors in the tests will be reported when the test file is compiled, // dcx. Any errors in the tests will be reported when the test file is compiled,
// Note that we still need to cancel the errors above otherwise `DiagnosticBuilder` // Note that we still need to cancel the errors above otherwise `DiagnosticBuilder`
// will panic on drop. // will panic on drop.
sess.dcx.reset_err_count(); sess.dcx.reset_err_count();
@ -754,8 +754,8 @@ fn check_if_attr_is_complete(source: &str, edition: Edition) -> bool {
let emitter = EmitterWriter::new(Box::new(io::sink()), fallback_bundle); let emitter = EmitterWriter::new(Box::new(io::sink()), fallback_bundle);
let handler = DiagCtxt::with_emitter(Box::new(emitter)).disable_warnings(); let dcx = DiagCtxt::with_emitter(Box::new(emitter)).disable_warnings();
let sess = ParseSess::with_dcx(handler, sm); let sess = ParseSess::with_dcx(dcx, sm);
let mut parser = let mut parser =
match maybe_new_parser_from_source_str(&sess, filename, source.to_owned()) { match maybe_new_parser_from_source_str(&sess, filename, source.to_owned()) {
Ok(p) => p, Ok(p) => p,

View File

@ -157,7 +157,7 @@ pub fn main() {
} }
} }
let mut handler = EarlyDiagCtxt::new(ErrorOutputType::default()); let mut early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
let using_internal_features = rustc_driver::install_ice_hook( let using_internal_features = rustc_driver::install_ice_hook(
"https://github.com/rust-lang/rust/issues/new\ "https://github.com/rust-lang/rust/issues/new\
@ -175,11 +175,11 @@ pub fn main() {
// `debug_logging = true` is because all rustc logging goes to its version of tracing (the one // `debug_logging = true` is because all rustc logging goes to its version of tracing (the one
// in the sysroot), and all of rustdoc's logging goes to its version (the one in Cargo.toml). // in the sysroot), and all of rustdoc's logging goes to its version (the one in Cargo.toml).
init_logging(&handler); init_logging(&early_dcx);
rustc_driver::init_logger(&handler, rustc_log::LoggerConfig::from_env("RUSTDOC_LOG")); rustc_driver::init_logger(&early_dcx, rustc_log::LoggerConfig::from_env("RUSTDOC_LOG"));
let exit_code = rustc_driver::catch_with_exit_code(|| match get_args(&handler) { let exit_code = rustc_driver::catch_with_exit_code(|| match get_args(&early_dcx) {
Some(args) => main_args(&mut handler, &args, using_internal_features), Some(args) => main_args(&mut early_dcx, &args, using_internal_features),
_ => _ =>
{ {
#[allow(deprecated)] #[allow(deprecated)]
@ -770,7 +770,7 @@ fn main_args(
} }
// need to move these items separately because we lose them by the time the closure is called, // need to move these items separately because we lose them by the time the closure is called,
// but we can't create the handler ahead of time because it's not Send // but we can't create the dcx ahead of time because it's not Send
let show_coverage = options.show_coverage; let show_coverage = options.show_coverage;
let run_check = options.run_check; let run_check = options.run_check;

View File

@ -42,9 +42,9 @@ fn check_rust_syntax(
let emitter = BufferEmitter { buffer: Lrc::clone(&buffer), fallback_bundle }; let emitter = BufferEmitter { buffer: Lrc::clone(&buffer), fallback_bundle };
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let handler = DiagCtxt::with_emitter(Box::new(emitter)).disable_warnings(); let dcx = DiagCtxt::with_emitter(Box::new(emitter)).disable_warnings();
let source = dox[code_block.code].to_owned(); let source = dox[code_block.code].to_owned();
let sess = ParseSess::with_dcx(handler, sm); let sess = ParseSess::with_dcx(dcx, sm);
let edition = code_block.lang_string.edition.unwrap_or_else(|| cx.tcx.sess.edition()); let edition = code_block.lang_string.edition.unwrap_or_else(|| cx.tcx.sess.edition());
let expn_data = let expn_data =

View File

@ -45,10 +45,10 @@ pub fn check(
let fallback_bundle = let fallback_bundle =
rustc_errors::fallback_fluent_bundle(rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(), false); rustc_errors::fallback_fluent_bundle(rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(), false);
let emitter = EmitterWriter::new(Box::new(io::sink()), fallback_bundle); let emitter = EmitterWriter::new(Box::new(io::sink()), fallback_bundle);
let handler = DiagCtxt::with_emitter(Box::new(emitter)).disable_warnings(); let dcx = DiagCtxt::with_emitter(Box::new(emitter)).disable_warnings();
#[expect(clippy::arc_with_non_send_sync)] // `Lrc` is expected by with_dcx #[expect(clippy::arc_with_non_send_sync)] // `Lrc` is expected by with_dcx
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sess = ParseSess::with_dcx(handler, sm); let sess = ParseSess::with_dcx(dcx, sm);
let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code) { let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code) {
Ok(p) => p, Ok(p) => p,

View File

@ -174,9 +174,9 @@ const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/ne
#[allow(clippy::too_many_lines)] #[allow(clippy::too_many_lines)]
#[allow(clippy::ignored_unit_patterns)] #[allow(clippy::ignored_unit_patterns)]
pub fn main() { pub fn main() {
let handler = EarlyDiagCtxt::new(ErrorOutputType::default()); let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
rustc_driver::init_rustc_env_logger(&handler); rustc_driver::init_rustc_env_logger(&early_dcx);
let using_internal_features = rustc_driver::install_ice_hook(BUG_REPORT_URL, |handler| { let using_internal_features = rustc_driver::install_ice_hook(BUG_REPORT_URL, |handler| {
// FIXME: this macro calls unwrap internally but is called in a panicking context! It's not // FIXME: this macro calls unwrap internally but is called in a panicking context! It's not

View File

@ -69,8 +69,8 @@ impl rustc_driver::Callbacks for MiriCompilerCalls {
tcx.sess.fatal("miri cannot be run on programs that fail compilation"); tcx.sess.fatal("miri cannot be run on programs that fail compilation");
} }
let handler = EarlyDiagCtxt::new(tcx.sess.opts.error_format); let early_dcx = EarlyDiagCtxt::new(tcx.sess.opts.error_format);
init_late_loggers(&handler, tcx); init_late_loggers(&early_dcx, tcx);
if !tcx.crate_types().contains(&CrateType::Executable) { if !tcx.crate_types().contains(&CrateType::Executable) {
tcx.sess.fatal("miri only makes sense on bin crates"); tcx.sess.fatal("miri only makes sense on bin crates");
} }
@ -300,7 +300,7 @@ fn parse_comma_list<T: FromStr>(input: &str) -> Result<Vec<T>, T::Err> {
} }
fn main() { fn main() {
let handler = EarlyDiagCtxt::new(ErrorOutputType::default()); let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
// Snapshot a copy of the environment before `rustc` starts messing with it. // Snapshot a copy of the environment before `rustc` starts messing with it.
// (`install_ice_hook` might change `RUST_BACKTRACE`.) // (`install_ice_hook` might change `RUST_BACKTRACE`.)
@ -311,7 +311,7 @@ fn main() {
// Earliest rustc setup. // Earliest rustc setup.
let using_internal_features = let using_internal_features =
rustc_driver::install_ice_hook(rustc_driver::DEFAULT_BUG_REPORT_URL, |_| ()); rustc_driver::install_ice_hook(rustc_driver::DEFAULT_BUG_REPORT_URL, |_| ());
rustc_driver::init_rustc_env_logger(&handler); rustc_driver::init_rustc_env_logger(&early_dcx);
let target_crate = if crate_kind == "target" { let target_crate = if crate_kind == "target" {
true true
@ -335,7 +335,7 @@ fn main() {
rustc_driver::install_ice_hook("https://github.com/rust-lang/miri/issues/new", |_| ()); rustc_driver::install_ice_hook("https://github.com/rust-lang/miri/issues/new", |_| ());
// Init loggers the Miri way. // Init loggers the Miri way.
init_early_loggers(&handler); init_early_loggers(&early_dcx);
// Parse our arguments and split them across `rustc` and `miri`. // Parse our arguments and split them across `rustc` and `miri`.
let mut miri_config = miri::MiriConfig::default(); let mut miri_config = miri::MiriConfig::default();

View File

@ -159,14 +159,14 @@ impl ParseSess {
let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty())); let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let can_reset_errors = Lrc::new(AtomicBool::new(false)); let can_reset_errors = Lrc::new(AtomicBool::new(false));
let handler = default_dcx( let dcx = default_dcx(
Lrc::clone(&source_map), Lrc::clone(&source_map),
Lrc::clone(&ignore_path_set), Lrc::clone(&ignore_path_set),
Lrc::clone(&can_reset_errors), Lrc::clone(&can_reset_errors),
config.hide_parse_errors(), config.hide_parse_errors(),
config.color(), config.color(),
); );
let parse_sess = RawParseSess::with_dcx(handler, source_map); let parse_sess = RawParseSess::with_dcx(dcx, source_map);
Ok(ParseSess { Ok(ParseSess {
parse_sess, parse_sess,