summary refs log tree commit diff
path: root/compiler/rustc_builtin_macros/src
diff options
context:
space:
mode:
authorNicholas Nethercote <n.nethercote@gmail.com>2023-12-18 20:54:03 +1100
committerNicholas Nethercote <n.nethercote@gmail.com>2023-12-24 07:24:52 +1100
commitd86a48278f7bcd069a56870a70c6376e77bd4ee5 (patch)
tree7b653abdf0eda9cd3568a96299fbfe28a39ee259 /compiler/rustc_builtin_macros/src
parent5eccfc388e70d45c98b859af5c14f397ae1c206e (diff)
downloadrust-d86a48278f7bcd069a56870a70c6376e77bd4ee5.tar.gz
rust-d86a48278f7bcd069a56870a70c6376e77bd4ee5.zip
Remove `ExtCtxt` methods that duplicate `DiagCtxt` methods.
Diffstat (limited to 'compiler/rustc_builtin_macros/src')
-rw-r--r--compiler/rustc_builtin_macros/src/alloc_error_handler.rs2
-rw-r--r--compiler/rustc_builtin_macros/src/asm.rs23
-rw-r--r--compiler/rustc_builtin_macros/src/assert.rs6
-rw-r--r--compiler/rustc_builtin_macros/src/cfg.rs4
-rw-r--r--compiler/rustc_builtin_macros/src/cfg_accessible.rs10
-rw-r--r--compiler/rustc_builtin_macros/src/compile_error.rs2
-rw-r--r--compiler/rustc_builtin_macros/src/concat.rs8
-rw-r--r--compiler/rustc_builtin_macros/src/concat_bytes.rs28
-rw-r--r--compiler/rustc_builtin_macros/src/concat_idents.rs6
-rw-r--r--compiler/rustc_builtin_macros/src/deriving/clone.rs12
-rw-r--r--compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs2
-rw-r--r--compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs2
-rw-r--r--compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs3
-rw-r--r--compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs2
-rw-r--r--compiler/rustc_builtin_macros/src/deriving/debug.rs2
-rw-r--r--compiler/rustc_builtin_macros/src/deriving/decodable.rs2
-rw-r--r--compiler/rustc_builtin_macros/src/deriving/default.rs18
-rw-r--r--compiler/rustc_builtin_macros/src/deriving/encodable.rs2
-rw-r--r--compiler/rustc_builtin_macros/src/deriving/generic/mod.rs20
-rw-r--r--compiler/rustc_builtin_macros/src/deriving/generic/ty.rs4
-rw-r--r--compiler/rustc_builtin_macros/src/deriving/hash.rs4
-rw-r--r--compiler/rustc_builtin_macros/src/env.rs8
-rw-r--r--compiler/rustc_builtin_macros/src/format.rs22
-rw-r--r--compiler/rustc_builtin_macros/src/global_allocator.rs2
-rw-r--r--compiler/rustc_builtin_macros/src/source_util.rs6
-rw-r--r--compiler/rustc_builtin_macros/src/test.rs27
-rw-r--r--compiler/rustc_builtin_macros/src/trace_macros.rs2
27 files changed, 117 insertions, 112 deletions
diff --git a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs
index dffda8acc8d..bc94e0b972b 100644
--- a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs
+++ b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs
@@ -31,7 +31,7 @@ pub fn expand(
     {
         (item, true, ecx.with_def_site_ctxt(fn_kind.sig.span))
     } else {
-        ecx.sess.dcx().emit_err(errors::AllocErrorMustBeFn { span: item.span() });
+        ecx.dcx().emit_err(errors::AllocErrorMustBeFn { span: item.span() });
         return vec![orig_item];
     };
 
diff --git a/compiler/rustc_builtin_macros/src/asm.rs b/compiler/rustc_builtin_macros/src/asm.rs
index 6f1acd8e570..b2b9e494053 100644
--- a/compiler/rustc_builtin_macros/src/asm.rs
+++ b/compiler/rustc_builtin_macros/src/asm.rs
@@ -541,7 +541,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
             let err = parser.errors.remove(0);
             let err_sp = template_span.from_inner(InnerSpan::new(err.span.start, err.span.end));
             let msg = format!("invalid asm template string: {}", err.description);
-            let mut e = ecx.struct_span_err(err_sp, msg);
+            let mut e = ecx.dcx().struct_span_err(err_sp, msg);
             e.span_label(err_sp, err.label + " in asm template string");
             if let Some(note) = err.note {
                 e.note(note);
@@ -575,7 +575,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
                                 || args.reg_args.contains(idx)
                             {
                                 let msg = format!("invalid reference to argument at index {idx}");
-                                let mut err = ecx.struct_span_err(span, msg);
+                                let mut err = ecx.dcx().struct_span_err(span, msg);
                                 err.span_label(span, "from here");
 
                                 let positional_args = args.operands.len()
@@ -625,12 +625,13 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
                                 None => {
                                     let msg = format!("there is no argument named `{name}`");
                                     let span = arg.position_span;
-                                    ecx.struct_span_err(
-                                        template_span
-                                            .from_inner(InnerSpan::new(span.start, span.end)),
-                                        msg,
-                                    )
-                                    .emit();
+                                    ecx.dcx()
+                                        .struct_span_err(
+                                            template_span
+                                                .from_inner(InnerSpan::new(span.start, span.end)),
+                                            msg,
+                                        )
+                                        .emit();
                                     None
                                 }
                             }
@@ -645,7 +646,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
                             .ty_span
                             .map(|sp| template_sp.from_inner(InnerSpan::new(sp.start, sp.end)))
                             .unwrap_or(template_sp);
-                        ecx.emit_err(errors::AsmModifierInvalid { span });
+                        ecx.dcx().emit_err(errors::AsmModifierInvalid { span });
                         modifier = None;
                     }
 
@@ -692,7 +693,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
         0 => {}
         1 => {
             let (sp, msg) = unused_operands.into_iter().next().unwrap();
-            let mut err = ecx.struct_span_err(sp, msg);
+            let mut err = ecx.dcx().struct_span_err(sp, msg);
             err.span_label(sp, msg);
             err.help(format!(
                 "if this argument is intentionally unused, \
@@ -701,7 +702,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
             err.emit();
         }
         _ => {
-            let mut err = ecx.struct_span_err(
+            let mut err = ecx.dcx().struct_span_err(
                 unused_operands.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
                 "multiple unused asm arguments",
             );
diff --git a/compiler/rustc_builtin_macros/src/assert.rs b/compiler/rustc_builtin_macros/src/assert.rs
index 7abfcc8c50c..8fa3fe5b3e6 100644
--- a/compiler/rustc_builtin_macros/src/assert.rs
+++ b/compiler/rustc_builtin_macros/src/assert.rs
@@ -115,7 +115,7 @@ fn parse_assert<'a>(cx: &mut ExtCtxt<'a>, sp: Span, stream: TokenStream) -> PRes
     let mut parser = cx.new_parser_from_tts(stream);
 
     if parser.token == token::Eof {
-        return Err(cx.create_err(errors::AssertRequiresBoolean { span: sp }));
+        return Err(cx.dcx().create_err(errors::AssertRequiresBoolean { span: sp }));
     }
 
     let cond_expr = parser.parse_expr()?;
@@ -128,7 +128,7 @@ fn parse_assert<'a>(cx: &mut ExtCtxt<'a>, sp: Span, stream: TokenStream) -> PRes
     //
     // Emit an error about semicolon and suggest removing it.
     if parser.token == token::Semi {
-        cx.emit_err(errors::AssertRequiresExpression { span: sp, token: parser.token.span });
+        cx.dcx().emit_err(errors::AssertRequiresExpression { span: sp, token: parser.token.span });
         parser.bump();
     }
 
@@ -141,7 +141,7 @@ fn parse_assert<'a>(cx: &mut ExtCtxt<'a>, sp: Span, stream: TokenStream) -> PRes
     let custom_message =
         if let token::Literal(token::Lit { kind: token::Str, .. }) = parser.token.kind {
             let comma = parser.prev_token.span.shrink_to_hi();
-            cx.emit_err(errors::AssertMissingComma { span: parser.token.span, comma });
+            cx.dcx().emit_err(errors::AssertMissingComma { span: parser.token.span, comma });
 
             parse_custom_message(&mut parser)
         } else if parser.eat(&token::Comma) {
diff --git a/compiler/rustc_builtin_macros/src/cfg.rs b/compiler/rustc_builtin_macros/src/cfg.rs
index 31cac51845f..48be680b619 100644
--- a/compiler/rustc_builtin_macros/src/cfg.rs
+++ b/compiler/rustc_builtin_macros/src/cfg.rs
@@ -39,7 +39,7 @@ fn parse_cfg<'a>(cx: &mut ExtCtxt<'a>, span: Span, tts: TokenStream) -> PResult<
     let mut p = cx.new_parser_from_tts(tts);
 
     if p.token == token::Eof {
-        return Err(cx.create_err(errors::RequiresCfgPattern { span }));
+        return Err(cx.dcx().create_err(errors::RequiresCfgPattern { span }));
     }
 
     let cfg = p.parse_meta_item()?;
@@ -47,7 +47,7 @@ fn parse_cfg<'a>(cx: &mut ExtCtxt<'a>, span: Span, tts: TokenStream) -> PResult<
     let _ = p.eat(&token::Comma);
 
     if !p.eat(&token::Eof) {
-        return Err(cx.create_err(errors::OneCfgPattern { span }));
+        return Err(cx.dcx().create_err(errors::OneCfgPattern { span }));
     }
 
     Ok(cfg)
diff --git a/compiler/rustc_builtin_macros/src/cfg_accessible.rs b/compiler/rustc_builtin_macros/src/cfg_accessible.rs
index 64be8da5902..ceb5f861078 100644
--- a/compiler/rustc_builtin_macros/src/cfg_accessible.rs
+++ b/compiler/rustc_builtin_macros/src/cfg_accessible.rs
@@ -15,18 +15,18 @@ fn validate_input<'a>(ecx: &mut ExtCtxt<'_>, mi: &'a ast::MetaItem) -> Option<&'
     match mi.meta_item_list() {
         None => {}
         Some([]) => {
-            ecx.emit_err(UnspecifiedPath(mi.span));
+            ecx.dcx().emit_err(UnspecifiedPath(mi.span));
         }
         Some([_, .., l]) => {
-            ecx.emit_err(MultiplePaths(l.span()));
+            ecx.dcx().emit_err(MultiplePaths(l.span()));
         }
         Some([nmi]) => match nmi.meta_item() {
             None => {
-                ecx.emit_err(LiteralPath(nmi.span()));
+                ecx.dcx().emit_err(LiteralPath(nmi.span()));
             }
             Some(mi) => {
                 if !mi.is_word() {
-                    ecx.emit_err(HasArguments(mi.span));
+                    ecx.dcx().emit_err(HasArguments(mi.span));
                 }
                 return Some(&mi.path);
             }
@@ -61,7 +61,7 @@ impl MultiItemModifier for Expander {
             Ok(true) => ExpandResult::Ready(vec![item]),
             Ok(false) => ExpandResult::Ready(Vec::new()),
             Err(Indeterminate) if ecx.force_mode => {
-                ecx.emit_err(errors::CfgAccessibleIndeterminate { span });
+                ecx.dcx().emit_err(errors::CfgAccessibleIndeterminate { span });
                 ExpandResult::Ready(vec![item])
             }
             Err(Indeterminate) => ExpandResult::Retry(item),
diff --git a/compiler/rustc_builtin_macros/src/compile_error.rs b/compiler/rustc_builtin_macros/src/compile_error.rs
index 5efc5a4e3ee..f157575da79 100644
--- a/compiler/rustc_builtin_macros/src/compile_error.rs
+++ b/compiler/rustc_builtin_macros/src/compile_error.rs
@@ -18,7 +18,7 @@ pub fn expand_compile_error<'cx>(
         reason = "diagnostic message is specified by user"
     )]
     #[expect(rustc::untranslatable_diagnostic, reason = "diagnostic message is specified by user")]
-    cx.span_err(sp, var.to_string());
+    cx.dcx().span_err(sp, var.to_string());
 
     DummyResult::any(sp)
 }
diff --git a/compiler/rustc_builtin_macros/src/concat.rs b/compiler/rustc_builtin_macros/src/concat.rs
index 6b8330bfdaf..dade29593af 100644
--- a/compiler/rustc_builtin_macros/src/concat.rs
+++ b/compiler/rustc_builtin_macros/src/concat.rs
@@ -33,11 +33,11 @@ pub fn expand_concat(
                     accumulator.push_str(&b.to_string());
                 }
                 Ok(ast::LitKind::CStr(..)) => {
-                    cx.emit_err(errors::ConcatCStrLit { span: e.span });
+                    cx.dcx().emit_err(errors::ConcatCStrLit { span: e.span });
                     has_errors = true;
                 }
                 Ok(ast::LitKind::Byte(..) | ast::LitKind::ByteStr(..)) => {
-                    cx.emit_err(errors::ConcatBytestr { span: e.span });
+                    cx.dcx().emit_err(errors::ConcatBytestr { span: e.span });
                     has_errors = true;
                 }
                 Ok(ast::LitKind::Err) => {
@@ -63,7 +63,7 @@ pub fn expand_concat(
                 }
             }
             ast::ExprKind::IncludedBytes(..) => {
-                cx.emit_err(errors::ConcatBytestr { span: e.span });
+                cx.dcx().emit_err(errors::ConcatBytestr { span: e.span });
             }
             ast::ExprKind::Err => {
                 has_errors = true;
@@ -75,7 +75,7 @@ pub fn expand_concat(
     }
 
     if !missing_literal.is_empty() {
-        cx.emit_err(errors::ConcatMissingLiteral { spans: missing_literal });
+        cx.dcx().emit_err(errors::ConcatMissingLiteral { spans: missing_literal });
         return DummyResult::any(sp);
     } else if has_errors {
         return DummyResult::any(sp);
diff --git a/compiler/rustc_builtin_macros/src/concat_bytes.rs b/compiler/rustc_builtin_macros/src/concat_bytes.rs
index 96e9584c209..4f7c0266343 100644
--- a/compiler/rustc_builtin_macros/src/concat_bytes.rs
+++ b/compiler/rustc_builtin_macros/src/concat_bytes.rs
@@ -17,16 +17,17 @@ fn invalid_type_err(
         ConcatBytesInvalid, ConcatBytesInvalidSuggestion, ConcatBytesNonU8, ConcatBytesOob,
     };
     let snippet = cx.sess.source_map().span_to_snippet(span).ok();
+    let dcx = cx.dcx();
     match ast::LitKind::from_token_lit(token_lit) {
         Ok(ast::LitKind::CStr(_, _)) => {
             // Avoid ambiguity in handling of terminal `NUL` by refusing to
             // concatenate C string literals as bytes.
-            cx.emit_err(errors::ConcatCStrLit { span: span });
+            dcx.emit_err(errors::ConcatCStrLit { span: span });
         }
         Ok(ast::LitKind::Char(_)) => {
             let sugg =
                 snippet.map(|snippet| ConcatBytesInvalidSuggestion::CharLit { span, snippet });
-            cx.sess.emit_err(ConcatBytesInvalid { span, lit_kind: "character", sugg });
+            dcx.emit_err(ConcatBytesInvalid { span, lit_kind: "character", sugg });
         }
         Ok(ast::LitKind::Str(_, _)) => {
             // suggestion would be invalid if we are nested
@@ -35,29 +36,29 @@ fn invalid_type_err(
             } else {
                 None
             };
-            cx.emit_err(ConcatBytesInvalid { span, lit_kind: "string", sugg });
+            dcx.emit_err(ConcatBytesInvalid { span, lit_kind: "string", sugg });
         }
         Ok(ast::LitKind::Float(_, _)) => {
-            cx.emit_err(ConcatBytesInvalid { span, lit_kind: "float", sugg: None });
+            dcx.emit_err(ConcatBytesInvalid { span, lit_kind: "float", sugg: None });
         }
         Ok(ast::LitKind::Bool(_)) => {
-            cx.emit_err(ConcatBytesInvalid { span, lit_kind: "boolean", sugg: None });
+            dcx.emit_err(ConcatBytesInvalid { span, lit_kind: "boolean", sugg: None });
         }
         Ok(ast::LitKind::Err) => {}
         Ok(ast::LitKind::Int(_, _)) if !is_nested => {
             let sugg =
                 snippet.map(|snippet| ConcatBytesInvalidSuggestion::IntLit { span: span, snippet });
-            cx.emit_err(ConcatBytesInvalid { span, lit_kind: "numeric", sugg });
+            dcx.emit_err(ConcatBytesInvalid { span, lit_kind: "numeric", sugg });
         }
         Ok(ast::LitKind::Int(
             val,
             ast::LitIntType::Unsuffixed | ast::LitIntType::Unsigned(ast::UintTy::U8),
         )) => {
             assert!(val > u8::MAX.into()); // must be an error
-            cx.emit_err(ConcatBytesOob { span });
+            dcx.emit_err(ConcatBytesOob { span });
         }
         Ok(ast::LitKind::Int(_, _)) => {
-            cx.emit_err(ConcatBytesNonU8 { span });
+            dcx.emit_err(ConcatBytesNonU8 { span });
         }
         Ok(ast::LitKind::ByteStr(..) | ast::LitKind::Byte(_)) => unreachable!(),
         Err(err) => {
@@ -72,10 +73,11 @@ fn handle_array_element(
     missing_literals: &mut Vec<rustc_span::Span>,
     expr: &P<rustc_ast::Expr>,
 ) -> Option<u8> {
+    let dcx = cx.dcx();
     match expr.kind {
         ast::ExprKind::Array(_) | ast::ExprKind::Repeat(_, _) => {
             if !*has_errors {
-                cx.emit_err(errors::ConcatBytesArray { span: expr.span, bytestr: false });
+                dcx.emit_err(errors::ConcatBytesArray { span: expr.span, bytestr: false });
             }
             *has_errors = true;
             None
@@ -89,7 +91,7 @@ fn handle_array_element(
             Ok(ast::LitKind::Byte(val)) => Some(val),
             Ok(ast::LitKind::ByteStr(..)) => {
                 if !*has_errors {
-                    cx.emit_err(errors::ConcatBytesArray { span: expr.span, bytestr: true });
+                    dcx.emit_err(errors::ConcatBytesArray { span: expr.span, bytestr: true });
                 }
                 *has_errors = true;
                 None
@@ -104,7 +106,7 @@ fn handle_array_element(
         },
         ast::ExprKind::IncludedBytes(..) => {
             if !*has_errors {
-                cx.emit_err(errors::ConcatBytesArray { span: expr.span, bytestr: false });
+                dcx.emit_err(errors::ConcatBytesArray { span: expr.span, bytestr: false });
             }
             *has_errors = true;
             None
@@ -151,7 +153,7 @@ pub fn expand_concat_bytes(
                         }
                     }
                 } else {
-                    cx.emit_err(errors::ConcatBytesBadRepeat { span: count.value.span });
+                    cx.dcx().emit_err(errors::ConcatBytesBadRepeat { span: count.value.span });
                 }
             }
             &ast::ExprKind::Lit(token_lit) => match ast::LitKind::from_token_lit(token_lit) {
@@ -180,7 +182,7 @@ pub fn expand_concat_bytes(
         }
     }
     if !missing_literals.is_empty() {
-        cx.emit_err(errors::ConcatBytesMissingLiteral { spans: missing_literals });
+        cx.dcx().emit_err(errors::ConcatBytesMissingLiteral { spans: missing_literals });
         return base::MacEager::expr(DummyResult::raw_expr(sp, true));
     } else if has_errors {
         return base::MacEager::expr(DummyResult::raw_expr(sp, true));
diff --git a/compiler/rustc_builtin_macros/src/concat_idents.rs b/compiler/rustc_builtin_macros/src/concat_idents.rs
index ee56d45c9c8..17fd3901cc6 100644
--- a/compiler/rustc_builtin_macros/src/concat_idents.rs
+++ b/compiler/rustc_builtin_macros/src/concat_idents.rs
@@ -14,7 +14,7 @@ pub fn expand_concat_idents<'cx>(
     tts: TokenStream,
 ) -> Box<dyn base::MacResult + 'cx> {
     if tts.is_empty() {
-        cx.emit_err(errors::ConcatIdentsMissingArgs { span: sp });
+        cx.dcx().emit_err(errors::ConcatIdentsMissingArgs { span: sp });
         return DummyResult::any(sp);
     }
 
@@ -24,7 +24,7 @@ pub fn expand_concat_idents<'cx>(
             match e {
                 TokenTree::Token(Token { kind: token::Comma, .. }, _) => {}
                 _ => {
-                    cx.emit_err(errors::ConcatIdentsMissingComma { span: sp });
+                    cx.dcx().emit_err(errors::ConcatIdentsMissingComma { span: sp });
                     return DummyResult::any(sp);
                 }
             }
@@ -36,7 +36,7 @@ pub fn expand_concat_idents<'cx>(
                 }
             }
 
-            cx.emit_err(errors::ConcatIdentsIdentArgs { span: sp });
+            cx.dcx().emit_err(errors::ConcatIdentsIdentArgs { span: sp });
             return DummyResult::any(sp);
         }
     }
diff --git a/compiler/rustc_builtin_macros/src/deriving/clone.rs b/compiler/rustc_builtin_macros/src/deriving/clone.rs
index 467fa5a2b15..7bf19f61166 100644
--- a/compiler/rustc_builtin_macros/src/deriving/clone.rs
+++ b/compiler/rustc_builtin_macros/src/deriving/clone.rs
@@ -62,10 +62,10 @@ pub fn expand_deriving_clone(
                     cs_clone_simple("Clone", c, s, sub, true)
                 }));
             }
-            _ => cx.span_bug(span, "`#[derive(Clone)]` on wrong item kind"),
+            _ => cx.dcx().span_bug(span, "`#[derive(Clone)]` on wrong item kind"),
         },
 
