Skip to content

Commit bcae781

Browse files
committed
Auto merge of #119146 - nnethercote:rm-DiagCtxt-api-duplication, r=compiler-errors
Remove `DiagCtxt` API duplication `DiagCtxt` defines the internal API for creating and emitting diagnostics: methods like `struct_err`, `struct_span_warn`, `note`, `create_fatal`, `emit_bug`. There are over 50 methods. Some of these methods are then duplicated across several other types: `Session`, `ParseSess`, `Parser`, `ExtCtxt`, and `MirBorrowckCtxt`. `Session` duplicates the most, though half the ones it does are unused. Each duplicated method just calls forward to the corresponding method in `DiagCtxt`. So this duplication exists to (in the best case) shorten chains like `ecx.tcx.sess.parse_sess.dcx.emit_err()` to `ecx.emit_err()`. This API duplication is ugly and has been bugging me for a while. And it's inconsistent: there's no real logic about which methods are duplicated, and the use of `#[rustc_lint_diagnostic]` and `#[track_caller]` attributes vary across the duplicates. This PR removes the duplicated API methods and makes all diagnostic creation and emission go through `DiagCtxt`. It also adds `dcx` getter methods to several types to shorten chains. This approach scales *much* better than API duplication; indeed, the PR adds `dcx()` to numerous types that didn't have API duplication: `TyCtxt`, `LoweringCtxt`, `ConstCx`, `FnCtxt`, `TypeErrCtxt`, `InferCtxt`, `CrateLoader`, `CheckAttrVisitor`, and `Resolver`. These result in a lot of changes from `foo.tcx.sess.emit_err()` to `foo.dcx().emit_err()`. (You could do this with more types, but it gets into diminishing returns territory for types that don't emit many diagnostics.) After all these changes, some call sites are more verbose, some are less verbose, and many are the same. The total number of lines is reduced, mostly because of the removed API duplication. And consistency is increased, because calls to `emit_err` and friends are always preceded with `.dcx()` or `.dcx`. r? `@compiler-errors`
2 parents 653121c + 93c86f7 commit bcae781

16 files changed

+79
-69
lines changed

src/abi/mod.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,12 @@ pub(crate) fn conv_to_call_conv(sess: &Session, c: Conv, default_call_conv: Call
4747
}
4848

4949
Conv::X86Intr | Conv::RiscvInterrupt { .. } => {
50-
sess.fatal(format!("interrupt call conv {c:?} not yet implemented"))
50+
sess.dcx().fatal(format!("interrupt call conv {c:?} not yet implemented"))
5151
}
5252

53-
Conv::ArmAapcs => sess.fatal("aapcs call conv not yet implemented"),
53+
Conv::ArmAapcs => sess.dcx().fatal("aapcs call conv not yet implemented"),
5454
Conv::CCmseNonSecureCall => {
55-
sess.fatal("C-cmse-nonsecure-call call conv is not yet implemented");
55+
sess.dcx().fatal("C-cmse-nonsecure-call call conv is not yet implemented");
5656
}
5757