-        _ => cx.span_bug(span, "`#[derive(Clone)]` on trait item or impl item"),
+        _ => cx.dcx().span_bug(span, "`#[derive(Clone)]` on trait item or impl item"),
     }
 
     let trait_def = TraitDef {
@@ -144,7 +144,7 @@ fn cs_clone_simple(
                     process_variant(&variant.data);
                 }
             }
-            _ => cx.span_bug(
+            _ => cx.dcx().span_bug(
                 trait_span,
                 format!("unexpected substructure in simple `derive({name})`"),
             ),
@@ -180,10 +180,10 @@ fn cs_clone(
             vdata = &variant.data;
         }
         EnumTag(..) | AllFieldlessEnum(..) => {
-            cx.span_bug(trait_span, format!("enum tags in `derive({name})`",))
+            cx.dcx().span_bug(trait_span, format!("enum tags in `derive({name})`",))
         }
         StaticEnum(..) | StaticStruct(..) => {
-            cx.span_bug(trait_span, format!("associated function in `derive({name})`"))
+            cx.dcx().span_bug(trait_span, format!("associated function in `derive({name})`"))
         }
     }
 
@@ -193,7 +193,7 @@ fn cs_clone(
                 .iter()
                 .map(|field| {
                     let Some(ident) = field.name else {
-                        cx.span_bug(
+                        cx.dcx().span_bug(
                             trait_span,
                             format!("unnamed field in normal struct in `derive({name})`",),
                         );
diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs
index 8a6d219379f..14ae999427d 100644
--- a/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs
+++ b/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs
@@ -99,7 +99,7 @@ fn cs_total_eq_assert(
                 process_variant(&variant.data);
             }
         }
-        _ => cx.span_bug(trait_span, "unexpected substructure in `derive(Eq)`"),
+        _ => cx.dcx().span_bug(trait_span, "unexpected substructure in `derive(Eq)`"),
     }
     BlockOrExpr::new_stmts(stmts)
 }
diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs
index ea81cee78b7..0923acfeedd 100644
--- a/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs
+++ b/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs
@@ -61,7 +61,7 @@ pub fn cs_cmp(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> Bl
         |cx, fold| match fold {
             CsFold::Single(field) => {
                 let [other_expr] = &field.other_selflike_exprs[..] else {
-                    cx.span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`");
+                    cx.dcx().span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`");
                 };
                 let args = thin_vec![field.self_expr.clone(), other_expr.clone()];
                 cx.expr_call_global(field.span, cmp_path.clone(), args)
diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs
index a170468b413..006110cd4b1 100644
--- a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs
+++ b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs
@@ -26,7 +26,8 @@ pub fn expand_deriving_partial_eq(
             |cx, fold| match fold {
                 CsFold::Single(field) => {
                     let [other_expr] = &field.other_selflike_exprs[..] else {
-                        cx.span_bug(field.span, "not exactly 2 arguments in `derive(PartialEq)`");
+                        cx.dcx()
+                            .span_bug(field.span, "not exactly 2 arguments in `derive(PartialEq)`");
                     };
 
                     // We received arguments of type `&T`. Convert them to type `T` by stripping
diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs
index 7f5589210d4..6eccd67f8af 100644
--- a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs
+++ b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs
@@ -95,7 +95,7 @@ fn cs_partial_cmp(
         |cx, fold| match fold {
             CsFold::Single(field) => {
                 let [other_expr] = &field.other_selflike_exprs[..] else {
-                    cx.span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`");
+                    cx.dcx().span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`");
                 };
                 let args = thin_vec![field.self_expr.clone(), other_expr.clone()];
                 cx.expr_call_global(field.span, partial_cmp_path.clone(), args)
diff --git a/compiler/rustc_builtin_macros/src/deriving/debug.rs b/compiler/rustc_builtin_macros/src/deriving/debug.rs
index 50ea8628861..b11a1b6cda1 100644
--- a/compiler/rustc_builtin_macros/src/deriving/debug.rs
+++ b/compiler/rustc_builtin_macros/src/deriving/debug.rs
@@ -55,7 +55,7 @@ fn show_substructure(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>
         EnumMatching(_, _, v, fields) => (v.ident, &v.data, fields),
         AllFieldlessEnum(enum_def) => return show_fieldless_enum(cx, span, enum_def, substr),
         EnumTag(..) | StaticStruct(..) | StaticEnum(..) => {
-            cx.span_bug(span, "nonsensical .fields in `#[derive(Debug)]`")
+            cx.dcx().span_bug(span, "nonsensical .fields in `#[derive(Debug)]`")
         }
     };
 
diff --git a/compiler/rustc_builtin_macros/src/deriving/decodable.rs b/compiler/rustc_builtin_macros/src/deriving/decodable.rs
index bcf11cb4ce9..97d6b82de98 100644
--- a/compiler/rustc_builtin_macros/src/deriving/decodable.rs
+++ b/compiler/rustc_builtin_macros/src/deriving/decodable.rs
@@ -177,7 +177,7 @@ fn decodable_substructure(
                 ],
             )
         }
-        _ => cx.bug("expected StaticEnum or StaticStruct in derive(Decodable)"),
+        _ => cx.dcx().bug("expected StaticEnum or StaticStruct in derive(Decodable)"),
     };
     BlockOrExpr::new_expr(expr)
 }
diff --git a/compiler/rustc_builtin_macros/src/deriving/default.rs b/compiler/rustc_builtin_macros/src/deriving/default.rs
index 43874a242f2..d5a42566e19 100644
--- a/compiler/rustc_builtin_macros/src/deriving/default.rs
+++ b/compiler/rustc_builtin_macros/src/deriving/default.rs
@@ -41,7 +41,7 @@ pub fn expand_deriving_default(
                         default_struct_substructure(cx, trait_span, substr, fields)
                     }
                     StaticEnum(enum_def, _) => default_enum_substructure(cx, trait_span, enum_def),
-                    _ => cx.span_bug(trait_span, "method in `derive(Default)`"),
+                    _ => cx.dcx().span_bug(trait_span, "method in `derive(Default)`"),
                 }
             })),
         }],
@@ -120,7 +120,7 @@ fn extract_default_variant<'a>(
             let suggs = possible_defaults
                 .map(|v| errors::NoDefaultVariantSugg { span: v.span, ident: v.ident })
                 .collect();
-            cx.emit_err(errors::NoDefaultVariant { span: trait_span, suggs });
+            cx.dcx().emit_err(errors::NoDefaultVariant { span: trait_span, suggs });
 
             return Err(());
         }