5858
Conv::Msp430Intr
@@ -88,10 +88,10 @@ pub(crate) fn import_function<'tcx>(
8888
let sig = get_function_sig(tcx, module.target_config().default_call_conv, inst);
8989
match module.declare_function(name, Linkage::Import, &sig) {
9090
Ok(func_id) => func_id,
91-
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(format!(
91+
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.dcx().fatal(format!(
9292
"attempt to declare `{name}` as function, but it was already declared as static"
9393
)),
94-
Err(ModuleError::IncompatibleSignature(_, prev_sig, new_sig)) => tcx.sess.fatal(format!(
94+
Err(ModuleError::IncompatibleSignature(_, prev_sig, new_sig)) => tcx.dcx().fatal(format!(
9595
"attempt to declare `{name}` with signature {new_sig:?}, \
9696
but it was already declared with signature {prev_sig:?}"
9797
)),
@@ -181,7 +181,7 @@ fn make_local_place<'tcx>(
181181
is_ssa: bool,
182182
) -> CPlace<'tcx> {
183183
if layout.is_unsized() {
184-
fx.tcx.sess.span_fatal(
184+
fx.tcx.dcx().span_fatal(
185185
fx.mir.local_decls[local].source_info.span,
186186
"unsized locals are not yet supported",
187187
);
@@ -226,7 +226,7 @@ pub(crate) fn codegen_fn_prelude<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, start_
226226

227227
// FIXME implement variadics in cranelift
228228
if fn_abi.c_variadic {
229-
fx.tcx.sess.span_fatal(
229+
fx.tcx.dcx().span_fatal(
230230
fx.mir.span,
231231
"Defining variadic functions is not yet supported by Cranelift",
232232
);
@@ -543,7 +543,7 @@ pub(crate) fn codegen_terminator_call<'tcx>(
543543
// FIXME find a cleaner way to support varargs
544544
if fn_sig.c_variadic() {
545545
if !matches!(fn_sig.abi(), Abi::C { .. }) {
546-
fx.tcx.sess.span_fatal(
546+
fx.tcx.dcx().span_fatal(
547547
source_info.span,
548548
format!("Variadic call for non-C abi {:?}", fn_sig.abi()),
549549
);
@@ -555,7 +555,7 @@ pub(crate) fn codegen_terminator_call<'tcx>(
555555
let ty = fx.bcx.func.dfg.value_type(arg);
556556
if !ty.is_int() {
557557
// FIXME set %al to upperbound on float args once floats are supported
558-
fx.tcx.sess.span_fatal(
558+
fx.tcx.dcx().span_fatal(
559559
source_info.span,
560560
format!("Non int ty {:?} for variadic call", ty),
561561
);

src/base.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -236,13 +236,13 @@ pub(crate) fn verify_func(
236236
match cranelift_codegen::verify_function(&func, &flags) {
237237
Ok(_) => {}
238238
Err(err) => {
239-
tcx.sess.err(format!("{:?}", err));
239+
tcx.dcx().err(format!("{:?}", err));
240240
let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
241241
&func,
242242
Some(Box::new(writer)),
243243
err,
244244
);
245-
tcx.sess.fatal(format!("cranelift verify error:\n{}", pretty_error));
245+
tcx.dcx().fatal(format!("cranelift verify error:\n{}", pretty_error));
246246
}
247247
}
248248
});
@@ -450,7 +450,7 @@ fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) {
450450
unwind: _,
451451
} => {
452452
if options.contains(InlineAsmOptions::MAY_UNWIND) {
453-
fx.tcx.sess.span_fatal(
453+
fx.tcx.dcx().span_fatal(
454454
source_info.span,
455455
"cranelift doesn't support unwinding from inline assembly.",
456456
);
@@ -812,7 +812,7 @@ fn codegen_stmt<'tcx>(
812812
| StatementKind::PlaceMention(..)
813813
| StatementKind::AscribeUserType(..) => {}
814814

815-
StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"),
815+
StatementKind::Coverage { .. } => fx.tcx.dcx().fatal("-Zcoverage is unimplemented"),
816816
StatementKind::Intrinsic(ref intrinsic) => match &**intrinsic {
817817
// We ignore `assume` intrinsics, they are only useful for optimizations
818818
NonDivergingIntrinsic::Assume(_) => {}

src/common.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -465,9 +465,12 @@ impl<'tcx> LayoutOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
465465
#[inline]
466466
fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
467467
if let LayoutError::SizeOverflow(_) | LayoutError::ReferencesError(_) = err {
468-
self.0.sess.span_fatal(span, err.to_string())
468+
self.0.sess.dcx().span_fatal(span, err.to_string())
469469
} else {
470-
self.0.sess.span_fatal(span, format!("failed to get layout for `{}`: {}", ty, err))
470+
self.0
471+
.sess
472+
.dcx()
473+
.span_fatal(span, format!("failed to get layout for `{}`: {}", ty, err))
471474
}
472475
}
473476
}
@@ -483,7 +486,7 @@ impl<'tcx> FnAbiOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
483486
fn_abi_request: FnAbiRequest<'tcx>,
484487
) -> ! {
485488
if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err {
486-
self.0.sess.emit_fatal(Spanned { span, node: err })
489+
self.0.sess.dcx().emit_fatal(Spanned { span, node: err })
487490
} else {
488491
match fn_abi_request {
489492
FnAbiRequest::OfFnPtr { sig, extra_args } => {

src/constant.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@ fn data_id_for_static(
263263
attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
264264
) {
265265
Ok(data_id) => data_id,
266-
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(format!(
266+
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.dcx().fatal(format!(
267267
"attempt to declare `{symbol_name}` as static, but it was already declared as function"
268268
)),
269269
Err(err) => Err::<_, _>(err).unwrap(),
@@ -311,7 +311,7 @@ fn data_id_for_static(
311311
attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
312312
) {
313313
Ok(data_id) => data_id,
314-
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(format!(
314+
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.dcx().fatal(format!(
315315
"attempt to declare `{symbol_name}` as static, but it was already declared as function"
316316
)),
317317
Err(err) => Err::<_, _>(err).unwrap(),
@@ -360,7 +360,7 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut Constant
360360
if let Some(names) = section_name.split_once(',') {
361361
names
362362
} else {
363-
tcx.sess.fatal(format!(
363+
tcx.dcx().fatal(format!(
364364
"#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
365365
section_name
366366
));
@@ -406,7 +406,7 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut Constant
406406
GlobalAlloc::Static(def_id) => {
407407
if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
408408
{
409-
tcx.sess.fatal(format!(
409+
tcx.dcx().fatal(format!(
410410
"Allocation {:?} contains reference to TLS value {:?}",
411411
alloc_id, def_id
412412
));

src/driver/aot.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ impl OngoingCodegen {
6969

7070
let module_codegen_result = match module_codegen_result {
7171
Ok(module_codegen_result) => module_codegen_result,
72-
Err(err) => sess.fatal(err),
72+
Err(err) => sess.dcx().fatal(err),
7373
};
7474
let ModuleCodegenResult { module_regular, module_global_asm, existing_work_product } =
7575
module_codegen_result;
@@ -108,7 +108,7 @@ impl OngoingCodegen {
108108

109109
self.concurrency_limiter.finished();
110110

111-
sess.abort_if_errors();
111+
sess.dcx().abort_if_errors();
112112

113113
(
114114
CodegenResults {
@@ -422,7 +422,7 @@ pub(crate) fn run_aot(
422422
backend_config.clone(),
423423
global_asm_config.clone(),
424424
cgu.name(),
425-
concurrency_limiter.acquire(tcx.sess.dcx()),
425+
concurrency_limiter.acquire(tcx.dcx()),
426426
),
427427
module_codegen,
428428
Some(rustc_middle::dep_graph::hash_result),
@@ -455,7 +455,7 @@ pub(crate) fn run_aot(
455455
"allocator_shim".to_owned(),
456456
) {
457457
Ok(allocator_module) => Some(allocator_module),
458-
Err(err) => tcx.sess.fatal(err),
458+
Err(err) => tcx.dcx().fatal(err),
459459
}
460460
} else {
461461
None
@@ -478,7 +478,7 @@ pub(crate) fn run_aot(
478478
let obj = create_compressed_metadata_file(tcx.sess, &metadata, &symbol_name);
479479

480480
if let Err(err) = std::fs::write(&tmp_file, obj) {
481-
tcx.sess.fatal(format!("error writing metadata object file: {}", err));
481+
tcx.dcx().fatal(format!("error writing metadata object file: {}", err));
482482
}
483483

484484
(metadata_cgu_name, tmp_file)

src/driver/jit.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -94,11 +94,11 @@ fn create_jit_module(
9494

9595
pub(crate) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! {
9696
if !tcx.sess.opts.output_types.should_codegen() {
97-
tcx.sess.fatal("JIT mode doesn't work with `cargo check`");
97+
tcx.dcx().fatal("JIT mode doesn't work with `cargo check`");
9898
}
9999

100100
if !tcx.crate_types().contains(&rustc_session::config::CrateType::Executable) {
101-
tcx.sess.fatal("can't jit non-executable crate");
101+
tcx.dcx().fatal("can't jit non-executable crate");
102102
}
103103

104104
let (mut jit_module, mut cx) = create_jit_module(
@@ -141,17 +141,17 @@ pub(crate) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! {
141141
}
142142
MonoItem::GlobalAsm(item_id) => {
143143
let item = tcx.hir().item(item_id);
144-
tcx.sess.span_fatal(item.span, "Global asm is not supported in JIT mode");
144+
tcx.dcx().span_fatal(item.span, "Global asm is not supported in JIT mode");
145145
}
146146
}
147147
}
148148
});
149149

150150
if !cx.global_asm.is_empty() {
151-
tcx.sess.fatal("Inline asm is not supported in JIT mode");
151+
tcx.dcx().fatal("Inline asm is not supported in JIT mode");
152152
}
153153

154-
tcx.sess.abort_if_errors();
154+
tcx.dcx().abort_if_errors();
155155

156156
jit_module.finalize_definitions().unwrap();
157157
unsafe { cx.unwind_context.register_jit(&jit_module) };
@@ -338,7 +338,7 @@ fn dep_symbol_lookup_fn(
338338
.collect::<Box<[_]>>(),
339339
);
340340

341-
sess.abort_if_errors();
341+
sess.dcx().abort_if_errors();
342342

343343
Box::new(move |sym_name| {
344344
for dylib in &*imported_dylibs {

src/global_asm.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ pub(crate) fn codegen_global_asm_item(tcx: TyCtxt<'_>, global_asm: &mut String,
4747
}
4848
InlineAsmOperand::SymFn { anon_const } => {
4949
if cfg!(not(feature = "inline_asm_sym")) {
50-
tcx.sess.span_err(
50+
tcx.dcx().span_err(
5151
item.span,
5252
"asm! and global_asm! sym operands are not yet supported",
5353
);
@@ -65,7 +65,7 @@ pub(crate) fn codegen_global_asm_item(tcx: TyCtxt<'_>, global_asm: &mut String,
6565
}
6666
InlineAsmOperand::SymStatic { path: _, def_id } => {
6767
if cfg!(not(feature = "inline_asm_sym")) {
68-
tcx.sess.span_err(
68+
tcx.dcx().span_err(
6969
item.span,
7070
"asm! and global_asm! sym operands are not yet supported",
7171
);

src/inline_asm.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ pub(crate) fn codegen_inline_asm_terminator<'tcx>(
8484
InlineAsmOperand::SymFn { ref value } => {
8585
if cfg!(not(feature = "inline_asm_sym")) {
8686
fx.tcx
87-
.sess
87+
.dcx()
8888
.span_err(span, "asm! and global_asm! sym operands are not yet supported");
8989
}
9090

@@ -455,7 +455,7 @@ impl<'tcx> InlineAssemblyGenerator<'_, 'tcx> {
455455
}
456456
_ => self
457457
.tcx
458-
.sess
458+
.dcx()
459459
.fatal(format!("Unsupported binary format for inline asm: {binary_format:?}")),
460460
}
461461

@@ -563,7 +563,7 @@ impl<'tcx> InlineAssemblyGenerator<'_, 'tcx> {
563563
BinaryFormat::Macho | BinaryFormat::Coff => {}
564564
_ => self
565565
.tcx
566-
.sess
566+
.dcx()
567567
.fatal(format!("Unsupported binary format for inline asm: {binary_format:?}")),
568568
}
569569

src/intrinsics/llvm.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ pub(crate) fn codegen_llvm_intrinsic_call<'tcx>(
6868

6969
_ => {
7070
fx.tcx
71-
.sess
71+
.dcx()
7272
.warn(format!("unsupported llvm intrinsic {}; replacing with trap", intrinsic));
7373
crate::trap::trap_unimplemented(fx, intrinsic);
7474
return;

src/intrinsics/llvm_aarch64.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ pub(crate) fn codegen_aarch64_llvm_intrinsic_call<'tcx>(
309309
}
310310
*/
311311
_ => {
312-
fx.tcx.sess.warn(format!(
312+
fx.tcx.dcx().warn(format!(
313313
"unsupported AArch64 llvm intrinsic {}; replacing with trap",
314314
intrinsic
315315
));

src/intrinsics/llvm_x86.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -960,7 +960,9 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>(
960960
{
961961
imm8
962962
} else {
963-
fx.tcx.sess.span_fatal(span, "Index argument for `_mm_cmpestri` is not a constant");
963+
fx.tcx
964+
.dcx()
965+
.span_fatal(span, "Index argument for `_mm_cmpestri` is not a constant");
964966
};
965967

966968
let imm8 = imm8.try_to_u8().unwrap_or_else(|_| panic!("kind not scalar: {:?}", imm8));
@@ -1011,7 +1013,9 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>(
10111013
{
10121014
imm8
10131015
} else {
1014-
fx.tcx.sess.span_fatal(span, "Index argument for `_mm_cmpestrm` is not a constant");
1016+
fx.tcx
1017+
.dcx()
1018+
.span_fatal(span, "Index argument for `_mm_cmpestrm` is not a constant");
10151019
};
10161020

10171021
let imm8 = imm8.try_to_u8().unwrap_or_else(|_| panic!("kind not scalar: {:?}", imm8));
@@ -1056,7 +1060,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>(
10561060
{
10571061
imm8
10581062
} else {
1059-
fx.tcx.sess.span_fatal(
1063+
fx.tcx.dcx().span_fatal(
10601064
span,
10611065
"Index argument for `_mm_clmulepi64_si128` is not a constant",
10621066
);
@@ -1093,7 +1097,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>(
10931097
{
10941098
imm8
10951099
} else {
1096-
fx.tcx.sess.span_fatal(
1100+
fx.tcx.dcx().span_fatal(
10971101
span,
10981102
"Index argument for `_mm_aeskeygenassist_si128` is not a constant",
10991103
);
@@ -1361,7 +1365,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>(
13611365

13621366
_ => {
13631367
fx.tcx
1364-
.sess
1368+
.dcx()
13651369
.warn(format!("unsupported x86 llvm intrinsic {}; replacing with trap", intrinsic));
13661370
crate::trap::trap_unimplemented(fx, intrinsic);
13671371
return;

0 commit comments

Comments
 (0)