@@ -140,7 +140,7 @@ fn extract_default_variant<'a>(
                         .then_some(errors::MultipleDefaultsSugg { spans, ident: variant.ident })
                 })
                 .collect();
-            cx.emit_err(errors::MultipleDefaults {
+            cx.dcx().emit_err(errors::MultipleDefaults {
                 span: trait_span,
                 first: first.span,
                 additional: rest.iter().map(|v| v.span).collect(),
@@ -151,12 +151,12 @@ fn extract_default_variant<'a>(
     };
 
     if !matches!(variant.data, VariantData::Unit(..)) {
-        cx.emit_err(errors::NonUnitDefault { span: variant.ident.span });
+        cx.dcx().emit_err(errors::NonUnitDefault { span: variant.ident.span });
         return Err(());
     }
 
     if let Some(non_exhaustive_attr) = attr::find_by_name(&variant.attrs, sym::non_exhaustive) {
-        cx.emit_err(errors::NonExhaustiveDefault {
+        cx.dcx().emit_err(errors::NonExhaustiveDefault {
             span: variant.ident.span,
             non_exhaustive: non_exhaustive_attr.span,
         });
@@ -176,14 +176,14 @@ fn validate_default_attribute(
 
     let attr = match attrs.as_slice() {
         [attr] => attr,
-        [] => cx.bug(
+        [] => cx.dcx().bug(
             "this method must only be called with a variant that has a `#[default]` attribute",
         ),
         [first, rest @ ..] => {
             let sugg = errors::MultipleDefaultAttrsSugg {
                 spans: rest.iter().map(|attr| attr.span).collect(),
             };
-            cx.emit_err(errors::MultipleDefaultAttrs {
+            cx.dcx().emit_err(errors::MultipleDefaultAttrs {
                 span: default_variant.ident.span,
                 first: first.span,
                 first_rest: rest[0].span,
@@ -196,7 +196,7 @@ fn validate_default_attribute(
         }
     };
     if !attr.is_word() {
-        cx.emit_err(errors::DefaultHasArg { span: attr.span });
+        cx.dcx().emit_err(errors::DefaultHasArg { span: attr.span });
 
         return Err(());
     }
@@ -210,7 +210,7 @@ struct DetectNonVariantDefaultAttr<'a, 'b> {
 impl<'a, 'b> rustc_ast::visit::Visitor<'a> for DetectNonVariantDefaultAttr<'a, 'b> {
     fn visit_attribute(&mut self, attr: &'a rustc_ast::Attribute) {
         if attr.has_name(kw::Default) {
-            self.cx.emit_err(errors::NonUnitDefault { span: attr.span });
+            self.cx.dcx().emit_err(errors::NonUnitDefault { span: attr.span });
         }
 
         rustc_ast::visit::walk_attribute(self, attr);
diff --git a/compiler/rustc_builtin_macros/src/deriving/encodable.rs b/compiler/rustc_builtin_macros/src/deriving/encodable.rs
index 2dc20c32497..14d93a8cc23 100644
--- a/compiler/rustc_builtin_macros/src/deriving/encodable.rs
+++ b/compiler/rustc_builtin_macros/src/deriving/encodable.rs
@@ -296,6 +296,6 @@ fn encodable_substructure(
             BlockOrExpr::new_mixed(thin_vec![me], Some(expr))
         }
 
-        _ => cx.bug("expected Struct or EnumMatching in derive(Encodable)"),
+        _ => cx.dcx().bug("expected Struct or EnumMatching in derive(Encodable)"),
     }
 }
diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs
index 841cac78149..6eeb028728c 100644
--- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs
+++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs
@@ -430,7 +430,7 @@ fn find_type_parameters(
         }
 
         fn visit_mac_call(&mut self, mac: &ast::MacCall) {
-            self.cx.emit_err(errors::DeriveMacroCall { span: mac.span() });
+            self.cx.dcx().emit_err(errors::DeriveMacroCall { span: mac.span() });
         }
     }
 
@@ -503,7 +503,7 @@ impl<'a> TraitDef<'a> {
                                 is_packed,
                             )
                         } else {
-                            cx.emit_err(errors::DeriveUnion { span: mitem.span });
+                            cx.dcx().emit_err(errors::DeriveUnion { span: mitem.span });
                             return;
                         }
                     }
@@ -974,7 +974,7 @@ impl<'a> MethodDef<'a> {
             match ty {
                 // Selflike (`&Self`) arguments only occur in non-static methods.
                 Ref(box Self_, _) if !self.is_static() => selflike_args.push(arg_expr),
-                Self_ => cx.span_bug(span, "`Self` in non-return position"),
+                Self_ => cx.dcx().span_bug(span, "`Self` in non-return position"),
                 _ => nonselflike_args.push(arg_expr),
             }
         }
@@ -1441,9 +1441,9 @@ impl<'a> TraitDef<'a> {
 
         let is_tuple = matches!(struct_def, ast::VariantData::Tuple(..));
         match (just_spans.is_empty(), named_idents.is_empty()) {
-            (false, false) => {
-                cx.span_bug(self.span, "a struct with named and unnamed fields in generic `derive`")
-            }
+            (false, false) => cx
+                .dcx()
+                .span_bug(self.span, "a struct with named and unnamed fields in generic `derive`"),
             // named fields
             (_, false) => Named(named_idents),
             // unnamed fields
@@ -1489,7 +1489,7 @@ impl<'a> TraitDef<'a> {
                         let field_pats = pieces_iter
                             .map(|(sp, ident, pat)| {
                                 if ident.is_none() {
-                                    cx.span_bug(
+                                    cx.dcx().span_bug(
                                         sp,
                                         "a braced struct with unnamed fields in `derive`",
                                     );
@@ -1707,7 +1707,9 @@ where
                 tag_check_expr
             }
         }
-        StaticEnum(..) | StaticStruct(..) => cx.span_bug(trait_span, "static function in `derive`"),
-        AllFieldlessEnum(..) => cx.span_bug(trait_span, "fieldless enum in `derive`"),
+        StaticEnum(..) | StaticStruct(..) => {
+            cx.dcx().span_bug(trait_span, "static function in `derive`")
+        }
+        AllFieldlessEnum(..) => cx.dcx().span_bug(trait_span, "fieldless enum in `derive`"),
     }
 }
diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs b/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs
index 1a45c3279f7..603cefdd386 100644
--- a/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs
+++ b/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs
@@ -138,8 +138,8 @@ impl Ty {
                 cx.path_all(span, false, vec![self_ty], params)
             }
             Path(p) => p.to_path(cx, span, self_ty, generics),
-            Ref(..) => cx.span_bug(span, "ref in a path in generic `derive`"),
-            Unit => cx.span_bug(span, "unit in a path in generic `derive`"),
+            Ref(..) => cx.dcx().span_bug(span, "ref in a path in generic `derive`"),
+            Unit => cx.dcx().span_bug(span, "unit in a path in generic `derive`"),
         }
     }
 }
diff --git a/compiler/rustc_builtin_macros/src/deriving/hash.rs b/compiler/rustc_builtin_macros/src/deriving/hash.rs
index 101401f9c85..dd6149cf614 100644
--- a/compiler/rustc_builtin_macros/src/deriving/hash.rs
+++ b/compiler/rustc_builtin_macros/src/deriving/hash.rs
@@ -52,7 +52,7 @@ fn hash_substructure(
     substr: &Substructure<'_>,
 ) -> BlockOrExpr {
     let [state_expr] = substr.nonselflike_args else {
-        cx.span_bug(trait_span, "incorrect number of arguments in `derive(Hash)`");
+        cx.dcx().span_bug(trait_span, "incorrect number of arguments in `derive(Hash)`");
     };
     let call_hash = |span, expr| {
         let hash_path = {
@@ -75,7 +75,7 @@ fn hash_substructure(
             let stmts = thin_vec![call_hash(tag_field.span, tag_field.self_expr.clone())];
             (stmts, match_expr.clone())
         }
-        _ => cx.span_bug(trait_span, "impossible substructure in `derive(Hash)`"),
+        _ => cx.dcx().span_bug(trait_span, "impossible substructure in `derive(Hash)`"),
     };
 
     BlockOrExpr::new_mixed(stmts, match_expr)
diff --git a/compiler/rustc_builtin_macros/src/env.rs b/compiler/rustc_builtin_macros/src/env.rs
index d772642b88b..4b3eaf78557 100644
--- a/compiler/rustc_builtin_macros/src/env.rs
+++ b/compiler/rustc_builtin_macros/src/env.rs
@@ -66,7 +66,7 @@ pub fn expand_env<'cx>(
 ) -> Box<dyn base::MacResult + 'cx> {
     let mut exprs = match get_exprs_from_tts(cx, tts) {
         Some(exprs) if exprs.is_empty() || exprs.len() > 2 => {
-            cx.emit_err(errors::EnvTakesArgs { span: sp });
+            cx.dcx().emit_err(errors::EnvTakesArgs { span: sp });
             return DummyResult::any(sp);
         }
         None => return DummyResult::any(sp),
@@ -101,15 +101,15 @@ pub fn expand_env<'cx>(
             };
 
             if let Some(msg_from_user) = custom_msg {
-                cx.emit_err(errors::EnvNotDefinedWithUserMessage { span, msg_from_user });
+                cx.dcx().emit_err(errors::EnvNotDefinedWithUserMessage { span, msg_from_user });
             } else if is_cargo_env_var(var.as_str()) {
-                cx.emit_err(errors::EnvNotDefined::CargoEnvVar {
+                cx.dcx().emit_err(errors::EnvNotDefined::CargoEnvVar {
                     span,
                     var: *symbol,
                     var_expr: var_expr.ast_deref(),
                 });
             } else {
-                cx.emit_err(errors::EnvNotDefined::CustomEnvVar {
+                cx.dcx().emit_err(errors::EnvNotDefined::CustomEnvVar {
                     span,
                     var: *symbol,
                     var_expr: var_expr.ast_deref(),
diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs
index 2f23146096f..b896e51ddb3 100644
--- a/compiler/rustc_builtin_macros/src/format.rs
+++ b/compiler/rustc_builtin_macros/src/format.rs
@@ -69,7 +69,7 @@ fn parse_args<'a>(ecx: &mut ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<
     let mut p = ecx.new_parser_from_tts(tts);
 
     if p.token == token::Eof {
-        return Err(ecx.create_err(errors::FormatRequiresString { span: sp }));
+        return Err(ecx.dcx().create_err(errors::FormatRequiresString { span: sp }));
     }
 
     let first_token = &p.token;
@@ -126,7 +126,7 @@ fn parse_args<'a>(ecx: &mut ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<
                 p.expect(&token::Eq)?;
                 let expr = p.parse_expr()?;
                 if let Some((_, prev)) = args.by_name(ident.name) {
-                    ecx.emit_err(errors::FormatDuplicateArg {
+                    ecx.dcx().emit_err(errors::FormatDuplicateArg {
                         span: ident.span,
                         prev: prev.kind.ident().unwrap().span,
                         duplicate: ident.span,
@@ -139,7 +139,7 @@ fn parse_args<'a>(ecx: &mut ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<
             _ => {
                 let expr = p.parse_expr()?;
                 if !args.named_args().is_empty() {
-                    ecx.emit_err(errors::PositionalAfterNamed {
+                    ecx.dcx().emit_err(errors::PositionalAfterNamed {
                         span: expr.span,
                         args: args
                             .named_args()
@@ -293,7 +293,7 @@ fn make_format_args(
                 }
             }
         }
-        ecx.emit_err(e);
+        ecx.dcx().emit_err(e);
         return Err(());
     }
 
@@ -351,7 +351,7 @@ fn make_format_args(
                     } else {
                         // For the moment capturing variables from format strings expanded from macros is
                         // disabled (see RFC #2795)
-                        ecx.emit_err(errors::FormatNoArgNamed { span, name });
+                        ecx.dcx().emit_err(errors::FormatNoArgNamed { span, name });
                         DummyResult::raw_expr(span, true)
                     };
                     Ok(args.add(FormatArgument { kind: FormatArgumentKind::Captured(ident), expr }))
@@ -585,7 +585,7 @@ fn invalid_placeholder_type_error(
     } else {
         vec![]
     };
-    ecx.emit_err(errors::FormatUnknownTrait { span: sp.unwrap_or(fmt_span), ty, suggs });
+    ecx.dcx().emit_err(errors::FormatUnknownTrait { span: sp.unwrap_or(fmt_span), ty, suggs });
 }
 
 fn report_missing_placeholders(
@@ -600,12 +600,12 @@ fn report_missing_placeholders(
     fmt_span: Span,
 ) {
     let mut diag = if let &[(span, named)] = &unused[..] {
-        ecx.create_err(errors::FormatUnusedArg { span, named })
+        ecx.dcx().create_err(errors::FormatUnusedArg { span, named })
     } else {
         let unused_labels =
             unused.iter().map(|&(span, named)| errors::FormatUnusedArg { span, named }).collect();
         let unused_spans = unused.iter().map(|&(span, _)| span).collect();
-        ecx.create_err(errors::FormatUnusedArgs {
+        ecx.dcx().create_err(errors::FormatUnusedArgs {
             fmt: fmt_span,
             unused: unused_spans,
             unused_labels,
@@ -776,7 +776,7 @@ fn report_redundant_format_arguments<'a>(
             None
         };
 
-        return Some(ecx.create_err(errors::FormatRedundantArgs {
+        return Some(ecx.dcx().create_err(errors::FormatRedundantArgs {
             n: args_spans.len(),
             span: MultiSpan::from(args_spans),
             note: multispan,
@@ -876,7 +876,7 @@ fn report_invalid_references(
         } else {
             MultiSpan::from_spans(spans)
         };
-        e = ecx.create_err(errors::FormatPositionalMismatch {
+        e = ecx.dcx().create_err(errors::FormatPositionalMismatch {
             span,
             n: num_placeholders,
             desc: num_args_desc,
@@ -942,7 +942,7 @@ fn report_invalid_references(
                 head = indexes.into_iter().map(|i| i.to_string()).collect::<Vec<_>>().join(", ")
             )
         };
-        e = ecx.struct_span_err(
+        e = ecx.dcx().struct_span_err(
             span,
             format!("invalid reference to positional {arg_list} ({num_args_desc})"),
         );
diff --git a/compiler/rustc_builtin_macros/src/global_allocator.rs b/compiler/rustc_builtin_macros/src/global_allocator.rs
index 00c7907cdb4..099defd511b 100644
--- a/compiler/rustc_builtin_macros/src/global_allocator.rs
+++ b/compiler/rustc_builtin_macros/src/global_allocator.rs
@@ -34,7 +34,7 @@ pub fn expand(
     {
         (item, true, ecx.with_def_site_ctxt(ty.span))
     } else {
-        ecx.sess.dcx().emit_err(errors::AllocMustStatics { span: item.span() });
+        ecx.dcx().emit_err(errors::AllocMustStatics { span: item.span() });
         return vec![orig_item];
     };
 
diff --git a/compiler/rustc_builtin_macros/src/source_util.rs b/compiler/rustc_builtin_macros/src/source_util.rs
index 37808854a56..5f05f150094 100644
--- a/compiler/rustc_builtin_macros/src/source_util.rs
+++ b/compiler/rustc_builtin_macros/src/source_util.rs
@@ -193,12 +193,12 @@ pub fn expand_include_str(
                 base::MacEager::expr(cx.expr_str(sp, interned_src))
             }
             Err(_) => {
-                cx.span_err(sp, format!("{} wasn't a utf-8 file", file.display()));
+                cx.dcx().span_err(sp, format!("{} wasn't a utf-8 file", file.display()));
                 DummyResult::any(sp)
             }
         },
         Err(e) => {
-            cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e));
+            cx.dcx().span_err(sp, format!("couldn't read {}: {}", file.display(), e));
             DummyResult::any(sp)
         }
     }
@@ -226,7 +226,7 @@ pub fn expand_include_bytes(
             base::MacEager::expr(expr)
         }
         Err(e) => {
-            cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e));
+            cx.dcx().span_err(sp, format!("couldn't read {}: {}", file.display(), e));
             DummyResult::any(sp)
         }
     }
diff --git a/compiler/rustc_builtin_macros/src/test.rs b/compiler/rustc_builtin_macros/src/test.rs
index d760cea59a7..2af46f175d7 100644
--- a/compiler/rustc_builtin_macros/src/test.rs
+++ b/compiler/rustc_builtin_macros/src/test.rs
@@ -43,7 +43,7 @@ pub fn expand_test_case(
             }
         }
         _ => {
-            ecx.emit_err(errors::TestCaseNonItem { span: anno_item.span() });
+            ecx.dcx().emit_err(errors::TestCaseNonItem { span: anno_item.span() });
             return vec![];
         }
     };
@@ -389,7 +389,7 @@ pub fn expand_test_or_bench(
 }
 
 fn not_testable_error(cx: &ExtCtxt<'_>, attr_sp: Span, item: Option<&ast::Item>) {
-    let dcx = cx.sess.dcx();
+    let dcx = cx.dcx();
     let msg = "the `#[test]` attribute may only be used on a non-associated function";
     let level = match item.map(|i| &i.kind) {
         // These were a warning before #92959 and need to continue being that to avoid breaking
@@ -465,8 +465,6 @@ fn should_ignore_message(i: &ast::Item) -> Option<Symbol> {
 fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic {
     match attr::find_by_name(&i.attrs, sym::should_panic) {
         Some(attr) => {
-            let dcx = cx.sess.dcx();
-
             match attr.meta_item_list() {
                 // Handle #[should_panic(expected = "foo")]
                 Some(list) => {
@@ -476,17 +474,18 @@ fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic {
                         .and_then(|mi| mi.meta_item())
                         .and_then(|mi| mi.value_str());
                     if list.len() != 1 || msg.is_none() {
-                        dcx.struct_span_warn(
-                            attr.span,
-                            "argument must be of the form: \
+                        cx.dcx()
+                            .struct_span_warn(
+                                attr.span,
+                                "argument must be of the form: \
                              `expected = \"error message\"`",
-                        )
-                        .note(
-                            "errors in this attribute were erroneously \
+                            )
+                            .note(
+                                "errors in this attribute were erroneously \
                                 allowed and will become a hard error in a \
                                 future release",
-                        )
-                        .emit();
+                            )
+                            .emit();
                         ShouldPanic::Yes(None)
                     } else {
                         ShouldPanic::Yes(msg)
@@ -534,7 +533,7 @@ fn check_test_signature(
     f: &ast::Fn,
 ) -> Result<(), ErrorGuaranteed> {
     let has_should_panic_attr = attr::contains_name(&i.attrs, sym::should_panic);
-    let dcx = cx.sess.dcx();
+    let dcx = cx.dcx();
 
     if let ast::Unsafe::Yes(span) = f.sig.header.unsafety {
         return Err(dcx.emit_err(errors::TestBadFn { span: i.span, cause: span, kind: "unsafe" }));
@@ -600,7 +599,7 @@ fn check_bench_signature(
     // N.B., inadequate check, but we're running
     // well before resolve, can't get too deep.
     if f.sig.decl.inputs.len() != 1 {
-        return Err(cx.sess.dcx().emit_err(errors::BenchSig { span: i.span }));
+        return Err(cx.dcx().emit_err(errors::BenchSig { span: i.span }));
     }
     Ok(())
 }
diff --git a/compiler/rustc_builtin_macros/src/trace_macros.rs b/compiler/rustc_builtin_macros/src/trace_macros.rs
index af1a392acc5..e076aa6da73 100644
--- a/compiler/rustc_builtin_macros/src/trace_macros.rs
+++ b/compiler/rustc_builtin_macros/src/trace_macros.rs
@@ -21,7 +21,7 @@ pub fn expand_trace_macros(
     };
     err |= cursor.next().is_some();
     if err {
-        cx.emit_err(errors::TraceMacros { span: sp });
+        cx.dcx().emit_err(errors::TraceMacros { span: sp });
     } else {
         cx.set_trace_macros(value);
     }