authorbors <bors@rust-lang.org> 2024-06-18 16:49:19 UTC
committerbors <bors@rust-lang.org> 2024-06-18 16:49:19 UTC
logdd104ef16315e2387fe94e8c43eb5a66e3dbd660
treebc7569f842f9454815433b814d6cdf846f91948b
parent8814b926f49bc5780753ed9533853679a1181357
parent3f34196839730cfb5b241667cfcc9b94599ea0c1

Auto merge of #126623 - oli-obk:do_not_count_errors, r=davidtwco

Replace all `&DiagCtxt` with a `DiagCtxtHandle<'_>` wrapper type r? `@davidtwco` This paves the way for tracking more state (e.g. error tainting) in the diagnostic context handle Basically I will add a field to the `DiagCtxtHandle` that refers back to the `InferCtxt`'s (and others) `Option<ErrorHandled>`, allowing us to immediately taint these contexts when emitting an error and not needing manual tainting anymore (which is easy to forget and we don't do in general anyway)

118 files changed, 773 insertions(+), 915 deletions(-)

compiler/rustc_ast_lowering/src/lib.rs+2-2
......@@ -50,7 +50,7 @@ use rustc_data_structures::fx::FxIndexSet;
5050use rustc_data_structures::sorted_map::SortedMap;
5151use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
5252use rustc_data_structures::sync::Lrc;
53use rustc_errors::{DiagArgFromDisplay, DiagCtxt, StashKey};
53use rustc_errors::{DiagArgFromDisplay, DiagCtxtHandle, StashKey};
5454use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res};
5555use rustc_hir::def_id::{LocalDefId, LocalDefIdMap, CRATE_DEF_ID, LOCAL_CRATE};
5656use rustc_hir::{self as hir};
......@@ -188,7 +188,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
188188 }
189189 }
190190
191 pub(crate) fn dcx(&self) -> &'hir DiagCtxt {
191 pub(crate) fn dcx(&self) -> DiagCtxtHandle<'hir> {
192192 self.tcx.dcx()
193193 }
194194}
compiler/rustc_ast_passes/src/ast_validation.rs+3-6
......@@ -12,6 +12,7 @@ use rustc_ast::visit::{walk_list, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor}
1212use rustc_ast::*;
1313use rustc_ast_pretty::pprust::{self, State};
1414use rustc_data_structures::fx::FxIndexMap;
15use rustc_errors::DiagCtxtHandle;
1516use rustc_feature::Features;
1617use rustc_parse::validate_attr;
1718use rustc_session::lint::builtin::{
......@@ -269,7 +270,7 @@ impl<'a> AstValidator<'a> {
269270 }
270271 }
271272
272 fn dcx(&self) -> &rustc_errors::DiagCtxt {
273 fn dcx(&self) -> DiagCtxtHandle<'a> {
273274 self.session.dcx()
274275 }
275276
......@@ -809,11 +810,7 @@ impl<'a> AstValidator<'a> {
809810
810811/// Checks that generic parameters are in the correct order,
811812/// which is lifetimes, then types and then consts. (`<'a, T, const N: usize>`)
812fn validate_generic_param_order(
813 dcx: &rustc_errors::DiagCtxt,
814 generics: &[GenericParam],
815 span: Span,
816) {
813fn validate_generic_param_order(dcx: DiagCtxtHandle<'_>, generics: &[GenericParam], span: Span) {
817814 let mut max_param: Option<ParamKindOrd> = None;
818815 let mut out_of_order = FxIndexMap::default();
819816 let mut param_idents = Vec::with_capacity(generics.len());
compiler/rustc_ast_passes/src/show_span.rs+3-2
......@@ -8,6 +8,7 @@ use std::str::FromStr;
88use rustc_ast as ast;
99use rustc_ast::visit;
1010use rustc_ast::visit::Visitor;
11use rustc_errors::DiagCtxtHandle;
1112
1213use crate::errors;
1314
......@@ -31,7 +32,7 @@ impl FromStr for Mode {
3132}
3233
3334struct ShowSpanVisitor<'a> {
34 dcx: &'a rustc_errors::DiagCtxt,
35 dcx: DiagCtxtHandle<'a>,
3536 mode: Mode,
3637}
3738
......@@ -58,7 +59,7 @@ impl<'a> Visitor<'a> for ShowSpanVisitor<'a> {
5859 }
5960}
6061
61pub fn run(dcx: &rustc_errors::DiagCtxt, mode: &str, krate: &ast::Crate) {
62pub fn run(dcx: DiagCtxtHandle<'_>, mode: &str, krate: &ast::Crate) {
6263 let Ok(mode) = mode.parse() else {
6364 return;
6465 };
compiler/rustc_attr/src/builtin.rs+1-1
......@@ -596,7 +596,7 @@ pub fn eval_condition(
596596 features: Option<&Features>,
597597 eval: &mut impl FnMut(Condition) -> bool,
598598) -> bool {
599 let dcx = &sess.psess.dcx;
599 let dcx = sess.dcx();
600600 match &cfg.kind {
601601 ast::MetaItemKind::List(mis) if cfg.name_or_empty() == sym::version => {
602602 try_gate_cfg(sym::version, cfg.span, sess, features);
compiler/rustc_attr/src/session_diagnostics.rs+4-3
......@@ -1,7 +1,8 @@
11use std::num::IntErrorKind;
22
33use rustc_ast as ast;
4use rustc_errors::{codes::*, Applicability, Diag, DiagCtxt, Diagnostic, EmissionGuarantee, Level};
4use rustc_errors::DiagCtxtHandle;
5use rustc_errors::{codes::*, Applicability, Diag, Diagnostic, EmissionGuarantee, Level};
56use rustc_macros::{Diagnostic, Subdiagnostic};
67use rustc_span::{Span, Symbol};
78
......@@ -49,7 +50,7 @@ pub(crate) struct UnknownMetaItem<'a> {
4950
5051// Manual implementation to be able to format `expected` items correctly.
5152impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for UnknownMetaItem<'_> {
52 fn into_diag(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
53 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
5354 let expected = self.expected.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>();
5455 Diag::new(dcx, level, fluent::attr_unknown_meta_item)
5556 .with_span(self.span)
......@@ -202,7 +203,7 @@ pub(crate) struct UnsupportedLiteral {
202203}
203204
204205impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for UnsupportedLiteral {
205 fn into_diag(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
206 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
206207 let mut diag = Diag::new(
207208 dcx,
208209 level,
compiler/rustc_borrowck/src/borrowck_errors.rs+2-2
......@@ -1,13 +1,13 @@
11#![allow(rustc::diagnostic_outside_of_impl)]
22#![allow(rustc::untranslatable_diagnostic)]
33
4use rustc_errors::{codes::*, struct_span_code_err, Diag, DiagCtxt};
4use rustc_errors::{codes::*, struct_span_code_err, Diag, DiagCtxtHandle};
55use rustc_middle::span_bug;
66use rustc_middle::ty::{self, Ty, TyCtxt};
77use rustc_span::Span;
88
99impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
10 pub fn dcx(&self) -> &'tcx DiagCtxt {
10 pub fn dcx(&self) -> DiagCtxtHandle<'tcx> {
1111 self.infcx.dcx()
1212 }
1313
compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs+58-88
......@@ -228,7 +228,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
228228 seen_spans.insert(move_span);
229229 }
230230
231 use_spans.var_path_only_subdiag(self.dcx(), &mut err, desired_action);
231 use_spans.var_path_only_subdiag(&mut err, desired_action);
232232
233233 if !is_loop_move {
234234 err.span_label(
......@@ -303,24 +303,18 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
303303 if needs_note {
304304 if let Some(local) = place.as_local() {
305305 let span = self.body.local_decls[local].source_info.span;
306 err.subdiagnostic(
307 self.dcx(),
308 crate::session_diagnostics::TypeNoCopy::Label {
309 is_partial_move,
310 ty,
311 place: &note_msg,
312 span,
313 },
314 );
306 err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label {
307 is_partial_move,
308 ty,
309 place: &note_msg,
310 span,
311 });
315312 } else {
316 err.subdiagnostic(
317 self.dcx(),
318 crate::session_diagnostics::TypeNoCopy::Note {
319 is_partial_move,
320 ty,
321 place: &note_msg,
322 },
323 );
313 err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Note {
314 is_partial_move,
315 ty,
316 place: &note_msg,
317 });
324318 };
325319 }
326320
......@@ -597,7 +591,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
597591 E0381,
598592 "{used} binding {desc}{isnt_initialized}"
599593 );
600 use_spans.var_path_only_subdiag(self.dcx(), &mut err, desired_action);
594 use_spans.var_path_only_subdiag(&mut err, desired_action);
601595
602596 if let InitializationRequiringAction::PartialAssignment
603597 | InitializationRequiringAction::Assignment = desired_action
......@@ -996,7 +990,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
996990 &self,
997991 err: &mut Diag<'_>,
998992 ty: Ty<'tcx>,
999 expr: &'cx hir::Expr<'cx>,
993 expr: &hir::Expr<'_>,
1000994 ) {
1001995 let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
1002996 let hir::ExprKind::Struct(struct_qpath, fields, Some(base)) = expr.kind else { return };
......@@ -1084,8 +1078,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
10841078 &self,
10851079 err: &mut Diag<'_>,
10861080 ty: Ty<'tcx>,
1087 mut expr: &'cx hir::Expr<'cx>,
1088 mut other_expr: Option<&'cx hir::Expr<'cx>>,
1081 mut expr: &'tcx hir::Expr<'tcx>,
1082 mut other_expr: Option<&'tcx hir::Expr<'tcx>>,
10891083 use_spans: Option<UseSpans<'tcx>>,
10901084 ) {
10911085 if let hir::ExprKind::Struct(_, _, Some(_)) = expr.kind {
......@@ -1410,13 +1404,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
14101404 &value_msg,
14111405 );
14121406
1413 borrow_spans.var_path_only_subdiag(
1414 self.dcx(),
1415 &mut err,
1416 crate::InitializationRequiringAction::Borrow,
1417 );
1407 borrow_spans.var_path_only_subdiag(&mut err, crate::InitializationRequiringAction::Borrow);
14181408
1419 move_spans.var_subdiag(self.dcx(), &mut err, None, |kind, var_span| {
1409 move_spans.var_subdiag(&mut err, None, |kind, var_span| {
14201410 use crate::session_diagnostics::CaptureVarCause::*;
14211411 match kind {
14221412 hir::ClosureKind::Coroutine(_) => MoveUseInCoroutine { var_span },
......@@ -1468,7 +1458,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
14681458 borrow_span,
14691459 &self.describe_any_place(borrow.borrowed_place.as_ref()),
14701460 );
1471 borrow_spans.var_subdiag(self.dcx(), &mut err, Some(borrow.kind), |kind, var_span| {
1461 borrow_spans.var_subdiag(&mut err, Some(borrow.kind), |kind, var_span| {
14721462 use crate::session_diagnostics::CaptureVarCause::*;
14731463 let place = &borrow.borrowed_place;
14741464 let desc_place = self.describe_any_place(place.as_ref());
......@@ -1633,7 +1623,6 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
16331623 "mutably borrow",
16341624 );
16351625 borrow_spans.var_subdiag(
1636 self.dcx(),
16371626 &mut err,
16381627 Some(BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture }),
16391628 |kind, var_span| {
......@@ -1730,64 +1719,45 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
17301719 };
17311720
17321721 if issued_spans == borrow_spans {
1733 borrow_spans.var_subdiag(
1734 self.dcx(),
1735 &mut err,
1736 Some(gen_borrow_kind),
1737 |kind, var_span| {
1738 use crate::session_diagnostics::CaptureVarCause::*;
1739 match kind {
1740 hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1741 place: desc_place,
1742 var_span,
1743 is_single_var: false,
1744 },
1745 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1746 BorrowUsePlaceClosure {
1747 place: desc_place,
1748 var_span,
1749 is_single_var: false,
1750 }
1751 }
1722 borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
1723 use crate::session_diagnostics::CaptureVarCause::*;
1724 match kind {
1725 hir::ClosureKind::Coroutine(_) => BorrowUsePlaceCoroutine {
1726 place: desc_place,
1727 var_span,
1728 is_single_var: false,
1729 },
1730 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1731 BorrowUsePlaceClosure { place: desc_place, var_span, is_single_var: false }
17521732 }
1753 },
1754 );
1733 }
1734 });
17551735 } else {
1756 issued_spans.var_subdiag(
1757 self.dcx(),
1758 &mut err,
1759 Some(issued_borrow.kind),
1760 |kind, var_span| {
1761 use crate::session_diagnostics::CaptureVarCause::*;
1762 let borrow_place = &issued_borrow.borrowed_place;
1763 let borrow_place_desc = self.describe_any_place(borrow_place.as_ref());
1764 match kind {
1765 hir::ClosureKind::Coroutine(_) => {
1766 FirstBorrowUsePlaceCoroutine { place: borrow_place_desc, var_span }
1767 }
1768 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1769 FirstBorrowUsePlaceClosure { place: borrow_place_desc, var_span }
1770 }
1736 issued_spans.var_subdiag(&mut err, Some(issued_borrow.kind), |kind, var_span| {
1737 use crate::session_diagnostics::CaptureVarCause::*;
1738 let borrow_place = &issued_borrow.borrowed_place;
1739 let borrow_place_desc = self.describe_any_place(borrow_place.as_ref());
1740 match kind {
1741 hir::ClosureKind::Coroutine(_) => {
1742 FirstBorrowUsePlaceCoroutine { place: borrow_place_desc, var_span }
17711743 }
1772 },
1773 );
1744 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1745 FirstBorrowUsePlaceClosure { place: borrow_place_desc, var_span }
1746 }
1747 }
1748 });
17741749
1775 borrow_spans.var_subdiag(
1776 self.dcx(),
1777 &mut err,
1778 Some(gen_borrow_kind),
1779 |kind, var_span| {
1780 use crate::session_diagnostics::CaptureVarCause::*;
1781 match kind {
1782 hir::ClosureKind::Coroutine(_) => {
1783 SecondBorrowUsePlaceCoroutine { place: desc_place, var_span }
1784 }
1785 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1786 SecondBorrowUsePlaceClosure { place: desc_place, var_span }
1787 }
1750 borrow_spans.var_subdiag(&mut err, Some(gen_borrow_kind), |kind, var_span| {
1751 use crate::session_diagnostics::CaptureVarCause::*;
1752 match kind {
1753 hir::ClosureKind::Coroutine(_) => {
1754 SecondBorrowUsePlaceCoroutine { place: desc_place, var_span }
17881755 }
1789 },
1790 );
1756 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
1757 SecondBorrowUsePlaceClosure { place: desc_place, var_span }
1758 }
1759 }
1760 });
17911761 }
17921762
17931763 if union_type_name != "" {
......@@ -2016,7 +1986,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
20161986 );
20171987 }
20181988
2019 pub(crate) fn find_expr(&self, span: Span) -> Option<&hir::Expr<'_>> {
1989 pub(crate) fn find_expr(&self, span: Span) -> Option<&'tcx hir::Expr<'tcx>> {
20201990 let tcx = self.infcx.tcx;
20211991 let body_id = tcx.hir_node(self.mir_hir_id()).body_id()?;
20221992 let mut expr_finder = FindExprBySpan::new(span, tcx);
......@@ -2961,7 +2931,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
29612931 err.span_label(borrow_span, "borrowed value does not live long enough");
29622932 err.span_label(drop_span, format!("`{name}` dropped here while still borrowed"));
29632933
2964 borrow_spans.args_subdiag(self.dcx(), &mut err, |args_span| {
2934 borrow_spans.args_subdiag(&mut err, |args_span| {
29652935 crate::session_diagnostics::CaptureArgLabel::Capture {
29662936 is_within: borrow_spans.for_coroutine(),
29672937 args_span,
......@@ -3219,7 +3189,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
32193189 None,
32203190 );
32213191
3222 borrow_spans.args_subdiag(self.dcx(), &mut err, |args_span| {
3192 borrow_spans.args_subdiag(&mut err, |args_span| {
32233193 crate::session_diagnostics::CaptureArgLabel::Capture {
32243194 is_within: borrow_spans.for_coroutine(),
32253195 args_span,
......@@ -3680,7 +3650,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
36803650 "assign",
36813651 );
36823652
3683 loan_spans.var_subdiag(self.dcx(), &mut err, Some(loan.kind), |kind, var_span| {
3653 loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
36843654 use crate::session_diagnostics::CaptureVarCause::*;
36853655 match kind {
36863656 hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
......@@ -3698,7 +3668,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
36983668
36993669 let mut err = self.cannot_assign_to_borrowed(span, loan_span, &descr_place);
37003670
3701 loan_spans.var_subdiag(self.dcx(), &mut err, Some(loan.kind), |kind, var_span| {
3671 loan_spans.var_subdiag(&mut err, Some(loan.kind), |kind, var_span| {
37023672 use crate::session_diagnostics::CaptureVarCause::*;
37033673 match kind {
37043674 hir::ClosureKind::Coroutine(_) => BorrowUseInCoroutine { var_span },
compiler/rustc_borrowck/src/diagnostics/mod.rs+89-145
......@@ -4,8 +4,8 @@ use crate::session_diagnostics::{
44 CaptureArgLabel, CaptureReasonLabel, CaptureReasonNote, CaptureReasonSuggest, CaptureVarCause,
55 CaptureVarKind, CaptureVarPathUseCause, OnClosureNote,
66};
7use rustc_errors::MultiSpan;
78use rustc_errors::{Applicability, Diag};
8use rustc_errors::{DiagCtxt, MultiSpan};
99use rustc_hir::def::{CtorKind, Namespace};
1010use rustc_hir::CoroutineKind;
1111use rustc_hir::{self as hir, LangItem};
......@@ -130,16 +130,13 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
130130 if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind() {
131131 let did = did.expect_local();
132132 if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) {
133 diag.subdiagnostic(
134 self.dcx(),
135 OnClosureNote::InvokedTwice {
136 place_name: &ty::place_to_string_for_capture(
137 self.infcx.tcx,
138 hir_place,
139 ),
140 span: *span,
141 },
142 );
133 diag.subdiagnostic(OnClosureNote::InvokedTwice {
134 place_name: &ty::place_to_string_for_capture(
135 self.infcx.tcx,
136 hir_place,
137 ),
138 span: *span,
139 });
143140 return true;
144141 }
145142 }
......@@ -152,13 +149,10 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
152149 if let ty::Closure(did, _) = self.body.local_decls[target].ty.kind() {
153150 let did = did.expect_local();
154151 if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) {
155 diag.subdiagnostic(
156 self.dcx(),
157 OnClosureNote::MovedTwice {
158 place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place),
159 span: *span,
160 },
161 );
152 diag.subdiagnostic(OnClosureNote::MovedTwice {
153 place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place),
154 span: *span,
155 });
162156 return true;
163157 }
164158 }
......@@ -591,14 +585,9 @@ impl UseSpans<'_> {
591585
592586 /// Add a span label to the arguments of the closure, if it exists.
593587 #[allow(rustc::diagnostic_outside_of_impl)]
594 pub(super) fn args_subdiag(
595 self,
596 dcx: &DiagCtxt,
597 err: &mut Diag<'_>,
598 f: impl FnOnce(Span) -> CaptureArgLabel,
599 ) {
588 pub(super) fn args_subdiag(self, err: &mut Diag<'_>, f: impl FnOnce(Span) -> CaptureArgLabel) {
600589 if let UseSpans::ClosureUse { args_span, .. } = self {
601 err.subdiagnostic(dcx, f(args_span));
590 err.subdiagnostic(f(args_span));
602591 }
603592 }
604593
......@@ -607,7 +596,6 @@ impl UseSpans<'_> {
607596 #[allow(rustc::diagnostic_outside_of_impl)]
608597 pub(super) fn var_path_only_subdiag(
609598 self,
610 dcx: &DiagCtxt,
611599 err: &mut Diag<'_>,
612600 action: crate::InitializationRequiringAction,
613601 ) {
......@@ -616,26 +604,20 @@ impl UseSpans<'_> {
616604 if let UseSpans::ClosureUse { closure_kind, path_span, .. } = self {
617605 match closure_kind {
618606 hir::ClosureKind::Coroutine(_) => {
619 err.subdiagnostic(
620 dcx,
621 match action {
622 Borrow => BorrowInCoroutine { path_span },
623 MatchOn | Use => UseInCoroutine { path_span },
624 Assignment => AssignInCoroutine { path_span },
625 PartialAssignment => AssignPartInCoroutine { path_span },
626 },
627 );
607 err.subdiagnostic(match action {
608 Borrow => BorrowInCoroutine { path_span },
609 MatchOn | Use => UseInCoroutine { path_span },
610 Assignment => AssignInCoroutine { path_span },
611 PartialAssignment => AssignPartInCoroutine { path_span },
612 });
628613 }
629614 hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => {
630 err.subdiagnostic(
631 dcx,
632 match action {
633 Borrow => BorrowInClosure { path_span },
634 MatchOn | Use => UseInClosure { path_span },
635 Assignment => AssignInClosure { path_span },
636 PartialAssignment => AssignPartInClosure { path_span },
637 },
638 );
615 err.subdiagnostic(match action {
616 Borrow => BorrowInClosure { path_span },
617 MatchOn | Use => UseInClosure { path_span },
618 Assignment => AssignInClosure { path_span },
619 PartialAssignment => AssignPartInClosure { path_span },
620 });
639621 }
640622 }
641623 }
......@@ -645,32 +627,28 @@ impl UseSpans<'_> {
645627 #[allow(rustc::diagnostic_outside_of_impl)]
646628 pub(super) fn var_subdiag(
647629 self,
648 dcx: &DiagCtxt,
649630 err: &mut Diag<'_>,
650631 kind: Option<rustc_middle::mir::BorrowKind>,
651632 f: impl FnOnce(hir::ClosureKind, Span) -> CaptureVarCause,
652633 ) {
653634 if let UseSpans::ClosureUse { closure_kind, capture_kind_span, path_span, .. } = self {
654635 if capture_kind_span != path_span {
655 err.subdiagnostic(
656 dcx,
657 match kind {
658 Some(kd) => match kd {
659 rustc_middle::mir::BorrowKind::Shared
660 | rustc_middle::mir::BorrowKind::Fake(_) => {
661 CaptureVarKind::Immut { kind_span: capture_kind_span }
662 }
636 err.subdiagnostic(match kind {
637 Some(kd) => match kd {
638 rustc_middle::mir::BorrowKind::Shared
639 | rustc_middle::mir::BorrowKind::Fake(_) => {
640 CaptureVarKind::Immut { kind_span: capture_kind_span }
641 }
663642
664 rustc_middle::mir::BorrowKind::Mut { .. } => {
665 CaptureVarKind::Mut { kind_span: capture_kind_span }
666 }
667 },
668 None => CaptureVarKind::Move { kind_span: capture_kind_span },
643 rustc_middle::mir::BorrowKind::Mut { .. } => {
644 CaptureVarKind::Mut { kind_span: capture_kind_span }
645 }
669646 },
670 );
647 None => CaptureVarKind::Move { kind_span: capture_kind_span },
648 });
671649 };
672650 let diag = f(closure_kind, path_span);
673 err.subdiagnostic(dcx, diag);
651 err.subdiagnostic(diag);
674652 }
675653 }
676654
......@@ -1042,15 +1020,12 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
10421020 CallKind::FnCall { fn_trait_id, self_ty }
10431021 if self.infcx.tcx.is_lang_item(fn_trait_id, LangItem::FnOnce) =>
10441022 {
1045 err.subdiagnostic(
1046 self.dcx(),
1047 CaptureReasonLabel::Call {
1048 fn_call_span,
1049 place_name: &place_name,
1050 is_partial,
1051 is_loop_message,
1052 },
1053 );
1023 err.subdiagnostic(CaptureReasonLabel::Call {
1024 fn_call_span,
1025 place_name: &place_name,
1026 is_partial,
1027 is_loop_message,
1028 });
10541029 // Check if the move occurs on a value because of a call on a closure that comes
10551030 // from a type parameter `F: FnOnce()`. If so, we provide a targeted `note`:
10561031 // ```
......@@ -1119,27 +1094,20 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
11191094 );
11201095 err.span_note(span, fluent::borrowck_moved_a_fn_once_in_call_call);
11211096 } else {
1122 err.subdiagnostic(
1123 self.dcx(),
1124 CaptureReasonNote::FnOnceMoveInCall { var_span },
1125 );
1097 err.subdiagnostic(CaptureReasonNote::FnOnceMoveInCall { var_span });
11261098 }
11271099 }
11281100 CallKind::Operator { self_arg, trait_id, .. } => {
11291101 let self_arg = self_arg.unwrap();
1130 err.subdiagnostic(
1131 self.dcx(),
1132 CaptureReasonLabel::OperatorUse {
1133 fn_call_span,
1134 place_name: &place_name,
1135 is_partial,
1136 is_loop_message,
1137 },
1138 );
1102 err.subdiagnostic(CaptureReasonLabel::OperatorUse {
1103 fn_call_span,
1104 place_name: &place_name,
1105 is_partial,
1106 is_loop_message,
1107 });
11391108 if self.fn_self_span_reported.insert(fn_span) {
11401109 let lang = self.infcx.tcx.lang_items();
11411110 err.subdiagnostic(
1142 self.dcx(),
11431111 if [lang.not_trait(), lang.deref_trait(), lang.neg_trait()]
11441112 .contains(&Some(trait_id))
11451113 {
......@@ -1164,14 +1132,11 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
11641132 );
11651133
11661134 let func = tcx.def_path_str(method_did);
1167 err.subdiagnostic(
1168 self.dcx(),
1169 CaptureReasonNote::FuncTakeSelf {
1170 func,
1171 place_name: place_name.clone(),
1172 span: self_arg.span,
1173 },
1174 );
1135 err.subdiagnostic(CaptureReasonNote::FuncTakeSelf {
1136 func,
1137 place_name: place_name.clone(),
1138 span: self_arg.span,
1139 });
11751140 }
11761141 let parent_did = tcx.parent(method_did);
11771142 let parent_self_ty =
......@@ -1185,10 +1150,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
11851150 matches!(tcx.get_diagnostic_name(def_id), Some(sym::Option | sym::Result))
11861151 });
11871152 if is_option_or_result && maybe_reinitialized_locations_is_empty {
1188 err.subdiagnostic(
1189 self.dcx(),
1190 CaptureReasonLabel::BorrowContent { var_span },
1191 );
1153 err.subdiagnostic(CaptureReasonLabel::BorrowContent { var_span });
11921154 }
11931155 if let Some((CallDesugaringKind::ForLoopIntoIter, _)) = desugaring {
11941156 let ty = moved_place.ty(self.body, tcx).ty;
......@@ -1202,24 +1164,18 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
12021164 _ => false,
12031165 };
12041166 if suggest {
1205 err.subdiagnostic(
1206 self.dcx(),
1207 CaptureReasonSuggest::IterateSlice {
1208 ty,
1209 span: move_span.shrink_to_lo(),
1210 },
1211 );
1167 err.subdiagnostic(CaptureReasonSuggest::IterateSlice {
1168 ty,
1169 span: move_span.shrink_to_lo(),
1170 });
12121171 }
12131172
1214 err.subdiagnostic(
1215 self.dcx(),
1216 CaptureReasonLabel::ImplicitCall {
1217 fn_call_span,
1218 place_name: &place_name,
1219 is_partial,
1220 is_loop_message,
1221 },
1222 );
1173 err.subdiagnostic(CaptureReasonLabel::ImplicitCall {
1174 fn_call_span,
1175 place_name: &place_name,
1176 is_partial,
1177 is_loop_message,
1178 });
12231179 // If the moved place was a `&mut` ref, then we can
12241180 // suggest to reborrow it where it was moved, so it
12251181 // will still be valid by the time we get to the usage.
......@@ -1243,25 +1199,19 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
12431199 }
12441200 } else {
12451201 if let Some((CallDesugaringKind::Await, _)) = desugaring {
1246 err.subdiagnostic(
1247 self.dcx(),
1248 CaptureReasonLabel::Await {
1249 fn_call_span,
1250 place_name: &place_name,
1251 is_partial,
1252 is_loop_message,
1253 },
1254 );
1202 err.subdiagnostic(CaptureReasonLabel::Await {
1203 fn_call_span,
1204 place_name: &place_name,
1205 is_partial,
1206 is_loop_message,
1207 });
12551208 } else {
1256 err.subdiagnostic(
1257 self.dcx(),
1258 CaptureReasonLabel::MethodCall {
1259 fn_call_span,
1260 place_name: &place_name,
1261 is_partial,
1262 is_loop_message,
1263 },
1264 );
1209 err.subdiagnostic(CaptureReasonLabel::MethodCall {
1210 fn_call_span,
1211 place_name: &place_name,
1212 is_partial,
1213 is_loop_message,
1214 });
12651215 }
12661216 // Erase and shadow everything that could be passed to the new infcx.
12671217 let ty = moved_place.ty(self.body, tcx).ty;
......@@ -1276,12 +1226,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
12761226 )
12771227 && self.infcx.can_eq(self.param_env, ty, self_ty)
12781228 {
1279 err.subdiagnostic(
1280 self.dcx(),
1281 CaptureReasonSuggest::FreshReborrow {
1282 span: move_span.shrink_to_hi(),
1283 },
1284 );
1229 err.subdiagnostic(CaptureReasonSuggest::FreshReborrow {
1230 span: move_span.shrink_to_hi(),
1231 });
12851232 has_sugg = true;
12861233 }
12871234 if let Some(clone_trait) = tcx.lang_items().clone_trait() {
......@@ -1368,20 +1315,17 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
13681315 }
13691316 } else {
13701317 if move_span != span || is_loop_message {
1371 err.subdiagnostic(
1372 self.dcx(),
1373 CaptureReasonLabel::MovedHere {
1374 move_span,
1375 is_partial,
1376 is_move_msg,
1377 is_loop_message,
1378 },
1379 );
1318 err.subdiagnostic(CaptureReasonLabel::MovedHere {
1319 move_span,
1320 is_partial,
1321 is_move_msg,
1322 is_loop_message,
1323 });
13801324 }
13811325 // If the move error occurs due to a loop, don't show
13821326 // another message for the same span
13831327 if !is_loop_message {
1384 move_spans.var_subdiag(self.dcx(), err, None, |kind, var_span| match kind {
1328 move_spans.var_subdiag(err, None, |kind, var_span| match kind {
13851329 hir::ClosureKind::Coroutine(_) => {
13861330 CaptureVarCause::PartialMoveUseInCoroutine { var_span, is_partial }
13871331 }
compiler/rustc_borrowck/src/diagnostics/move_errors.rs+19-28
......@@ -579,15 +579,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
579579 self.suggest_cloning(err, place_ty, expr, self.find_expr(other_span), None);
580580 }
581581
582 err.subdiagnostic(
583 self.dcx(),
584 crate::session_diagnostics::TypeNoCopy::Label {
585 is_partial_move: false,
586 ty: place_ty,
587 place: &place_desc,
588 span,
589 },
590 );
582 err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label {
583 is_partial_move: false,
584 ty: place_ty,
585 place: &place_desc,
586 span,
587 });
591588 } else {
592589 binds_to.sort();
593590 binds_to.dedup();
......@@ -620,17 +617,14 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
620617 );
621618 }
622619
623 err.subdiagnostic(
624 self.dcx(),
625 crate::session_diagnostics::TypeNoCopy::Label {
626 is_partial_move: false,
627 ty: place_ty,
628 place: &place_desc,
629 span: use_span,
630 },
631 );
620 err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label {
621 is_partial_move: false,
622 ty: place_ty,
623 place: &place_desc,
624 span: use_span,
625 });
632626
633 use_spans.args_subdiag(self.dcx(), err, |args_span| {
627 use_spans.args_subdiag(err, |args_span| {
634628 crate::session_diagnostics::CaptureArgLabel::MoveOutPlace {
635629 place: place_desc,
636630 args_span,
......@@ -733,15 +727,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
733727 self.suggest_cloning(err, bind_to.ty, expr, None, None);
734728 }
735729
736 err.subdiagnostic(
737 self.dcx(),
738 crate::session_diagnostics::TypeNoCopy::Label {
739 is_partial_move: false,
740 ty: bind_to.ty,
741 place: place_desc,
742 span: binding_span,
743 },
744 );
730 err.subdiagnostic(crate::session_diagnostics::TypeNoCopy::Label {
731 is_partial_move: false,
732 ty: bind_to.ty,
733 place: place_desc,
734 span: binding_span,
735 });
745736 }
746737 }
747738
compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs-1
......@@ -230,7 +230,6 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
230230 }
231231 if suggest {
232232 borrow_spans.var_subdiag(
233 self.dcx(),
234233 &mut err,
235234 Some(mir::BorrowKind::Mut { kind: mir::MutBorrowKind::Default }),
236235 |_kind, var_span| {
compiler/rustc_borrowck/src/diagnostics/region_errors.rs+5-5
......@@ -631,13 +631,13 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
631631 let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap();
632632 let upvar_def_span = self.infcx.tcx.hir().span(def_hir);
633633 let upvar_span = upvars_map.get(&def_hir).unwrap().span;
634 diag.subdiagnostic(self.dcx(), VarHereDenote::Defined { span: upvar_def_span });
635 diag.subdiagnostic(self.dcx(), VarHereDenote::Captured { span: upvar_span });
634 diag.subdiagnostic(VarHereDenote::Defined { span: upvar_def_span });
635 diag.subdiagnostic(VarHereDenote::Captured { span: upvar_span });
636636 }
637637 }
638638
639639 if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
640 diag.subdiagnostic(self.dcx(), VarHereDenote::FnMutInferred { span: fr_span });
640 diag.subdiagnostic(VarHereDenote::FnMutInferred { span: fr_span });
641641 }
642642
643643 self.suggest_move_on_borrowing_closure(&mut diag);
......@@ -810,7 +810,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
810810 },
811811 };
812812
813 diag.subdiagnostic(self.dcx(), err_category);
813 diag.subdiagnostic(err_category);
814814
815815 self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
816816 self.suggest_adding_lifetime_params(&mut diag, *fr, *outlived_fr);
......@@ -1008,7 +1008,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
10081008 ident.span,
10091009 "calling this method introduces the `impl`'s `'static` requirement",
10101010 );
1011 err.subdiagnostic(self.dcx(), RequireStaticErr::UsedImpl { multi_span });
1011 err.subdiagnostic(RequireStaticErr::UsedImpl { multi_span });
10121012 err.span_suggestion_verbose(
10131013 span.shrink_to_hi(),
10141014 "consider relaxing the implicit `'static` requirement",
compiler/rustc_builtin_macros/src/asm.rs+4-4
......@@ -46,7 +46,7 @@ pub fn parse_asm_args<'a>(
4646 sp: Span,
4747 is_global_asm: bool,
4848) -> PResult<'a, AsmArgs> {
49 let dcx = &p.psess.dcx;
49 let dcx = p.dcx();
5050
5151 if p.token == token::Eof {
5252 return Err(dcx.create_err(errors::AsmRequiresTemplate { span: sp }));
......@@ -307,7 +307,7 @@ pub fn parse_asm_args<'a>(
307307fn err_duplicate_option(p: &Parser<'_>, symbol: Symbol, span: Span) {
308308 // Tool-only output
309309 let full_span = if p.token.kind == token::Comma { span.to(p.token.span) } else { span };
310 p.psess.dcx.emit_err(errors::AsmOptAlreadyprovided { span, symbol, full_span });
310 p.dcx().emit_err(errors::AsmOptAlreadyprovided { span, symbol, full_span });
311311}
312312
313313/// Try to set the provided option in the provided `AsmArgs`.
......@@ -379,7 +379,7 @@ fn parse_clobber_abi<'a>(p: &mut Parser<'a>, args: &mut AsmArgs) -> PResult<'a,
379379 p.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
380380
381381 if p.eat(&token::CloseDelim(Delimiter::Parenthesis)) {
382 return Err(p.psess.dcx.create_err(errors::NonABI { span: p.token.span }));
382 return Err(p.dcx().create_err(errors::NonABI { span: p.token.span }));
383383 }
384384
385385 let mut new_abis = Vec::new();
......@@ -390,7 +390,7 @@ fn parse_clobber_abi<'a>(p: &mut Parser<'a>, args: &mut AsmArgs) -> PResult<'a,
390390 }
391391 Err(opt_lit) => {
392392 let span = opt_lit.map_or(p.token.span, |lit| lit.span);
393 let mut err = p.psess.dcx.struct_span_err(span, "expected string literal");
393 let mut err = p.dcx().struct_span_err(span, "expected string literal");
394394 err.span_label(span, "not a string literal");
395395 return Err(err);
396396 }
compiler/rustc_builtin_macros/src/cmdline_attrs.rs+1-1
......@@ -26,7 +26,7 @@ pub fn inject(krate: &mut ast::Crate, psess: &ParseSess, attrs: &[String]) {
2626 };
2727 let end_span = parser.token.span;
2828 if parser.token != token::Eof {
29 psess.dcx.emit_err(errors::InvalidCrateAttr { span: start_span.to(end_span) });
29 psess.dcx().emit_err(errors::InvalidCrateAttr { span: start_span.to(end_span) });
3030 continue;
3131 }
3232
compiler/rustc_builtin_macros/src/errors.rs+3-3
......@@ -1,5 +1,5 @@
11use rustc_errors::{
2 codes::*, Diag, DiagCtxt, Diagnostic, EmissionGuarantee, Level, MultiSpan,
2 codes::*, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, MultiSpan,
33 SingleLabelManySpans, SubdiagMessageOp, Subdiagnostic,
44};
55use rustc_macros::{Diagnostic, Subdiagnostic};
......@@ -434,7 +434,7 @@ pub(crate) struct EnvNotDefinedWithUserMessage {
434434// Hand-written implementation to support custom user messages.
435435impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for EnvNotDefinedWithUserMessage {
436436 #[track_caller]
437 fn into_diag(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
437 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
438438 #[expect(
439439 rustc::untranslatable_diagnostic,
440440 reason = "cannot translate user-provided messages"
......@@ -801,7 +801,7 @@ pub(crate) struct AsmClobberNoReg {
801801}
802802
803803impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for AsmClobberNoReg {
804 fn into_diag(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
804 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
805805 // eager translation as `span_labels` takes `AsRef<str>`
806806 let lbl1 = dcx.eagerly_translate_to_string(
807807 crate::fluent_generated::builtin_macros_asm_clobber_abi,
compiler/rustc_builtin_macros/src/proc_macro_harness.rs+3-2
......@@ -3,6 +3,7 @@ use rustc_ast::ptr::P;
33use rustc_ast::visit::{self, Visitor};
44use rustc_ast::{self as ast, attr, NodeId};
55use rustc_ast_pretty::pprust;
6use rustc_errors::DiagCtxtHandle;
67use rustc_expand::base::{parse_macro_name_and_helper_attrs, ExtCtxt, ResolverExpand};
78use rustc_expand::expand::{AstFragment, ExpansionConfig};
89use rustc_feature::Features;
......@@ -38,7 +39,7 @@ enum ProcMacro {
3839struct CollectProcMacros<'a> {
3940 macros: Vec<ProcMacro>,
4041 in_root: bool,
41 dcx: &'a rustc_errors::DiagCtxt,
42 dcx: DiagCtxtHandle<'a>,
4243 source_map: &'a SourceMap,
4344 is_proc_macro_crate: bool,
4445 is_test_crate: bool,
......@@ -52,7 +53,7 @@ pub fn inject(
5253 is_proc_macro_crate: bool,
5354 has_proc_macro_decls: bool,
5455 is_test_crate: bool,
55 dcx: &rustc_errors::DiagCtxt,
56 dcx: DiagCtxtHandle<'_>,
5657) {
5758 let ecfg = ExpansionConfig::default("proc_macro".to_string(), features);
5859 let mut cx = ExtCtxt::new(sess, ecfg, resolver, None);
compiler/rustc_builtin_macros/src/test_harness.rs+2-1
......@@ -6,6 +6,7 @@ use rustc_ast::mut_visit::*;
66use rustc_ast::ptr::P;
77use rustc_ast::visit::{walk_item, Visitor};
88use rustc_ast::{attr, ModKind};
9use rustc_errors::DiagCtxtHandle;
910use rustc_expand::base::{ExtCtxt, ResolverExpand};
1011use rustc_expand::expand::{AstFragment, ExpansionConfig};
1112use rustc_feature::Features;
......@@ -391,7 +392,7 @@ fn get_test_name(i: &ast::Item) -> Option<Symbol> {
391392 attr::first_attr_value_str_by_name(&i.attrs, sym::rustc_test_marker)
392393}
393394
394fn get_test_runner(dcx: &rustc_errors::DiagCtxt, krate: &ast::Crate) -> Option<ast::Path> {
395fn get_test_runner(dcx: DiagCtxtHandle<'_>, krate: &ast::Crate) -> Option<ast::Path> {
395396 let test_attr = attr::find_by_name(&krate.attrs, sym::test_runner)?;
396397 let meta_list = test_attr.meta_item_list()?;
397398 let span = test_attr.span;
compiler/rustc_codegen_cranelift/src/concurrency_limiter.rs+2-1
......@@ -1,6 +1,7 @@
11use std::sync::{Arc, Condvar, Mutex};
22
33use jobserver::HelperThread;
4use rustc_errors::DiagCtxtHandle;
45use rustc_session::Session;
56
67// FIXME don't panic when a worker thread panics
......@@ -46,7 +47,7 @@ impl ConcurrencyLimiter {
4647 }
4748 }
4849
49 pub(super) fn acquire(&self, dcx: &rustc_errors::DiagCtxt) -> ConcurrencyLimiterToken {
50 pub(super) fn acquire(&self, dcx: DiagCtxtHandle<'_>) -> ConcurrencyLimiterToken {
5051 let mut state = self.state.lock().unwrap();
5152 loop {
5253 state.assert_invariants();
compiler/rustc_codegen_gcc/src/back/lto.rs+6-5
......@@ -28,7 +28,7 @@ use rustc_codegen_ssa::back::write::{CodegenContext, FatLtoInput};
2828use rustc_codegen_ssa::traits::*;
2929use rustc_codegen_ssa::{looks_like_rust_object_file, ModuleCodegen, ModuleKind};
3030use rustc_data_structures::memmap::Mmap;
31use rustc_errors::{DiagCtxt, FatalError};
31use rustc_errors::{DiagCtxtHandle, FatalError};
3232use rustc_hir::def_id::LOCAL_CRATE;
3333use rustc_middle::dep_graph::WorkProduct;
3434use rustc_middle::middle::exported_symbols::{SymbolExportInfo, SymbolExportLevel};
......@@ -59,7 +59,7 @@ struct LtoData {
5959
6060fn prepare_lto(
6161 cgcx: &CodegenContext<GccCodegenBackend>,
62 dcx: &DiagCtxt,
62 dcx: DiagCtxtHandle<'_>,
6363) -> Result<LtoData, FatalError> {
6464 let export_threshold = match cgcx.lto {
6565 // We're just doing LTO for our one crate
......@@ -179,12 +179,13 @@ pub(crate) fn run_fat(
179179 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
180180) -> Result<LtoModuleCodegen<GccCodegenBackend>, FatalError> {
181181 let dcx = cgcx.create_dcx();
182 let lto_data = prepare_lto(cgcx, &dcx)?;
182 let dcx = dcx.handle();
183 let lto_data = prepare_lto(cgcx, dcx)?;
183184 /*let symbols_below_threshold =
184185 lto_data.symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();*/
185186 fat_lto(
186187 cgcx,
187 &dcx,
188 dcx,
188189 modules,
189190 cached_modules,
190191 lto_data.upstream_modules,
......@@ -195,7 +196,7 @@ pub(crate) fn run_fat(
195196
196197fn fat_lto(
197198 cgcx: &CodegenContext<GccCodegenBackend>,
198 _dcx: &DiagCtxt,
199 _dcx: DiagCtxtHandle<'_>,
199200 modules: Vec<FatLtoInput<GccCodegenBackend>>,
200201 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
201202 mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
compiler/rustc_codegen_gcc/src/back/write.rs+3-3
......@@ -4,7 +4,7 @@ use gccjit::OutputKind;
44use rustc_codegen_ssa::back::link::ensure_removed;
55use rustc_codegen_ssa::back::write::{BitcodeSection, CodegenContext, EmitObj, ModuleConfig};
66use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
7use rustc_errors::DiagCtxt;
7use rustc_errors::DiagCtxtHandle;
88use rustc_fs_util::link_or_copy;
99use rustc_session::config::OutputType;
1010use rustc_span::fatal_error::FatalError;
......@@ -15,7 +15,7 @@ use crate::{GccCodegenBackend, GccContext};
1515
1616pub(crate) unsafe fn codegen(
1717 cgcx: &CodegenContext<GccCodegenBackend>,
18 dcx: &DiagCtxt,
18 dcx: DiagCtxtHandle<'_>,
1919 module: ModuleCodegen<GccContext>,
2020 config: &ModuleConfig,
2121) -> Result<CompiledModule, FatalError> {
......@@ -166,7 +166,7 @@ pub(crate) unsafe fn codegen(
166166
167167pub(crate) fn link(
168168 _cgcx: &CodegenContext<GccCodegenBackend>,
169 _dcx: &DiagCtxt,
169 _dcx: DiagCtxtHandle<'_>,
170170 mut _modules: Vec<ModuleCodegen<GccContext>>,
171171) -> Result<ModuleCodegen<GccContext>, FatalError> {
172172 unimplemented!();
compiler/rustc_codegen_gcc/src/errors.rs+3-3
......@@ -1,4 +1,4 @@
1use rustc_errors::{Diag, DiagCtxt, Diagnostic, EmissionGuarantee, Level};
1use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level};
22use rustc_macros::{Diagnostic, Subdiagnostic};
33use rustc_span::Span;
44
......@@ -90,13 +90,13 @@ pub(crate) struct TargetFeatureDisableOrEnable<'a> {
9090pub(crate) struct MissingFeatures;
9191
9292impl<G: EmissionGuarantee> Diagnostic<'_, G> for TargetFeatureDisableOrEnable<'_> {
93 fn into_diag(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
93 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
9494 let mut diag = Diag::new(dcx, level, fluent::codegen_gcc_target_feature_disable_or_enable);
9595 if let Some(span) = self.span {
9696 diag.span(span);
9797 };
9898 if let Some(missing_features) = self.missing_features {
99 diag.subdiagnostic(dcx, missing_features);
99 diag.subdiagnostic(missing_features);
100100 }
101101 diag.arg("features", self.features.join(", "));
102102 diag
compiler/rustc_codegen_gcc/src/lib.rs+9-12
......@@ -16,13 +16,7 @@
1616#![allow(internal_features)]
1717#![doc(rust_logo)]
1818#![feature(rustdoc_internals)]
19#![feature(
20 rustc_private,
21 decl_macro,
22 never_type,
23 trusted_len,
24 hash_raw_entry
25)]
19#![feature(rustc_private, decl_macro, never_type, trusted_len, hash_raw_entry)]
2620#![allow(broken_intra_doc_links)]
2721#![recursion_limit = "256"]
2822#![warn(rust_2018_idioms)]
......@@ -104,7 +98,7 @@ use rustc_codegen_ssa::traits::{
10498use rustc_codegen_ssa::{CodegenResults, CompiledModule, ModuleCodegen};
10599use rustc_data_structures::fx::FxIndexMap;
106100use rustc_data_structures::sync::IntoDynSyncSend;
107use rustc_errors::{DiagCtxt, ErrorGuaranteed};
101use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
108102use rustc_metadata::EncodedMetadata;
109103use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
110104use rustc_middle::ty::TyCtxt;
......@@ -386,7 +380,7 @@ impl WriteBackendMethods for GccCodegenBackend {
386380
387381 unsafe fn optimize(
388382 _cgcx: &CodegenContext<Self>,
389 _dcx: &DiagCtxt,
383 _dcx: DiagCtxtHandle<'_>,
390384 module: &ModuleCodegen<Self::Module>,
391385 config: &ModuleConfig,
392386 ) -> Result<(), FatalError> {
......@@ -411,14 +405,17 @@ impl WriteBackendMethods for GccCodegenBackend {
411405
412406 unsafe fn codegen(
413407 cgcx: &CodegenContext<Self>,
414 dcx: &DiagCtxt,
408 dcx: DiagCtxtHandle<'_>,
415409 module: ModuleCodegen<Self::Module>,
416410 config: &ModuleConfig,
417411 ) -> Result<CompiledModule, FatalError> {
418412 back::write::codegen(cgcx, dcx, module, config)
419413 }
420414
421 fn prepare_thin(_module: ModuleCodegen<Self::Module>, _emit_summary: bool) -> (String, Self::ThinBuffer) {
415 fn prepare_thin(
416 _module: ModuleCodegen<Self::Module>,
417 _emit_summary: bool,
418 ) -> (String, Self::ThinBuffer) {
422419 unimplemented!();
423420 }
424421
......@@ -428,7 +425,7 @@ impl WriteBackendMethods for GccCodegenBackend {
428425
429426 fn run_link(
430427 cgcx: &CodegenContext<Self>,
431 dcx: &DiagCtxt,
428 dcx: DiagCtxtHandle<'_>,
432429 modules: Vec<ModuleCodegen<Self::Module>>,
433430 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
434431 back::write::link(cgcx, dcx, modules)
compiler/rustc_codegen_llvm/src/back/lto.rs+20-17
......@@ -14,7 +14,7 @@ use rustc_codegen_ssa::traits::*;
1414use rustc_codegen_ssa::{looks_like_rust_object_file, ModuleCodegen, ModuleKind};
1515use rustc_data_structures::fx::FxHashMap;
1616use rustc_data_structures::memmap::Mmap;
17use rustc_errors::{DiagCtxt, FatalError};
17use rustc_errors::{DiagCtxtHandle, FatalError};
1818use rustc_hir::def_id::LOCAL_CRATE;
1919use rustc_middle::bug;
2020use rustc_middle::dep_graph::WorkProduct;
......@@ -49,7 +49,7 @@ pub fn crate_type_allows_lto(crate_type: CrateType) -> bool {
4949
5050fn prepare_lto(
5151 cgcx: &CodegenContext<LlvmCodegenBackend>,
52 dcx: &DiagCtxt,
52 dcx: DiagCtxtHandle<'_>,
5353) -> Result<(Vec<CString>, Vec<(SerializedModule<ModuleBuffer>, CString)>), FatalError> {
5454 let export_threshold = match cgcx.lto {
5555 // We're just doing LTO for our one crate
......@@ -203,10 +203,11 @@ pub(crate) fn run_fat(
203203 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
204204) -> Result<LtoModuleCodegen<LlvmCodegenBackend>, FatalError> {
205205 let dcx = cgcx.create_dcx();
206 let (symbols_below_threshold, upstream_modules) = prepare_lto(cgcx, &dcx)?;
206 let dcx = dcx.handle();
207 let (symbols_below_threshold, upstream_modules) = prepare_lto(cgcx, dcx)?;
207208 let symbols_below_threshold =
208209 symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
209 fat_lto(cgcx, &dcx, modules, cached_modules, upstream_modules, &symbols_below_threshold)
210 fat_lto(cgcx, dcx, modules, cached_modules, upstream_modules, &symbols_below_threshold)
210211}
211212
212213/// Performs thin LTO by performing necessary global analysis and returning two
......@@ -218,7 +219,8 @@ pub(crate) fn run_thin(
218219 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
219220) -> Result<(Vec<LtoModuleCodegen<LlvmCodegenBackend>>, Vec<WorkProduct>), FatalError> {
220221 let dcx = cgcx.create_dcx();
221 let (symbols_below_threshold, upstream_modules) = prepare_lto(cgcx, &dcx)?;
222 let dcx = dcx.handle();
223 let (symbols_below_threshold, upstream_modules) = prepare_lto(cgcx, dcx)?;
222224 let symbols_below_threshold =
223225 symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
224226 if cgcx.opts.cg.linker_plugin_lto.enabled() {
......@@ -227,7 +229,7 @@ pub(crate) fn run_thin(
227229 is deferred to the linker"
228230 );
229231 }
230 thin_lto(cgcx, &dcx, modules, upstream_modules, cached_modules, &symbols_below_threshold)
232 thin_lto(cgcx, dcx, modules, upstream_modules, cached_modules, &symbols_below_threshold)
231233}
232234
233235pub(crate) fn prepare_thin(
......@@ -241,7 +243,7 @@ pub(crate) fn prepare_thin(
241243
242244fn fat_lto(
243245 cgcx: &CodegenContext<LlvmCodegenBackend>,
244 dcx: &DiagCtxt,
246 dcx: DiagCtxtHandle<'_>,
245247 modules: Vec<FatLtoInput<LlvmCodegenBackend>>,
246248 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
247249 mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
......@@ -436,7 +438,7 @@ impl Drop for Linker<'_> {
436438/// they all go out of scope.
437439fn thin_lto(
438440 cgcx: &CodegenContext<LlvmCodegenBackend>,
439 dcx: &DiagCtxt,
441 dcx: DiagCtxtHandle<'_>,
440442 modules: Vec<(String, ThinBuffer)>,
441443 serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
442444 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
......@@ -593,7 +595,7 @@ fn thin_lto(
593595
594596pub(crate) fn run_pass_manager(
595597 cgcx: &CodegenContext<LlvmCodegenBackend>,
596 dcx: &DiagCtxt,
598 dcx: DiagCtxtHandle<'_>,
597599 module: &mut ModuleCodegen<ModuleLlvm>,
598600 thin: bool,
599601) -> Result<(), FatalError> {
......@@ -714,10 +716,11 @@ pub unsafe fn optimize_thin_module(
714716 cgcx: &CodegenContext<LlvmCodegenBackend>,
715717) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
716718 let dcx = cgcx.create_dcx();
719 let dcx = dcx.handle();
717720
718721 let module_name = &thin_module.shared.module_names[thin_module.idx];
719722 let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, module_name.to_str().unwrap());
720 let tm = (cgcx.tm_factory)(tm_factory_config).map_err(|e| write::llvm_err(&dcx, e))?;
723 let tm = (cgcx.tm_factory)(tm_factory_config).map_err(|e| write::llvm_err(dcx, e))?;
721724
722725 // Right now the implementation we've got only works over serialized
723726 // modules, so we create a fresh new LLVM context and parse the module
......@@ -725,7 +728,7 @@ pub unsafe fn optimize_thin_module(
725728 // crates but for locally codegened modules we may be able to reuse
726729 // that LLVM Context and Module.
727730 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
728 let llmod_raw = parse_module(llcx, module_name, thin_module.data(), &dcx)? as *const _;
731 let llmod_raw = parse_module(llcx, module_name, thin_module.data(), dcx)? as *const _;
729732 let mut module = ModuleCodegen {
730733 module_llvm: ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) },
731734 name: thin_module.name().to_string(),
......@@ -748,7 +751,7 @@ pub unsafe fn optimize_thin_module(
748751 let _timer =
749752 cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_rename", thin_module.name());
750753 if !llvm::LLVMRustPrepareThinLTORename(thin_module.shared.data.0, llmod, target) {
751 return Err(write::llvm_err(&dcx, LlvmError::PrepareThinLtoModule));
754 return Err(write::llvm_err(dcx, LlvmError::PrepareThinLtoModule));
752755 }
753756 save_temp_bitcode(cgcx, &module, "thin-lto-after-rename");
754757 }
......@@ -758,7 +761,7 @@ pub unsafe fn optimize_thin_module(
758761 .prof
759762 .generic_activity_with_arg("LLVM_thin_lto_resolve_weak", thin_module.name());
760763 if !llvm::LLVMRustPrepareThinLTOResolveWeak(thin_module.shared.data.0, llmod) {
761 return Err(write::llvm_err(&dcx, LlvmError::PrepareThinLtoModule));
764 return Err(write::llvm_err(dcx, LlvmError::PrepareThinLtoModule));
762765 }
763766 save_temp_bitcode(cgcx, &module, "thin-lto-after-resolve");
764767 }
......@@ -768,7 +771,7 @@ pub unsafe fn optimize_thin_module(
768771 .prof
769772 .generic_activity_with_arg("LLVM_thin_lto_internalize", thin_module.name());
770773 if !llvm::LLVMRustPrepareThinLTOInternalize(thin_module.shared.data.0, llmod) {
771 return Err(write::llvm_err(&dcx, LlvmError::PrepareThinLtoModule));
774 return Err(write::llvm_err(dcx, LlvmError::PrepareThinLtoModule));
772775 }
773776 save_temp_bitcode(cgcx, &module, "thin-lto-after-internalize");
774777 }
......@@ -777,7 +780,7 @@ pub unsafe fn optimize_thin_module(
777780 let _timer =
778781 cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_import", thin_module.name());
779782 if !llvm::LLVMRustPrepareThinLTOImport(thin_module.shared.data.0, llmod, target) {
780 return Err(write::llvm_err(&dcx, LlvmError::PrepareThinLtoModule));
783 return Err(write::llvm_err(dcx, LlvmError::PrepareThinLtoModule));
781784 }
782785 save_temp_bitcode(cgcx, &module, "thin-lto-after-import");
783786 }
......@@ -789,7 +792,7 @@ pub unsafe fn optimize_thin_module(
789792 // little differently.
790793 {
791794 info!("running thin lto passes over {}", module.name);
792 run_pass_manager(cgcx, &dcx, &mut module, true)?;
795 run_pass_manager(cgcx, dcx, &mut module, true)?;
793796 save_temp_bitcode(cgcx, &module, "thin-lto-after-pm");
794797 }
795798 }
......@@ -859,7 +862,7 @@ pub fn parse_module<'a>(
859862 cx: &'a llvm::Context,
860863 name: &CStr,
861864 data: &[u8],
862 dcx: &DiagCtxt,
865 dcx: DiagCtxtHandle<'_>,
863866) -> Result<&'a llvm::Module, FatalError> {
864867 unsafe {
865868 llvm::LLVMRustParseBitcodeForLTO(cx, data.as_ptr(), data.len(), name.as_ptr())
compiler/rustc_codegen_llvm/src/back/write.rs+10-10
......@@ -26,7 +26,7 @@ use rustc_codegen_ssa::traits::*;
2626use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
2727use rustc_data_structures::profiling::SelfProfilerRef;
2828use rustc_data_structures::small_c_str::SmallCStr;
29use rustc_errors::{DiagCtxt, FatalError, Level};
29use rustc_errors::{DiagCtxtHandle, FatalError, Level};
3030use rustc_fs_util::{link_or_copy, path_to_c_string};
3131use rustc_middle::ty::TyCtxt;
3232use rustc_session::config::{self, Lto, OutputType, Passes};
......@@ -47,7 +47,7 @@ use std::slice;
4747use std::str;
4848use std::sync::Arc;
4949
50pub fn llvm_err<'a>(dcx: &rustc_errors::DiagCtxt, err: LlvmError<'a>) -> FatalError {
50pub fn llvm_err<'a>(dcx: DiagCtxtHandle<'_>, err: LlvmError<'a>) -> FatalError {
5151 match llvm::last_error() {
5252 Some(llvm_err) => dcx.emit_almost_fatal(WithLlvmError(err, llvm_err)),
5353 None => dcx.emit_almost_fatal(err),
......@@ -55,7 +55,7 @@ pub fn llvm_err<'a>(dcx: &rustc_errors::DiagCtxt, err: LlvmError<'a>) -> FatalEr
5555}
5656
5757pub fn write_output_file<'ll>(
58 dcx: &rustc_errors::DiagCtxt,
58 dcx: DiagCtxtHandle<'_>,
5959 target: &'ll llvm::TargetMachine,
6060 pm: &llvm::PassManager<'ll>,
6161 m: &'ll llvm::Module,
......@@ -331,7 +331,7 @@ pub enum CodegenDiagnosticsStage {
331331}
332332
333333pub struct DiagnosticHandlers<'a> {
334 data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a DiagCtxt),
334 data: *mut (&'a CodegenContext<LlvmCodegenBackend>, DiagCtxtHandle<'a>),
335335 llcx: &'a llvm::Context,
336336 old_handler: Option<&'a llvm::DiagnosticHandler>,
337337}
......@@ -339,7 +339,7 @@ pub struct DiagnosticHandlers<'a> {
339339impl<'a> DiagnosticHandlers<'a> {
340340 pub fn new(
341341 cgcx: &'a CodegenContext<LlvmCodegenBackend>,
342 dcx: &'a DiagCtxt,
342 dcx: DiagCtxtHandle<'a>,
343343 llcx: &'a llvm::Context,
344344 module: &ModuleCodegen<ModuleLlvm>,
345345 stage: CodegenDiagnosticsStage,
......@@ -428,7 +428,7 @@ unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void
428428 if user.is_null() {
429429 return;
430430 }
431 let (cgcx, dcx) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &DiagCtxt));
431 let (cgcx, dcx) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, DiagCtxtHandle<'_>));
432432
433433 match llvm::diagnostic::Diagnostic::unpack(info) {
434434 llvm::diagnostic::InlineAsm(inline) => {
......@@ -506,7 +506,7 @@ fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
506506
507507pub(crate) unsafe fn llvm_optimize(
508508 cgcx: &CodegenContext<LlvmCodegenBackend>,
509 dcx: &DiagCtxt,
509 dcx: DiagCtxtHandle<'_>,
510510 module: &ModuleCodegen<ModuleLlvm>,
511511 config: &ModuleConfig,
512512 opt_level: config::OptLevel,
......@@ -604,7 +604,7 @@ pub(crate) unsafe fn llvm_optimize(
604604// Unsafe due to LLVM calls.
605605pub(crate) unsafe fn optimize(
606606 cgcx: &CodegenContext<LlvmCodegenBackend>,
607 dcx: &DiagCtxt,
607 dcx: DiagCtxtHandle<'_>,
608608 module: &ModuleCodegen<ModuleLlvm>,
609609 config: &ModuleConfig,
610610) -> Result<(), FatalError> {
......@@ -637,7 +637,7 @@ pub(crate) unsafe fn optimize(
637637
638638pub(crate) fn link(
639639 cgcx: &CodegenContext<LlvmCodegenBackend>,
640 dcx: &DiagCtxt,
640 dcx: DiagCtxtHandle<'_>,
641641 mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
642642) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
643643 use super::lto::{Linker, ModuleBuffer};
......@@ -660,7 +660,7 @@ pub(crate) fn link(
660660
661661pub(crate) unsafe fn codegen(
662662 cgcx: &CodegenContext<LlvmCodegenBackend>,
663 dcx: &DiagCtxt,
663 dcx: DiagCtxtHandle<'_>,
664664 module: ModuleCodegen<ModuleLlvm>,
665665 config: &ModuleConfig,
666666) -> Result<CompiledModule, FatalError> {
compiler/rustc_codegen_llvm/src/errors.rs+5-5
......@@ -4,7 +4,7 @@ use std::path::Path;
44
55use crate::fluent_generated as fluent;
66use rustc_data_structures::small_c_str::SmallCStr;
7use rustc_errors::{Diag, DiagCtxt, Diagnostic, EmissionGuarantee, Level};
7use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level};
88use rustc_macros::{Diagnostic, Subdiagnostic};
99use rustc_span::Span;
1010
......@@ -100,7 +100,7 @@ pub(crate) struct DynamicLinkingWithLTO;
100100pub(crate) struct ParseTargetMachineConfig<'a>(pub LlvmError<'a>);
101101
102102impl<G: EmissionGuarantee> Diagnostic<'_, G> for ParseTargetMachineConfig<'_> {
103 fn into_diag(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
103 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
104104 let diag: Diag<'_, G> = self.0.into_diag(dcx, level);
105105 let (message, _) = diag.messages.first().expect("`LlvmError` with no message");
106106 let message = dcx.eagerly_translate_to_string(message.clone(), diag.args.iter());
......@@ -120,13 +120,13 @@ pub(crate) struct TargetFeatureDisableOrEnable<'a> {
120120pub(crate) struct MissingFeatures;
121121
122122impl<G: EmissionGuarantee> Diagnostic<'_, G> for TargetFeatureDisableOrEnable<'_> {
123 fn into_diag(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
123 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
124124 let mut diag = Diag::new(dcx, level, fluent::codegen_llvm_target_feature_disable_or_enable);
125125 if let Some(span) = self.span {
126126 diag.span(span);
127127 };
128128 if let Some(missing_features) = self.missing_features {
129 diag.subdiagnostic(dcx, missing_features);
129 diag.subdiagnostic(missing_features);
130130 }
131131 diag.arg("features", self.features.join(", "));
132132 diag
......@@ -180,7 +180,7 @@ pub enum LlvmError<'a> {
180180pub(crate) struct WithLlvmError<'a>(pub LlvmError<'a>, pub String);
181181
182182impl<G: EmissionGuarantee> Diagnostic<'_, G> for WithLlvmError<'_> {
183 fn into_diag(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
183 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
184184 use LlvmError::*;
185185 let msg_with_llvm_err = match &self.0 {
186186 WriteOutput { .. } => fluent::codegen_llvm_write_output_with_llvm_err,
compiler/rustc_codegen_llvm/src/lib.rs+7-6
......@@ -31,7 +31,7 @@ use rustc_codegen_ssa::traits::*;
3131use rustc_codegen_ssa::ModuleCodegen;
3232use rustc_codegen_ssa::{CodegenResults, CompiledModule};
3333use rustc_data_structures::fx::FxIndexMap;
34use rustc_errors::{DiagCtxt, ErrorGuaranteed, FatalError};
34use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, FatalError};
3535use rustc_metadata::EncodedMetadata;
3636use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
3737use rustc_middle::ty::TyCtxt;
......@@ -191,7 +191,7 @@ impl WriteBackendMethods for LlvmCodegenBackend {
191191 }
192192 fn run_link(
193193 cgcx: &CodegenContext<Self>,
194 dcx: &DiagCtxt,
194 dcx: DiagCtxtHandle<'_>,
195195 modules: Vec<ModuleCodegen<Self::Module>>,
196196 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
197197 back::write::link(cgcx, dcx, modules)
......@@ -212,7 +212,7 @@ impl WriteBackendMethods for LlvmCodegenBackend {
212212 }
213213 unsafe fn optimize(
214214 cgcx: &CodegenContext<Self>,
215 dcx: &DiagCtxt,
215 dcx: DiagCtxtHandle<'_>,
216216 module: &ModuleCodegen<Self::Module>,
217217 config: &ModuleConfig,
218218 ) -> Result<(), FatalError> {
......@@ -223,7 +223,8 @@ impl WriteBackendMethods for LlvmCodegenBackend {
223223 module: &mut ModuleCodegen<Self::Module>,
224224 ) -> Result<(), FatalError> {
225225 let dcx = cgcx.create_dcx();
226 back::lto::run_pass_manager(cgcx, &dcx, module, false)
226 let dcx = dcx.handle();
227 back::lto::run_pass_manager(cgcx, dcx, module, false)
227228 }
228229 unsafe fn optimize_thin(
229230 cgcx: &CodegenContext<Self>,
......@@ -233,7 +234,7 @@ impl WriteBackendMethods for LlvmCodegenBackend {
233234 }
234235 unsafe fn codegen(
235236 cgcx: &CodegenContext<Self>,
236 dcx: &DiagCtxt,
237 dcx: DiagCtxtHandle<'_>,
237238 module: ModuleCodegen<Self::Module>,
238239 config: &ModuleConfig,
239240 ) -> Result<CompiledModule, FatalError> {
......@@ -441,7 +442,7 @@ impl ModuleLlvm {
441442 cgcx: &CodegenContext<LlvmCodegenBackend>,
442443 name: &CStr,
443444 buffer: &[u8],
444 dcx: &DiagCtxt,
445 dcx: DiagCtxtHandle<'_>,
445446 ) -> Result<Self, FatalError> {
446447 unsafe {
447448 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
compiler/rustc_codegen_ssa/src/back/link.rs+2-2
......@@ -3,7 +3,7 @@ use rustc_ast::CRATE_NODE_ID;
33use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
44use rustc_data_structures::memmap::Mmap;
55use rustc_data_structures::temp_dir::MaybeTempDir;
6use rustc_errors::{DiagCtxt, ErrorGuaranteed, FatalError};
6use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, FatalError};
77use rustc_fs_util::{fix_windows_verbatim_for_gcc, try_canonicalize};
88use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
99use rustc_metadata::find_native_static_library;
......@@ -54,7 +54,7 @@ use std::process::{ExitStatus, Output, Stdio};
5454use std::{env, fmt, fs, io, mem, str};
5555use tracing::{debug, info, warn};
5656
57pub fn ensure_removed(dcx: &DiagCtxt, path: &Path) {
57pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) {
5858 if let Err(e) = fs::remove_file(path) {
5959 if e.kind() != io::ErrorKind::NotFound {
6060 dcx.err(format!("failed to remove {}: {}", path.display(), e));
compiler/rustc_codegen_ssa/src/back/write.rs+13-6
......@@ -891,9 +891,10 @@ fn execute_optimize_work_item<B: ExtraBackendMethods>(
891891 module_config: &ModuleConfig,
892892) -> Result<WorkItemResult<B>, FatalError> {
893893 let dcx = cgcx.create_dcx();
894 let dcx = dcx.handle();
894895
895896 unsafe {
896 B::optimize(cgcx, &dcx, &module, module_config)?;
897 B::optimize(cgcx, dcx, &module, module_config)?;
897898 }
898899
899900 // After we've done the initial round of optimizations we need to
......@@ -954,7 +955,11 @@ fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
954955 match link_or_copy(&source_file, &output_path) {
955956 Ok(_) => Some(output_path),
956957 Err(error) => {
957 cgcx.create_dcx().emit_err(errors::CopyPathBuf { source_file, output_path, error });
958 cgcx.create_dcx().handle().emit_err(errors::CopyPathBuf {
959 source_file,
960 output_path,
961 error,
962 });
958963 None
959964 }
960965 }
......@@ -987,7 +992,7 @@ fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
987992 let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
988993 let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
989994 if should_emit_obj && object.is_none() {
990 cgcx.create_dcx().emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
995 cgcx.create_dcx().handle().emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
991996 }
992997
993998 WorkItemResult::Finished(CompiledModule {
......@@ -1016,12 +1021,13 @@ fn finish_intra_module_work<B: ExtraBackendMethods>(
10161021 module_config: &ModuleConfig,
10171022) -> Result<WorkItemResult<B>, FatalError> {
10181023 let dcx = cgcx.create_dcx();
1024 let dcx = dcx.handle();
10191025
10201026 if !cgcx.opts.unstable_opts.combine_cgu
10211027 || module.kind == ModuleKind::Metadata
10221028 || module.kind == ModuleKind::Allocator
10231029 {
1024 let module = unsafe { B::codegen(cgcx, &dcx, module, module_config)? };
1030 let module = unsafe { B::codegen(cgcx, dcx, module, module_config)? };
10251031 Ok(WorkItemResult::Finished(module))
10261032 } else {
10271033 Ok(WorkItemResult::NeedsLink(module))
......@@ -1692,9 +1698,10 @@ fn start_executing_work<B: ExtraBackendMethods>(
16921698 if !needs_link.is_empty() {
16931699 assert!(compiled_modules.is_empty());
16941700 let dcx = cgcx.create_dcx();
1695 let module = B::run_link(&cgcx, &dcx, needs_link).map_err(|_| ())?;
1701 let dcx = dcx.handle();
1702 let module = B::run_link(&cgcx, dcx, needs_link).map_err(|_| ())?;
16961703 let module = unsafe {
1697 B::codegen(&cgcx, &dcx, module, cgcx.config(ModuleKind::Regular)).map_err(|_| ())?
1704 B::codegen(&cgcx, dcx, module, cgcx.config(ModuleKind::Regular)).map_err(|_| ())?
16981705 };
16991706 compiled_modules.push(module);
17001707 }
compiler/rustc_codegen_ssa/src/errors.rs+3-3
......@@ -4,7 +4,7 @@ use crate::assert_module_sources::CguReuse;
44use crate::back::command::Command;
55use crate::fluent_generated as fluent;
66use rustc_errors::{
7 codes::*, Diag, DiagArgValue, DiagCtxt, Diagnostic, EmissionGuarantee, IntoDiagArg, Level,
7 codes::*, Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, IntoDiagArg, Level,
88};
99use rustc_macros::Diagnostic;
1010use rustc_middle::ty::layout::LayoutError;
......@@ -215,7 +215,7 @@ pub enum LinkRlibError {
215215pub struct ThorinErrorWrapper(pub thorin::Error);
216216
217217impl<G: EmissionGuarantee> Diagnostic<'_, G> for ThorinErrorWrapper {
218 fn into_diag(self, dcx: &DiagCtxt, level: Level) -> Diag<'_, G> {
218 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
219219 let build = |msg| Diag::new(dcx, level, msg);
220220 match self.0 {
221221 thorin::Error::ReadInput(_) => build(fluent::codegen_ssa_thorin_read_input_failure),
......@@ -348,7 +348,7 @@ pub struct LinkingFailed<'a> {
348348}
349349
350350impl<G: EmissionGuarantee> Diagnostic<'_, G> for LinkingFailed<'_> {
351 fn into_diag(self, dcx: &DiagCtxt, level: Level) -> Diag<'_, G> {
351 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
352352 let mut diag = Diag::new(dcx, level, fluent::codegen_ssa_linking_failed);
353353 diag.arg("linker_path", format!("{}", self.linker_path.display()));
354354 diag.arg("exit_status", format!("{}", self.exit_status));
compiler/rustc_codegen_ssa/src/traits/write.rs+4-4
......@@ -2,7 +2,7 @@ use crate::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
22use crate::back::write::{CodegenContext, FatLtoInput, ModuleConfig};
33use crate::{CompiledModule, ModuleCodegen};
44
5use rustc_errors::{DiagCtxt, FatalError};
5use rustc_errors::{DiagCtxtHandle, FatalError};
66use rustc_middle::dep_graph::WorkProduct;
77
88pub trait WriteBackendMethods: 'static + Sized + Clone {
......@@ -16,7 +16,7 @@ pub trait WriteBackendMethods: 'static + Sized + Clone {
1616 /// Merge all modules into main_module and returning it
1717 fn run_link(
1818 cgcx: &CodegenContext<Self>,
19 dcx: &DiagCtxt,
19 dcx: DiagCtxtHandle<'_>,
2020 modules: Vec<ModuleCodegen<Self::Module>>,
2121 ) -> Result<ModuleCodegen<Self::Module>, FatalError>;
2222 /// Performs fat LTO by merging all modules into a single one and returning it
......@@ -38,7 +38,7 @@ pub trait WriteBackendMethods: 'static + Sized + Clone {
3838 fn print_statistics(&self);
3939 unsafe fn optimize(
4040 cgcx: &CodegenContext<Self>,
41 dcx: &DiagCtxt,
41 dcx: DiagCtxtHandle<'_>,
4242 module: &ModuleCodegen<Self::Module>,
4343 config: &ModuleConfig,
4444 ) -> Result<(), FatalError>;
......@@ -52,7 +52,7 @@ pub trait WriteBackendMethods: 'static + Sized + Clone {
5252 ) -> Result<ModuleCodegen<Self::Module>, FatalError>;
5353 unsafe fn codegen(
5454 cgcx: &CodegenContext<Self>,
55 dcx: &DiagCtxt,
55 dcx: DiagCtxtHandle<'_>,
5656 module: ModuleCodegen<Self::Module>,
5757 config: &ModuleConfig,
5858 ) -> Result<CompiledModule, FatalError>;
compiler/rustc_const_eval/src/check_consts/mod.rs+2-2
......@@ -5,7 +5,7 @@
55//! it finds operations that are invalid in a certain context.
66
77use rustc_attr as attr;
8use rustc_errors::DiagCtxt;
8use rustc_errors::DiagCtxtHandle;
99use rustc_hir as hir;
1010use rustc_hir::def_id::{DefId, LocalDefId};
1111use rustc_middle::bug;
......@@ -46,7 +46,7 @@ impl<'mir, 'tcx> ConstCx<'mir, 'tcx> {
4646 ConstCx { body, tcx, param_env, const_kind }
4747 }
4848
49 pub(crate) fn dcx(&self) -> &'tcx DiagCtxt {
49 pub(crate) fn dcx(&self) -> DiagCtxtHandle<'tcx> {
5050 self.tcx.dcx()
5151 }
5252
compiler/rustc_const_eval/src/check_consts/ops.rs+1-1
......@@ -138,7 +138,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> {
138138 // FIXME(effects) revisit this
139139 if !tcx.is_const_trait_impl_raw(data.impl_def_id) {
140140 let span = tcx.def_span(data.impl_def_id);
141 err.subdiagnostic(tcx.dcx(), errors::NonConstImplNote { span });
141 err.subdiagnostic(errors::NonConstImplNote { span });
142142 }
143143 }
144144 }
compiler/rustc_const_eval/src/errors.rs+2-2
......@@ -2,7 +2,7 @@ use std::borrow::Cow;
22
33use either::Either;
44use rustc_errors::{
5 codes::*, Diag, DiagArgValue, DiagCtxt, DiagMessage, Diagnostic, EmissionGuarantee, Level,
5 codes::*, Diag, DiagArgValue, DiagCtxtHandle, DiagMessage, Diagnostic, EmissionGuarantee, Level,
66};
77use rustc_hir::ConstContext;
88use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
......@@ -453,7 +453,7 @@ pub trait ReportErrorExt {
453453 }
454454}
455455
456fn bad_pointer_message(msg: CheckInAllocMsg, dcx: &DiagCtxt) -> String {
456fn bad_pointer_message(msg: CheckInAllocMsg, dcx: DiagCtxtHandle<'_>) -> String {
457457 use crate::fluent_generated::*;
458458
459459 let msg = match msg {
compiler/rustc_const_eval/src/interpret/eval_context.rs+2-2
......@@ -4,7 +4,7 @@ use std::{fmt, mem};
44use either::{Either, Left, Right};
55use tracing::{debug, info, info_span, instrument, trace};
66
7use rustc_errors::DiagCtxt;
7use rustc_errors::DiagCtxtHandle;
88use rustc_hir::{self as hir, def_id::DefId, definitions::DefPathData};
99use rustc_index::IndexVec;
1010use rustc_middle::mir;
......@@ -474,7 +474,7 @@ pub(super) fn from_known_layout<'tcx>(
474474///
475475/// This is NOT the preferred way to render an error; use `report` from `const_eval` instead.
476476/// However, this is useful when error messages appear in ICEs.
477pub fn format_interp_error<'tcx>(dcx: &DiagCtxt, e: InterpErrorInfo<'tcx>) -> String {
477pub fn format_interp_error<'tcx>(dcx: DiagCtxtHandle<'_>, e: InterpErrorInfo<'tcx>) -> String {
478478 let (e, backtrace) = e.into_parts();
479479 backtrace.print_backtrace();
480480 // FIXME(fee1-dead), HACK: we want to use the error as title therefore we can just extract the
compiler/rustc_driver_impl/src/lib.rs+2-1
......@@ -1444,6 +1444,7 @@ fn report_ice(
14441444 fallback_bundle,
14451445 ));
14461446 let dcx = rustc_errors::DiagCtxt::new(emitter);
1447 let dcx = dcx.handle();
14471448
14481449 // a .span_bug or .bug call has already printed what
14491450 // it wants to print.
......@@ -1509,7 +1510,7 @@ fn report_ice(
15091510
15101511 let num_frames = if backtrace { None } else { Some(2) };
15111512
1512 interface::try_print_query_stack(&dcx, num_frames, file);
1513 interface::try_print_query_stack(dcx, num_frames, file);
15131514
15141515 // We don't trust this callback not to panic itself, so run it at the end after we're sure we've
15151516 // printed all the relevant info.
compiler/rustc_errors/src/diagnostic.rs+11-13
......@@ -1,7 +1,7 @@
11use crate::snippet::Style;
22use crate::{
3 CodeSuggestion, DiagCtxt, DiagMessage, ErrCode, ErrorGuaranteed, ExplicitBug, Level, MultiSpan,
4 StashKey, SubdiagMessage, Substitution, SubstitutionPart, SuggestionStyle,
3 CodeSuggestion, DiagCtxtHandle, DiagMessage, ErrCode, ErrorGuaranteed, ExplicitBug, Level,
4 MultiSpan, StashKey, SubdiagMessage, Substitution, SubstitutionPart, SuggestionStyle,
55};
66use rustc_data_structures::fx::FxIndexMap;
77use rustc_error_messages::fluent_value_from_str_list_sep_by_and;
......@@ -133,7 +133,7 @@ impl EmissionGuarantee for rustc_span::fatal_error::FatalError {
133133pub trait Diagnostic<'a, G: EmissionGuarantee = ErrorGuaranteed> {
134134 /// Write out as a diagnostic out of `DiagCtxt`.
135135 #[must_use]
136 fn into_diag(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G>;
136 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G>;
137137}
138138
139139impl<'a, T, G> Diagnostic<'a, G> for Spanned<T>
......@@ -141,7 +141,7 @@ where
141141 T: Diagnostic<'a, G>,
142142 G: EmissionGuarantee,
143143{
144 fn into_diag(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
144 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
145145 self.node.into_diag(dcx, level).with_span(self.span)
146146 }
147147}
......@@ -490,7 +490,7 @@ pub struct Subdiag {
490490/// the methods of `Diag` here, consider extending `DiagCtxtFlags`.
491491#[must_use]
492492pub struct Diag<'a, G: EmissionGuarantee = ErrorGuaranteed> {
493 pub dcx: &'a DiagCtxt,
493 pub dcx: DiagCtxtHandle<'a>,
494494
495495 /// Why the `Option`? It is always `Some` until the `Diag` is consumed via
496496 /// `emit`, `cancel`, etc. At that point it is consumed and replaced with
......@@ -578,13 +578,13 @@ macro_rules! with_fn {
578578impl<'a, G: EmissionGuarantee> Diag<'a, G> {
579579 #[rustc_lint_diagnostics]
580580 #[track_caller]
581 pub fn new(dcx: &'a DiagCtxt, level: Level, message: impl Into<DiagMessage>) -> Self {
581 pub fn new(dcx: DiagCtxtHandle<'a>, level: Level, message: impl Into<DiagMessage>) -> Self {
582582 Self::new_diagnostic(dcx, DiagInner::new(level, message))
583583 }
584584
585585 /// Creates a new `Diag` with an already constructed diagnostic.
586586 #[track_caller]
587 pub(crate) fn new_diagnostic(dcx: &'a DiagCtxt, diag: DiagInner) -> Self {
587 pub(crate) fn new_diagnostic(dcx: DiagCtxtHandle<'a>, diag: DiagInner) -> Self {
588588 debug!("Created new diagnostic");
589589 Self { dcx, diag: Some(Box::new(diag)), _marker: PhantomData }
590590 }
......@@ -1192,11 +1192,8 @@ impl<'a, G: EmissionGuarantee> Diag<'a, G> {
11921192 /// used in the subdiagnostic, so suitable for use with repeated messages (i.e. re-use of
11931193 /// interpolated variables).
11941194 #[rustc_lint_diagnostics]
1195 pub fn subdiagnostic(
1196 &mut self,
1197 dcx: &crate::DiagCtxt,
1198 subdiagnostic: impl Subdiagnostic,
1199 ) -> &mut Self {
1195 pub fn subdiagnostic(&mut self, subdiagnostic: impl Subdiagnostic) -> &mut Self {
1196 let dcx = self.dcx;
12001197 subdiagnostic.add_to_diag_with(self, &|diag, msg| {
12011198 let args = diag.args.iter();
12021199 let msg = diag.subdiagnostic_message_to_diagnostic_message(msg);
......@@ -1341,7 +1338,8 @@ impl<'a, G: EmissionGuarantee> Diag<'a, G> {
13411338
13421339 /// See `DiagCtxt::stash_diagnostic` for details.
13431340 pub fn stash(mut self, span: Span, key: StashKey) -> Option<ErrorGuaranteed> {
1344 self.dcx.stash_diagnostic(span, key, self.take_diag())
1341 let diag = self.take_diag();
1342 self.dcx.stash_diagnostic(span, key, diag)
13451343 }
13461344
13471345 /// Delay emission of this diagnostic as a bug.
compiler/rustc_errors/src/diagnostic_impls.rs+3-3
......@@ -1,7 +1,7 @@
11use crate::diagnostic::DiagLocation;
2use crate::{fluent_generated as fluent, Subdiagnostic};
2use crate::{fluent_generated as fluent, DiagCtxtHandle, Subdiagnostic};
33use crate::{
4 Diag, DiagArgValue, DiagCtxt, Diagnostic, EmissionGuarantee, ErrCode, IntoDiagArg, Level,
4 Diag, DiagArgValue, Diagnostic, EmissionGuarantee, ErrCode, IntoDiagArg, Level,
55 SubdiagMessageOp,
66};
77use rustc_ast as ast;
......@@ -315,7 +315,7 @@ impl IntoDiagArg for DiagSymbolList {
315315}
316316
317317impl<G: EmissionGuarantee> Diagnostic<'_, G> for TargetDataLayoutErrors<'_> {
318 fn into_diag(self, dcx: &DiagCtxt, level: Level) -> Diag<'_, G> {
318 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
319319 match self {
320320 TargetDataLayoutErrors::InvalidAddressSpace { addr_space, err, cause } => {
321321 Diag::new(dcx, level, fluent::errors_target_invalid_address_space)
compiler/rustc_errors/src/emitter.rs+1-1
......@@ -567,7 +567,7 @@ impl Emitter for SilentEmitter {
567567 if let Some(fatal_note) = &self.fatal_note {
568568 diag.sub(Level::Note, fatal_note.clone(), MultiSpan::new());
569569 }
570 self.fatal_dcx.emit_diagnostic(diag);
570 self.fatal_dcx.handle().emit_diagnostic(diag);
571571 }
572572 }
573573}
compiler/rustc_errors/src/json/tests.rs+1-2
......@@ -55,8 +55,7 @@ fn test_positions(code: &str, span: (u32, u32), expected_output: SpanTestData) {
5555 );
5656
5757 let span = Span::with_root_ctxt(BytePos(span.0), BytePos(span.1));
58 let dcx = DiagCtxt::new(Box::new(je));
59 dcx.span_err(span, "foo");
58 DiagCtxt::new(Box::new(je)).handle().span_err(span, "foo");
6059
6160 let bytes = output.lock().unwrap();
6261 let actual_output = str::from_utf8(&bytes).unwrap();
compiler/rustc_errors/src/lib.rs+71-59
......@@ -414,6 +414,19 @@ pub struct DiagCtxt {
414414 inner: Lock<DiagCtxtInner>,
415415}
416416
417#[derive(Copy, Clone)]
418pub struct DiagCtxtHandle<'a> {
419 dcx: &'a DiagCtxt,
420}
421
422impl<'a> std::ops::Deref for DiagCtxtHandle<'a> {
423 type Target = &'a DiagCtxt;
424
425 fn deref(&self) -> &Self::Target {
426 &self.dcx
427 }
428}
429
417430/// This inner struct exists to keep it all behind a single lock;
418431/// this is done to prevent possible deadlocks in a multi-threaded compiler,
419432/// as well as inconsistent state observation.
......@@ -608,7 +621,7 @@ impl DiagCtxt {
608621 }
609622
610623 pub fn make_silent(
611 &mut self,
624 &self,
612625 fallback_bundle: LazyFallbackBundle,
613626 fatal_note: Option<String>,
614627 emit_fatal_diagnostic: bool,
......@@ -623,7 +636,7 @@ impl DiagCtxt {
623636 });
624637 }
625638
626 fn wrap_emitter<F>(&mut self, f: F)
639 fn wrap_emitter<F>(&self, f: F)
627640 where
628641 F: FnOnce(DiagCtxtInner) -> Box<DynEmitter>,
629642 {
......@@ -738,6 +751,12 @@ impl DiagCtxt {
738751 *fulfilled_expectations = Default::default();
739752 }
740753
754 pub fn handle<'a>(&'a self) -> DiagCtxtHandle<'a> {
755 DiagCtxtHandle { dcx: self }
756 }
757}
758
759impl<'a> DiagCtxtHandle<'a> {
741760 /// Stashes a diagnostic for possible later improvement in a different,
742761 /// later stage of the compiler. Possible actions depend on the diagnostic
743762 /// level:
......@@ -745,8 +764,8 @@ impl DiagCtxt {
745764 /// - Level::Error: immediately counted as an error that has occurred, because it
746765 /// is guaranteed to be emitted eventually. Can be later accessed with the
747766 /// provided `span` and `key` through
748 /// [`DiagCtxt::try_steal_modify_and_emit_err`] or
749 /// [`DiagCtxt::try_steal_replace_and_emit_err`]. These do not allow
767 /// [`DiagCtxtHandle::try_steal_modify_and_emit_err`] or
768 /// [`DiagCtxtHandle::try_steal_replace_and_emit_err`]. These do not allow
750769 /// cancellation or downgrading of the error. Returns
751770 /// `Some(ErrorGuaranteed)`.
752771 /// - Level::DelayedBug: this does happen occasionally with errors that are
......@@ -757,7 +776,7 @@ impl DiagCtxt {
757776 /// user-facing error. Returns `Some(ErrorGuaranteed)` as is normal for
758777 /// delayed bugs.
759778 /// - Level::Warning and lower (i.e. !is_error()): can be accessed with the
760 /// provided `span` and `key` through [`DiagCtxt::steal_non_err()`]. This
779 /// provided `span` and `key` through [`DiagCtxtHandle::steal_non_err()`]. This
761780 /// allows cancelling and downgrading of the diagnostic. Returns `None`.
762781 pub fn stash_diagnostic(
763782 &self,
......@@ -793,7 +812,7 @@ impl DiagCtxt {
793812 /// Steal a previously stashed non-error diagnostic with the given `Span`
794813 /// and [`StashKey`] as the key. Panics if the found diagnostic is an
795814 /// error.
796 pub fn steal_non_err(&self, span: Span, key: StashKey) -> Option<Diag<'_, ()>> {
815 pub fn steal_non_err(self, span: Span, key: StashKey) -> Option<Diag<'a, ()>> {
797816 let key = (span.with_parent(None), key);
798817 // FIXME(#120456) - is `swap_remove` correct?
799818 let (diag, guar) = self.inner.borrow_mut().stashed_diagnostics.swap_remove(&key)?;
......@@ -807,7 +826,7 @@ impl DiagCtxt {
807826 /// no matching diagnostic is found. Panics if the found diagnostic's level
808827 /// isn't `Level::Error`.
809828 pub fn try_steal_modify_and_emit_err<F>(
810 &self,
829 self,
811830 span: Span,
812831 key: StashKey,
813832 mut modify_err: F,
......@@ -833,7 +852,7 @@ impl DiagCtxt {
833852 /// [`StashKey`] as the key, cancels it if found, and emits `new_err`.
834853 /// Panics if the found diagnostic's level isn't `Level::Error`.
835854 pub fn try_steal_replace_and_emit_err(
836 &self,
855 self,
837856 span: Span,
838857 key: StashKey,
839858 new_err: Diag<'_>,
......@@ -1106,18 +1125,18 @@ impl DiagCtxt {
11061125//
11071126// Functions beginning with `struct_`/`create_` create a diagnostic. Other
11081127// functions create and emit a diagnostic all in one go.
1109impl DiagCtxt {
1128impl<'a> DiagCtxtHandle<'a> {
11101129 // No `#[rustc_lint_diagnostics]` and no `impl Into<DiagMessage>` because bug messages aren't
11111130 // user-facing.
11121131 #[track_caller]
1113 pub fn struct_bug(&self, msg: impl Into<Cow<'static, str>>) -> Diag<'_, BugAbort> {
1132 pub fn struct_bug(self, msg: impl Into<Cow<'static, str>>) -> Diag<'a, BugAbort> {
11141133 Diag::new(self, Bug, msg.into())
11151134 }
11161135
11171136 // No `#[rustc_lint_diagnostics]` and no `impl Into<DiagMessage>` because bug messages aren't
11181137 // user-facing.
11191138 #[track_caller]
1120 pub fn bug(&self, msg: impl Into<Cow<'static, str>>) -> ! {
1139 pub fn bug(self, msg: impl Into<Cow<'static, str>>) -> ! {
11211140 self.struct_bug(msg).emit()
11221141 }
11231142
......@@ -1125,111 +1144,108 @@ impl DiagCtxt {
11251144 // user-facing.
11261145 #[track_caller]
11271146 pub fn struct_span_bug(
1128 &self,
1147 self,
11291148 span: impl Into<MultiSpan>,
11301149 msg: impl Into<Cow<'static, str>>,
1131 ) -> Diag<'_, BugAbort> {
1150 ) -> Diag<'a, BugAbort> {
11321151 self.struct_bug(msg).with_span(span)
11331152 }
11341153
11351154 // No `#[rustc_lint_diagnostics]` and no `impl Into<DiagMessage>` because bug messages aren't
11361155 // user-facing.
11371156 #[track_caller]
1138 pub fn span_bug(&self, span: impl Into<MultiSpan>, msg: impl Into<Cow<'static, str>>) -> ! {
1157 pub fn span_bug(self, span: impl Into<MultiSpan>, msg: impl Into<Cow<'static, str>>) -> ! {
11391158 self.struct_span_bug(span, msg.into()).emit()
11401159 }
11411160
11421161 #[track_caller]
1143 pub fn create_bug<'a>(&'a self, bug: impl Diagnostic<'a, BugAbort>) -> Diag<'a, BugAbort> {
1162 pub fn create_bug(self, bug: impl Diagnostic<'a, BugAbort>) -> Diag<'a, BugAbort> {
11441163 bug.into_diag(self, Bug)
11451164 }
11461165
11471166 #[track_caller]
1148 pub fn emit_bug<'a>(&'a self, bug: impl Diagnostic<'a, BugAbort>) -> ! {
1167 pub fn emit_bug(self, bug: impl Diagnostic<'a, BugAbort>) -> ! {
11491168 self.create_bug(bug).emit()
11501169 }
11511170
11521171 #[rustc_lint_diagnostics]
11531172 #[track_caller]
1154 pub fn struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1173 pub fn struct_fatal(self, msg: impl Into<DiagMessage>) -> Diag<'a, FatalAbort> {
11551174 Diag::new(self, Fatal, msg)
11561175 }
11571176
11581177 #[rustc_lint_diagnostics]
11591178 #[track_caller]
1160 pub fn fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1179 pub fn fatal(self, msg: impl Into<DiagMessage>) -> ! {
11611180 self.struct_fatal(msg).emit()
11621181 }
11631182
11641183 #[rustc_lint_diagnostics]
11651184 #[track_caller]
11661185 pub fn struct_span_fatal(
1167 &self,
1186 self,
11681187 span: impl Into<MultiSpan>,
11691188 msg: impl Into<DiagMessage>,
1170 ) -> Diag<'_, FatalAbort> {
1189 ) -> Diag<'a, FatalAbort> {
11711190 self.struct_fatal(msg).with_span(span)
11721191 }
11731192
11741193 #[rustc_lint_diagnostics]
11751194 #[track_caller]
1176 pub fn span_fatal(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) -> ! {
1195 pub fn span_fatal(self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) -> ! {
11771196 self.struct_span_fatal(span, msg).emit()
11781197 }
11791198
11801199 #[track_caller]
1181 pub fn create_fatal<'a>(
1182 &'a self,
1183 fatal: impl Diagnostic<'a, FatalAbort>,
1184 ) -> Diag<'a, FatalAbort> {
1200 pub fn create_fatal(self, fatal: impl Diagnostic<'a, FatalAbort>) -> Diag<'a, FatalAbort> {
11851201 fatal.into_diag(self, Fatal)
11861202 }
11871203
11881204 #[track_caller]
1189 pub fn emit_fatal<'a>(&'a self, fatal: impl Diagnostic<'a, FatalAbort>) -> ! {
1205 pub fn emit_fatal(self, fatal: impl Diagnostic<'a, FatalAbort>) -> ! {
11901206 self.create_fatal(fatal).emit()
11911207 }
11921208
11931209 #[track_caller]
1194 pub fn create_almost_fatal<'a>(
1195 &'a self,
1210 pub fn create_almost_fatal(
1211 self,
11961212 fatal: impl Diagnostic<'a, FatalError>,
11971213 ) -> Diag<'a, FatalError> {
11981214 fatal.into_diag(self, Fatal)
11991215 }
12001216
12011217 #[track_caller]
1202 pub fn emit_almost_fatal<'a>(&'a self, fatal: impl Diagnostic<'a, FatalError>) -> FatalError {
1218 pub fn emit_almost_fatal(self, fatal: impl Diagnostic<'a, FatalError>) -> FatalError {
12031219 self.create_almost_fatal(fatal).emit()
12041220 }
12051221
12061222 // FIXME: This method should be removed (every error should have an associated error code).
12071223 #[rustc_lint_diagnostics]
12081224 #[track_caller]
1209 pub fn struct_err(&self, msg: impl Into<DiagMessage>) -> Diag<'_> {
1225 pub fn struct_err(self, msg: impl Into<DiagMessage>) -> Diag<'a> {
12101226 Diag::new(self, Error, msg)
12111227 }
12121228
12131229 #[rustc_lint_diagnostics]
12141230 #[track_caller]
1215 pub fn err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1231 pub fn err(self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
12161232 self.struct_err(msg).emit()
12171233 }
12181234
12191235 #[rustc_lint_diagnostics]
12201236 #[track_caller]
12211237 pub fn struct_span_err(
1222 &self,
1238 self,
12231239 span: impl Into<MultiSpan>,
12241240 msg: impl Into<DiagMessage>,
1225 ) -> Diag<'_> {
1241 ) -> Diag<'a> {
12261242 self.struct_err(msg).with_span(span)
12271243 }
12281244
12291245 #[rustc_lint_diagnostics]
12301246 #[track_caller]
12311247 pub fn span_err(
1232 &self,
1248 self,
12331249 span: impl Into<MultiSpan>,
12341250 msg: impl Into<DiagMessage>,
12351251 ) -> ErrorGuaranteed {
......@@ -1237,12 +1253,12 @@ impl DiagCtxt {
12371253 }
12381254
12391255 #[track_caller]
1240 pub fn create_err<'a>(&'a self, err: impl Diagnostic<'a>) -> Diag<'a> {
1256 pub fn create_err(self, err: impl Diagnostic<'a>) -> Diag<'a> {
12411257 err.into_diag(self, Error)
12421258 }
12431259
12441260 #[track_caller]
1245 pub fn emit_err<'a>(&'a self, err: impl Diagnostic<'a>) -> ErrorGuaranteed {
1261 pub fn emit_err(self, err: impl Diagnostic<'a>) -> ErrorGuaranteed {
12461262 self.create_err(err).emit()
12471263 }
12481264
......@@ -1251,7 +1267,7 @@ impl DiagCtxt {
12511267 // No `#[rustc_lint_diagnostics]` and no `impl Into<DiagMessage>` because bug messages aren't
12521268 // user-facing.
12531269 #[track_caller]
1254 pub fn delayed_bug(&self, msg: impl Into<Cow<'static, str>>) -> ErrorGuaranteed {
1270 pub fn delayed_bug(self, msg: impl Into<Cow<'static, str>>) -> ErrorGuaranteed {
12551271 Diag::<ErrorGuaranteed>::new(self, DelayedBug, msg.into()).emit()
12561272 }
12571273
......@@ -1264,7 +1280,7 @@ impl DiagCtxt {
12641280 // user-facing.
12651281 #[track_caller]
12661282 pub fn span_delayed_bug(
1267 &self,
1283 self,
12681284 sp: impl Into<MultiSpan>,
12691285 msg: impl Into<Cow<'static, str>>,
12701286 ) -> ErrorGuaranteed {
......@@ -1273,45 +1289,45 @@ impl DiagCtxt {
12731289
12741290 #[rustc_lint_diagnostics]
12751291 #[track_caller]
1276 pub fn struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1292 pub fn struct_warn(self, msg: impl Into<DiagMessage>) -> Diag<'a, ()> {
12771293 Diag::new(self, Warning, msg)
12781294 }
12791295
12801296 #[rustc_lint_diagnostics]
12811297 #[track_caller]
1282 pub fn warn(&self, msg: impl Into<DiagMessage>) {
1298 pub fn warn(self, msg: impl Into<DiagMessage>) {
12831299 self.struct_warn(msg).emit()
12841300 }
12851301
12861302 #[rustc_lint_diagnostics]
12871303 #[track_caller]
12881304 pub fn struct_span_warn(
1289 &self,
1305 self,
12901306 span: impl Into<MultiSpan>,
12911307 msg: impl Into<DiagMessage>,
1292 ) -> Diag<'_, ()> {
1308 ) -> Diag<'a, ()> {
12931309 self.struct_warn(msg).with_span(span)
12941310 }
12951311
12961312 #[rustc_lint_diagnostics]
12971313 #[track_caller]
1298 pub fn span_warn(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) {
1314 pub fn span_warn(self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) {
12991315 self.struct_span_warn(span, msg).emit()
13001316 }
13011317
13021318 #[track_caller]
1303 pub fn create_warn<'a>(&'a self, warning: impl Diagnostic<'a, ()>) -> Diag<'a, ()> {
1319 pub fn create_warn(self, warning: impl Diagnostic<'a, ()>) -> Diag<'a, ()> {
13041320 warning.into_diag(self, Warning)
13051321 }
13061322
13071323 #[track_caller]
1308 pub fn emit_warn<'a>(&'a self, warning: impl Diagnostic<'a, ()>) {
1324 pub fn emit_warn(self, warning: impl Diagnostic<'a, ()>) {
13091325 self.create_warn(warning).emit()
13101326 }
13111327
13121328 #[rustc_lint_diagnostics]
13131329 #[track_caller]
1314 pub fn struct_note(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1330 pub fn struct_note(self, msg: impl Into<DiagMessage>) -> Diag<'a, ()> {
13151331 Diag::new(self, Note, msg)
13161332 }
13171333
......@@ -1324,54 +1340,50 @@ impl DiagCtxt {
13241340 #[rustc_lint_diagnostics]
13251341 #[track_caller]
13261342 pub fn struct_span_note(
1327 &self,
1343 self,
13281344 span: impl Into<MultiSpan>,
13291345 msg: impl Into<DiagMessage>,
1330 ) -> Diag<'_, ()> {
1346 ) -> Diag<'a, ()> {
13311347 self.struct_note(msg).with_span(span)
13321348 }
13331349
13341350 #[rustc_lint_diagnostics]
13351351 #[track_caller]
1336 pub fn span_note(&self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) {
1352 pub fn span_note(self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) {
13371353 self.struct_span_note(span, msg).emit()
13381354 }
13391355
13401356 #[track_caller]
1341 pub fn create_note<'a>(&'a self, note: impl Diagnostic<'a, ()>) -> Diag<'a, ()> {
1357 pub fn create_note(self, note: impl Diagnostic<'a, ()>) -> Diag<'a, ()> {
13421358 note.into_diag(self, Note)
13431359 }
13441360
13451361 #[track_caller]
1346 pub fn emit_note<'a>(&'a self, note: impl Diagnostic<'a, ()>) {
1362 pub fn emit_note(self, note: impl Diagnostic<'a, ()>) {
13471363 self.create_note(note).emit()
13481364 }
13491365
13501366 #[rustc_lint_diagnostics]
13511367 #[track_caller]
1352 pub fn struct_help(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1368 pub fn struct_help(self, msg: impl Into<DiagMessage>) -> Diag<'a, ()> {
13531369 Diag::new(self, Help, msg)
13541370 }
13551371
13561372 #[rustc_lint_diagnostics]
13571373 #[track_caller]
1358 pub fn struct_failure_note(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1374 pub fn struct_failure_note(self, msg: impl Into<DiagMessage>) -> Diag<'a, ()> {
13591375 Diag::new(self, FailureNote, msg)
13601376 }
13611377
13621378 #[rustc_lint_diagnostics]
13631379 #[track_caller]
1364 pub fn struct_allow(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1380 pub fn struct_allow(self, msg: impl Into<DiagMessage>) -> Diag<'a, ()> {
13651381 Diag::new(self, Allow, msg)
13661382 }
13671383
13681384 #[rustc_lint_diagnostics]
13691385 #[track_caller]
1370 pub fn struct_expect(
1371 &self,
1372 msg: impl Into<DiagMessage>,
1373 id: LintExpectationId,
1374 ) -> Diag<'_, ()> {
1386 pub fn struct_expect(self, msg: impl Into<DiagMessage>, id: LintExpectationId) -> Diag<'a, ()> {
13751387 Diag::new(self, Expect(id), msg)
13761388 }
13771389}
compiler/rustc_expand/src/base.rs+4-4
......@@ -12,7 +12,7 @@ use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind
1212use rustc_attr::{self as attr, Deprecation, Stability};
1313use rustc_data_structures::fx::FxIndexMap;
1414use rustc_data_structures::sync::{self, Lrc};
15use rustc_errors::{DiagCtxt, ErrorGuaranteed, PResult};
15use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, PResult};
1616use rustc_feature::Features;
1717use rustc_lint_defs::{BufferedEarlyLint, RegisteredTools};
1818use rustc_parse::{parser::Parser, MACRO_ARGUMENTS};
......@@ -1135,7 +1135,7 @@ impl<'a> ExtCtxt<'a> {
11351135 }
11361136 }
11371137
1138 pub fn dcx(&self) -> &'a DiagCtxt {
1138 pub fn dcx(&self) -> DiagCtxtHandle<'a> {
11391139 self.sess.dcx()
11401140 }
11411141
......@@ -1256,7 +1256,7 @@ pub fn resolve_path(sess: &Session, path: impl Into<PathBuf>, span: Span) -> PRe
12561256}
12571257
12581258pub fn parse_macro_name_and_helper_attrs(
1259 dcx: &rustc_errors::DiagCtxt,
1259 dcx: DiagCtxtHandle<'_>,
12601260 attr: &Attribute,
12611261 macro_type: &str,
12621262) -> Option<(Symbol, Vec<Symbol>)> {
......@@ -1358,7 +1358,7 @@ fn pretty_printing_compatibility_hack(item: &Item, sess: &Session) {
13581358 if crate_matches {
13591359 // FIXME: make this translatable
13601360 #[allow(rustc::untranslatable_diagnostic)]
1361 sess.psess.dcx.emit_fatal(errors::ProcMacroBackCompat {
1361 sess.dcx().emit_fatal(errors::ProcMacroBackCompat {
13621362 crate_name: "rental".to_string(),
13631363 fixed_version: "0.5.6".to_string(),
13641364 });
compiler/rustc_expand/src/mbe/diagnostics.rs+5-5
......@@ -7,7 +7,7 @@ use crate::mbe::{
77use rustc_ast::token::{self, Token, TokenKind};
88use rustc_ast::tokenstream::TokenStream;
99use rustc_ast_pretty::pprust;
10use rustc_errors::{Applicability, Diag, DiagCtxt, DiagMessage};
10use rustc_errors::{Applicability, Diag, DiagMessage};
1111use rustc_macros::Subdiagnostic;
1212use rustc_parse::parser::{Parser, Recovery};
1313use rustc_span::source_map::SourceMap;
......@@ -61,7 +61,7 @@ pub(super) fn failed_to_match_macro<'cx>(
6161 err.span_label(cx.source_map().guess_head_span(def_span), "when calling this macro");
6262 }
6363
64 annotate_doc_comment(cx.sess.dcx(), &mut err, psess.source_map(), span);
64 annotate_doc_comment(&mut err, psess.source_map(), span);
6565
6666 if let Some(span) = remaining_matcher.span() {
6767 err.span_note(span, format!("while trying to match {remaining_matcher}"));
......@@ -324,12 +324,12 @@ enum ExplainDocComment {
324324 },
325325}
326326
327pub(super) fn annotate_doc_comment(dcx: &DiagCtxt, err: &mut Diag<'_>, sm: &SourceMap, span: Span) {
327pub(super) fn annotate_doc_comment(err: &mut Diag<'_>, sm: &SourceMap, span: Span) {
328328 if let Ok(src) = sm.span_to_snippet(span) {
329329 if src.starts_with("///") || src.starts_with("/**") {
330 err.subdiagnostic(dcx, ExplainDocComment::Outer { span });
330 err.subdiagnostic(ExplainDocComment::Outer { span });
331331 } else if src.starts_with("//!") || src.starts_with("/*!") {
332 err.subdiagnostic(dcx, ExplainDocComment::Inner { span });
332 err.subdiagnostic(ExplainDocComment::Inner { span });
333333 }
334334 }
335335}
compiler/rustc_expand/src/mbe/macro_check.rs+5-5
......@@ -206,7 +206,7 @@ pub(super) fn check_meta_variables(
206206 rhses: &[TokenTree],
207207) -> Result<(), ErrorGuaranteed> {
208208 if lhses.len() != rhses.len() {
209 psess.dcx.span_bug(span, "length mismatch between LHSes and RHSes")
209 psess.dcx().span_bug(span, "length mismatch between LHSes and RHSes")
210210 }
211211 let mut guar = None;
212212 for (lhs, rhs) in iter::zip(lhses, rhses) {
......@@ -245,7 +245,7 @@ fn check_binders(
245245 // MetaVar(fragment) and not as MetaVarDecl(y, fragment).
246246 TokenTree::MetaVar(span, name) => {
247247 if macros.is_empty() {
248 psess.dcx.span_bug(span, "unexpected MetaVar in lhs");
248 psess.dcx().span_bug(span, "unexpected MetaVar in lhs");
249249 }
250250 let name = MacroRulesNormalizedIdent::new(name);
251251 // There are 3 possibilities:
......@@ -276,7 +276,7 @@ fn check_binders(
276276 );
277277 }
278278 if !macros.is_empty() {
279 psess.dcx.span_bug(span, "unexpected MetaVarDecl in nested lhs");
279 psess.dcx().span_bug(span, "unexpected MetaVarDecl in nested lhs");
280280 }
281281 let name = MacroRulesNormalizedIdent::new(name);
282282 if let Some(prev_info) = get_binder_info(macros, binders, name) {
......@@ -284,7 +284,7 @@ fn check_binders(
284284 // for nested macro definitions.
285285 *guar = Some(
286286 psess
287 .dcx
287 .dcx()
288288 .emit_err(errors::DuplicateMatcherBinding { span, prev: prev_info.span }),
289289 );
290290 } else {
......@@ -344,7 +344,7 @@ fn check_occurrences(
344344 match *rhs {
345345 TokenTree::Token(..) => {}
346346 TokenTree::MetaVarDecl(span, _name, _kind) => {
347 psess.dcx.span_bug(span, "unexpected MetaVarDecl in rhs")
347 psess.dcx().span_bug(span, "unexpected MetaVarDecl in rhs")
348348 }
349349 TokenTree::MetaVar(span, name) => {
350350 let name = MacroRulesNormalizedIdent::new(name);
compiler/rustc_expand/src/mbe/macro_rules.rs+2-2
......@@ -383,7 +383,7 @@ pub fn compile_declarative_macro(
383383 };
384384 let dummy_syn_ext = |guar| (mk_syn_ext(Box::new(DummyExpander(guar))), Vec::new());
385385
386 let dcx = &sess.psess.dcx;
386 let dcx = sess.dcx();
387387 let lhs_nm = Ident::new(sym::lhs, def.span);
388388 let rhs_nm = Ident::new(sym::rhs, def.span);
389389 let tt_spec = Some(NonterminalKind::TT);
......@@ -463,7 +463,7 @@ pub fn compile_declarative_macro(
463463 let sp = token.span.substitute_dummy(def.span);
464464 let mut err = sess.dcx().struct_span_err(sp, s);
465465 err.span_label(sp, msg);
466 annotate_doc_comment(sess.dcx(), &mut err, sess.source_map(), sp);
466 annotate_doc_comment(&mut err, sess.source_map(), sp);
467467 let guar = err.emit();
468468 return dummy_syn_ext(guar);
469469 }
compiler/rustc_expand/src/mbe/metavar_expr.rs+15-14
......@@ -42,7 +42,7 @@ impl MetaVarExpr {
4242 let ident = parse_ident(&mut tts, psess, outer_span)?;
4343 let Some(TokenTree::Delimited(.., Delimiter::Parenthesis, args)) = tts.next() else {
4444 let msg = "meta-variable expression parameter must be wrapped in parentheses";
45 return Err(psess.dcx.struct_span_err(ident.span, msg));
45 return Err(psess.dcx().struct_span_err(ident.span, msg));
4646 };
4747 check_trailing_token(&mut tts, psess)?;
4848 let mut iter = args.trees();
......@@ -62,12 +62,12 @@ impl MetaVarExpr {
6262 break;
6363 }
6464 if !try_eat_comma(&mut iter) {
65 return Err(psess.dcx.struct_span_err(outer_span, "expected comma"));
65 return Err(psess.dcx().struct_span_err(outer_span, "expected comma"));
6666 }
6767 }
6868 if result.len() < 2 {
6969 return Err(psess
70 .dcx
70 .dcx()
7171 .struct_span_err(ident.span, "`concat` must have at least two elements"));
7272 }
7373 MetaVarExpr::Concat(result.into())
......@@ -81,7 +81,7 @@ impl MetaVarExpr {
8181 "len" => MetaVarExpr::Len(parse_depth(&mut iter, psess, ident.span)?),
8282 _ => {
8383 let err_msg = "unrecognized meta-variable expression";
84 let mut err = psess.dcx.struct_span_err(ident.span, err_msg);
84 let mut err = psess.dcx().struct_span_err(ident.span, err_msg);
8585 err.span_suggestion(
8686 ident.span,
8787 "supported expressions are count, ignore, index and len",
......@@ -120,7 +120,7 @@ fn check_trailing_token<'psess>(
120120) -> PResult<'psess, ()> {
121121 if let Some(tt) = iter.next() {
122122 let mut diag = psess
123 .dcx
123 .dcx()
124124 .struct_span_err(tt.span(), format!("unexpected token: {}", pprust::tt_to_string(tt)));
125125 diag.span_note(tt.span(), "meta-variable expression must not have trailing tokens");
126126 Err(diag)
......@@ -139,7 +139,7 @@ fn parse_count<'psess>(
139139 let ident = parse_ident(iter, psess, span)?;
140140 let depth = if try_eat_comma(iter) {
141141 if iter.look_ahead(0).is_none() {
142 return Err(psess.dcx.struct_span_err(
142 return Err(psess.dcx().struct_span_err(
143143 span,
144144 "`count` followed by a comma must have an associated index indicating its depth",
145145 ));
......@@ -160,7 +160,7 @@ fn parse_depth<'psess>(
160160 let Some(tt) = iter.next() else { return Ok(0) };
161161 let TokenTree::Token(token::Token { kind: token::TokenKind::Literal(lit), .. }, _) = tt else {
162162 return Err(psess
163 .dcx
163 .dcx()
164164 .struct_span_err(span, "meta-variable expression depth must be a literal"));
165165 };
166166 if let Ok(lit_kind) = LitKind::from_token_lit(*lit)
......@@ -170,7 +170,7 @@ fn parse_depth<'psess>(
170170 Ok(n_usize)
171171 } else {
172172 let msg = "only unsuffixes integer literals are supported in meta-variable expressions";
173 Err(psess.dcx.struct_span_err(span, msg))
173 Err(psess.dcx().struct_span_err(span, msg))
174174 }
175175}
176176
......@@ -181,20 +181,21 @@ fn parse_ident<'psess>(
181181 fallback_span: Span,
182182) -> PResult<'psess, Ident> {
183183 let Some(tt) = iter.next() else {
184 return Err(psess.dcx.struct_span_err(fallback_span, "expected identifier"));
184 return Err(psess.dcx().struct_span_err(fallback_span, "expected identifier"));
185185 };
186186 let TokenTree::Token(token, _) = tt else {
187 return Err(psess.dcx.struct_span_err(tt.span(), "expected identifier"));
187 return Err(psess.dcx().struct_span_err(tt.span(), "expected identifier"));
188188 };
189189 if let Some((elem, is_raw)) = token.ident() {
190190 if let IdentIsRaw::Yes = is_raw {
191 return Err(psess.dcx.struct_span_err(elem.span, RAW_IDENT_ERR));
191 return Err(psess.dcx().struct_span_err(elem.span, RAW_IDENT_ERR));
192192 }
193193 return Ok(elem);
194194 }
195195 let token_str = pprust::token_to_string(token);
196 let mut err =
197 psess.dcx.struct_span_err(token.span, format!("expected identifier, found `{token_str}`"));
196 let mut err = psess
197 .dcx()
198 .struct_span_err(token.span, format!("expected identifier, found `{token_str}`"));
198199 err.span_suggestion(
199200 token.span,
200201 format!("try removing `{token_str}`"),
......@@ -236,7 +237,7 @@ fn eat_dollar<'psess>(
236237 let _ = iter.next();
237238 return Ok(());
238239 }
239 Err(psess.dcx.struct_span_err(
240 Err(psess.dcx().struct_span_err(
240241 span,
241242 "meta-variables within meta-variable expressions must be referenced using a dollar sign",
242243 ))
compiler/rustc_expand/src/mbe/transcribe.rs+7-7
......@@ -10,7 +10,7 @@ use rustc_ast::token::IdentIsRaw;
1010use rustc_ast::token::{self, Delimiter, Token, TokenKind};
1111use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree};
1212use rustc_data_structures::fx::FxHashMap;
13use rustc_errors::{pluralize, Diag, DiagCtxt, PResult};
13use rustc_errors::{pluralize, Diag, DiagCtxtHandle, PResult};
1414use rustc_parse::parser::ParseNtResult;
1515use rustc_session::parse::ParseSess;
1616use rustc_span::hygiene::{LocalExpnId, Transparency};
......@@ -141,7 +141,7 @@ pub(super) fn transcribe<'a>(
141141 let mut result_stack = Vec::new();
142142 let mut marker = Marker(expand_id, transparency, Default::default());
143143
144 let dcx = &psess.dcx;
144 let dcx = psess.dcx();
145145 loop {
146146 // Look at the last frame on the stack.
147147 // If it still has a TokenTree we have not looked at yet, use that tree.
......@@ -571,7 +571,7 @@ fn lockstep_iter_size(
571571/// * `[ $( ${count(foo, 1)} ),* ]` will return an error because `${count(foo, 1)}` is
572572/// declared inside a single repetition and the index `1` implies two nested repetitions.
573573fn count_repetitions<'a>(
574 dcx: &'a DiagCtxt,
574 dcx: DiagCtxtHandle<'a>,
575575 depth_user: usize,
576576 mut matched: &NamedMatch,
577577 repeats: &[(usize, usize)],
......@@ -632,7 +632,7 @@ fn count_repetitions<'a>(
632632
633633/// Returns a `NamedMatch` item declared on the LHS given an arbitrary [Ident]
634634fn matched_from_ident<'ctx, 'interp, 'rslt>(
635 dcx: &'ctx DiagCtxt,
635 dcx: DiagCtxtHandle<'ctx>,
636636 ident: Ident,
637637 interp: &'interp FxHashMap<MacroRulesNormalizedIdent, NamedMatch>,
638638) -> PResult<'ctx, &'rslt NamedMatch>
......@@ -646,7 +646,7 @@ where
646646
647647/// Used by meta-variable expressions when an user input is out of the actual declared bounds. For
648648/// example, index(999999) in an repetition of only three elements.
649fn out_of_bounds_err<'a>(dcx: &'a DiagCtxt, max: usize, span: Span, ty: &str) -> Diag<'a> {
649fn out_of_bounds_err<'a>(dcx: DiagCtxtHandle<'a>, max: usize, span: Span, ty: &str) -> Diag<'a> {
650650 let msg = if max == 0 {
651651 format!(
652652 "meta-variable expression `{ty}` with depth parameter \
......@@ -662,7 +662,7 @@ fn out_of_bounds_err<'a>(dcx: &'a DiagCtxt, max: usize, span: Span, ty: &str) ->
662662}
663663
664664fn transcribe_metavar_expr<'a>(
665 dcx: &'a DiagCtxt,
665 dcx: DiagCtxtHandle<'a>,
666666 expr: &MetaVarExpr,
667667 interp: &FxHashMap<MacroRulesNormalizedIdent, NamedMatch>,
668668 marker: &mut Marker,
......@@ -730,7 +730,7 @@ fn transcribe_metavar_expr<'a>(
730730
731731/// Extracts an identifier that can be originated from a `$var:ident` variable or from a token tree.
732732fn extract_ident<'a>(
733 dcx: &'a DiagCtxt,
733 dcx: DiagCtxtHandle<'a>,
734734 ident: Ident,
735735 interp: &FxHashMap<MacroRulesNormalizedIdent, NamedMatch>,
736736) -> PResult<'a, String> {
compiler/rustc_expand/src/proc_macro_server.rs+1-1
......@@ -522,7 +522,7 @@ impl server::FreeFunctions for Rustc<'_, '_> {
522522 fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) {
523523 let message = rustc_errors::DiagMessage::from(diagnostic.message);
524524 let mut diag: Diag<'_, ()> =
525 Diag::new(&self.psess().dcx, diagnostic.level.to_internal(), message);
525 Diag::new(self.psess().dcx(), diagnostic.level.to_internal(), message);
526526 diag.span(MultiSpan::from_spans(diagnostic.spans));
527527 for child in diagnostic.children {
528528 // This message comes from another diagnostic, and we are just reconstructing the
compiler/rustc_hir_analysis/src/check/errs.rs+1-1
......@@ -63,7 +63,7 @@ fn handle_static_mut_ref(
6363 } else {
6464 (errors::StaticMutRefSugg::Shared { span, var }, "shared")
6565 };
66 tcx.sess.psess.dcx.emit_err(errors::StaticMutRef { span, sugg, shared });
66 tcx.dcx().emit_err(errors::StaticMutRef { span, sugg, shared });
6767 } else {
6868 let (sugg, shared) = if mutable == Mutability::Mut {
6969 (errors::RefOfMutStaticSugg::Mut { span, var }, "mutable")
compiler/rustc_hir_analysis/src/coherence/orphan.rs+28-46
......@@ -403,74 +403,56 @@ fn emit_orphan_check_error<'tcx>(
403403 match *ty.kind() {
404404 ty::Slice(_) => {
405405 if is_foreign {
406 diag.subdiagnostic(
407 tcx.dcx(),
408 errors::OnlyCurrentTraitsForeign { span },
409 );
406 diag.subdiagnostic(errors::OnlyCurrentTraitsForeign { span });
410407 } else {
411 diag.subdiagnostic(
412 tcx.dcx(),
413 errors::OnlyCurrentTraitsName { span, name: "slices" },
414 );
408 diag.subdiagnostic(errors::OnlyCurrentTraitsName {
409 span,
410 name: "slices",
411 });
415412 }
416413 }
417414 ty::Array(..) => {
418415 if is_foreign {
419 diag.subdiagnostic(
420 tcx.dcx(),
421 errors::OnlyCurrentTraitsForeign { span },
422 );
416 diag.subdiagnostic(errors::OnlyCurrentTraitsForeign { span });
423417 } else {
424 diag.subdiagnostic(
425 tcx.dcx(),
426 errors::OnlyCurrentTraitsName { span, name: "arrays" },
427 );
418 diag.subdiagnostic(errors::OnlyCurrentTraitsName {
419 span,
420 name: "arrays",
421 });
428422 }
429423 }
430424 ty::Tuple(..) => {
431425 if is_foreign {
432 diag.subdiagnostic(
433 tcx.dcx(),
434 errors::OnlyCurrentTraitsForeign { span },
435 );
426 diag.subdiagnostic(errors::OnlyCurrentTraitsForeign { span });
436427 } else {
437 diag.subdiagnostic(
438 tcx.dcx(),
439 errors::OnlyCurrentTraitsName { span, name: "tuples" },
440 );
428 diag.subdiagnostic(errors::OnlyCurrentTraitsName {
429 span,
430 name: "tuples",
431 });
441432 }
442433 }
443434 ty::Alias(ty::Opaque, ..) => {
444 diag.subdiagnostic(tcx.dcx(), errors::OnlyCurrentTraitsOpaque { span });
435 diag.subdiagnostic(errors::OnlyCurrentTraitsOpaque { span });
445436 }
446437 ty::RawPtr(ptr_ty, mutbl) => {
447438 if !trait_ref.self_ty().has_param() {
448 diag.subdiagnostic(
449 tcx.dcx(),
450 errors::OnlyCurrentTraitsPointerSugg {
451 wrapper_span: impl_.self_ty.span,
452 struct_span: item.span.shrink_to_lo(),
453 mut_key: mutbl.prefix_str(),
454 ptr_ty,
455 },
456 );
439 diag.subdiagnostic(errors::OnlyCurrentTraitsPointerSugg {
440 wrapper_span: impl_.self_ty.span,
441 struct_span: item.span.shrink_to_lo(),
442 mut_key: mutbl.prefix_str(),
443 ptr_ty,
444 });
457445 }
458 diag.subdiagnostic(
459 tcx.dcx(),
460 errors::OnlyCurrentTraitsPointer { span, pointer: ty },
461 );
446 diag.subdiagnostic(errors::OnlyCurrentTraitsPointer { span, pointer: ty });
462447 }
463448 ty::Adt(adt_def, _) => {
464 diag.subdiagnostic(
465 tcx.dcx(),
466 errors::OnlyCurrentTraitsAdt {
467 span,
468 name: tcx.def_path_str(adt_def.did()),
469 },
470 );
449 diag.subdiagnostic(errors::OnlyCurrentTraitsAdt {
450 span,
451 name: tcx.def_path_str(adt_def.did()),
452 });
471453 }
472454 _ => {
473 diag.subdiagnostic(tcx.dcx(), errors::OnlyCurrentTraitsTy { span, ty });
455 diag.subdiagnostic(errors::OnlyCurrentTraitsTy { span, ty });
474456 }
475457 }
476458 }
compiler/rustc_hir_analysis/src/errors.rs+2-2
......@@ -2,7 +2,7 @@
22
33use crate::fluent_generated as fluent;
44use rustc_errors::{
5 codes::*, Applicability, Diag, DiagCtxt, Diagnostic, EmissionGuarantee, Level, MultiSpan,
5 codes::*, Applicability, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, MultiSpan,
66};
77use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
88use rustc_middle::ty::Ty;
......@@ -424,7 +424,7 @@ pub struct MissingTypeParams {
424424// Manual implementation of `Diagnostic` to be able to call `span_to_snippet`.
425425impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for MissingTypeParams {
426426 #[track_caller]
427 fn into_diag(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
427 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
428428 let mut err = Diag::new(dcx, level, fluent::hir_analysis_missing_type_params);
429429 err.span(self.span);
430430 err.code(E0393);
compiler/rustc_hir_typeck/src/_match.rs+1-1
......@@ -246,7 +246,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
246246
247247 let semi = expr.span.shrink_to_hi().with_hi(semi_span.hi());
248248 let sugg = crate::errors::RemoveSemiForCoerce { expr: expr.span, ret, semi };
249 diag.subdiagnostic(self.dcx(), sugg);
249 diag.subdiagnostic(sugg);
250250 }
251251
252252 /// When the previously checked expression (the scrutinee) diverges,
compiler/rustc_hir_typeck/src/cast.rs+9-15
......@@ -1005,25 +1005,19 @@ impl<'a, 'tcx> CastCheck<'tcx> {
10051005 if let Some((deref_ty, _)) = derefed {
10061006 // Give a note about what the expr derefs to.
10071007 if deref_ty != self.expr_ty.peel_refs() {
1008 err.subdiagnostic(
1009 fcx.dcx(),
1010 errors::DerefImplsIsEmpty {
1011 span: self.expr_span,
1012 deref_ty: fcx.ty_to_string(deref_ty),
1013 },
1014 );
1008 err.subdiagnostic(errors::DerefImplsIsEmpty {
1009 span: self.expr_span,
1010 deref_ty: fcx.ty_to_string(deref_ty),
1011 });
10151012 }
10161013
10171014 // Create a multipart suggestion: add `!` and `.is_empty()` in
10181015 // place of the cast.
1019 err.subdiagnostic(
1020 fcx.dcx(),
1021 errors::UseIsEmpty {
1022 lo: self.expr_span.shrink_to_lo(),
1023 hi: self.span.with_lo(self.expr_span.hi()),
1024 expr_ty: fcx.ty_to_string(self.expr_ty),
1025 },
1026 );
1016 err.subdiagnostic(errors::UseIsEmpty {
1017 lo: self.expr_span.shrink_to_lo(),
1018 hi: self.span.with_lo(self.expr_span.hi()),
1019 expr_ty: fcx.ty_to_string(self.expr_ty),
1020 });
10271021 }
10281022 }
10291023 }
compiler/rustc_hir_typeck/src/coercion.rs+5-11
......@@ -1782,20 +1782,14 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
17821782 }
17831783
17841784 let rpid_def_span = fcx.tcx.def_span(rpit_def_id);
1785 err.subdiagnostic(
1786 fcx.tcx.dcx(),
1787 SuggestBoxingForReturnImplTrait::ChangeReturnType {
1788 start_sp: rpid_def_span.with_hi(rpid_def_span.lo() + BytePos(4)),
1789 end_sp: rpid_def_span.shrink_to_hi(),
1790 },
1791 );
1785 err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
1786 start_sp: rpid_def_span.with_hi(rpid_def_span.lo() + BytePos(4)),
1787 end_sp: rpid_def_span.shrink_to_hi(),
1788 });
17921789
17931790 let (starts, ends) =
17941791 arm_spans.map(|span| (span.shrink_to_lo(), span.shrink_to_hi())).unzip();
1795 err.subdiagnostic(
1796 fcx.tcx.dcx(),
1797 SuggestBoxingForReturnImplTrait::BoxReturnExpr { starts, ends },
1798 );
1792 err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr { starts, ends });
17991793 }
18001794
18011795 fn report_return_mismatched_types<'a>(
compiler/rustc_hir_typeck/src/expr.rs+2-5
......@@ -384,7 +384,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
384384 if let Some(sp) =
385385 tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp)
386386 {
387 err.subdiagnostic(self.dcx(), ExprParenthesesNeeded::surrounding(*sp));
387 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
388388 }
389389 oprnd_t = Ty::new_error(tcx, err.emit());
390390 }
......@@ -2018,10 +2018,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
20182018 .shrink_to_hi()
20192019 .to(range_end.span);
20202020
2021 err.subdiagnostic(
2022 self.dcx(),
2023 TypeMismatchFruTypo { expr_span: range_start.span, fru_span, expr },
2024 );
2021 err.subdiagnostic(TypeMismatchFruTypo { expr_span: range_start.span, fru_span, expr });
20252022
20262023 // Suppress any range expr type mismatches
20272024 self.dcx().try_steal_replace_and_emit_err(
compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs+1-1
......@@ -1435,7 +1435,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
14351435 {
14361436 // The user provided `ptr::null()`, but the function expects
14371437 // `ptr::null_mut()`.
1438 err.subdiagnostic(self.dcx(), SuggestPtrNullMut { span: arg.span });
1438 err.subdiagnostic(SuggestPtrNullMut { span: arg.span });
14391439 }
14401440 }
14411441
compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs+3-4
......@@ -5,14 +5,13 @@ mod checks;
55mod inspect_obligations;
66mod suggestions;
77
8use rustc_errors::ErrorGuaranteed;
8use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
99
1010use crate::coercion::DynamicCoerceMany;
1111use crate::fallback::DivergingFallbackBehavior;
1212use crate::fn_ctxt::checks::DivergingBlockBehavior;
1313use crate::{CoroutineTypes, Diverges, EnclosingBreakables, TypeckRootCtxt};
1414use hir::def_id::CRATE_DEF_ID;
15use rustc_errors::DiagCtxt;
1615use rustc_hir as hir;
1716use rustc_hir::def_id::{DefId, LocalDefId};
1817use rustc_hir_analysis::hir_ty_lowering::{HirTyLowerer, RegionInferReason};
......@@ -145,8 +144,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
145144 }
146145 }
147146
148 pub(crate) fn dcx(&self) -> &'tcx DiagCtxt {
149 self.tcx.dcx()
147 pub(crate) fn dcx(&self) -> DiagCtxtHandle<'tcx> {
148 self.infcx.dcx()
150149 }
151150
152151 pub fn cause(&self, span: Span, code: ObligationCauseCode<'tcx>) -> ObligationCause<'tcx> {
compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs+40-58
......@@ -460,16 +460,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
460460 // but those checks need to be a bit more delicate and the benefit is diminishing.
461461 if self.can_eq(self.param_env, found_ty_inner, peeled) && error_tys_equate_as_ref {
462462 let sugg = prefix_wrap(".as_ref()");
463 err.subdiagnostic(
464 self.dcx(),
465 errors::SuggestConvertViaMethod {
466 span: expr.span.shrink_to_hi(),
467 sugg,
468 expected,
469 found,
470 borrow_removal_span,
471 },
472 );
463 err.subdiagnostic(errors::SuggestConvertViaMethod {
464 span: expr.span.shrink_to_hi(),
465 sugg,
466 expected,
467 found,
468 borrow_removal_span,
469 });
473470 return true;
474471 } else if let Some((deref_ty, _)) =
475472 self.autoderef(expr.span, found_ty_inner).silence_errors().nth(1)
......@@ -477,16 +474,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
477474 && error_tys_equate_as_ref
478475 {
479476 let sugg = prefix_wrap(".as_deref()");
480 err.subdiagnostic(
481 self.dcx(),
482 errors::SuggestConvertViaMethod {
483 span: expr.span.shrink_to_hi(),
484 sugg,
485 expected,
486 found,
487 borrow_removal_span,
488 },
489 );
477 err.subdiagnostic(errors::SuggestConvertViaMethod {
478 span: expr.span.shrink_to_hi(),
479 sugg,
480 expected,
481 found,
482 borrow_removal_span,
483 });
490484 return true;
491485 } else if let ty::Adt(adt, _) = found_ty_inner.peel_refs().kind()
492486 && self.tcx.is_lang_item(adt.did(), LangItem::String)
......@@ -573,7 +567,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
573567 end: span.shrink_to_hi(),
574568 },
575569 };
576 err.subdiagnostic(self.dcx(), suggest_boxing);
570 err.subdiagnostic(suggest_boxing);
577571
578572 true
579573 } else {
......@@ -814,28 +808,22 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
814808 match &fn_decl.output {
815809 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() && !can_suggest => {
816810 // `fn main()` must return `()`, do not suggest changing return type
817 err.subdiagnostic(self.dcx(), errors::ExpectedReturnTypeLabel::Unit { span });
811 err.subdiagnostic(errors::ExpectedReturnTypeLabel::Unit { span });
818812 return true;
819813 }
820814 &hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
821815 if let Some(found) = found.make_suggestable(self.tcx, false, None) {
822 err.subdiagnostic(
823 self.dcx(),
824 errors::AddReturnTypeSuggestion::Add { span, found: found.to_string() },
825 );
816 err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
817 span,
818 found: found.to_string(),
819 });
826820 return true;
827821 } else if let Some(sugg) = suggest_impl_trait(self, self.param_env, found) {
828 err.subdiagnostic(
829 self.dcx(),
830 errors::AddReturnTypeSuggestion::Add { span, found: sugg },
831 );
822 err.subdiagnostic(errors::AddReturnTypeSuggestion::Add { span, found: sugg });
832823 return true;
833824 } else {
834825 // FIXME: if `found` could be `impl Iterator` we should suggest that.
835 err.subdiagnostic(
836 self.dcx(),
837 errors::AddReturnTypeSuggestion::MissingHere { span },
838 );
826 err.subdiagnostic(errors::AddReturnTypeSuggestion::MissingHere { span });
839827 return true;
840828 }
841829 }
......@@ -856,19 +844,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
856844 debug!(?found);
857845 if found.is_suggestable(self.tcx, false) {
858846 if ty.span.is_empty() {
859 err.subdiagnostic(
860 self.dcx(),
861 errors::AddReturnTypeSuggestion::Add {
862 span: ty.span,
863 found: found.to_string(),
864 },
865 );
847 err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
848 span: ty.span,
849 found: found.to_string(),
850 });
866851 return true;
867852 } else {
868 err.subdiagnostic(
869 self.dcx(),
870 errors::ExpectedReturnTypeLabel::Other { span: ty.span, expected },
871 );
853 err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
854 span: ty.span,
855 expected,
856 });
872857 }
873858 }
874859 } else {
......@@ -883,10 +868,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
883868 let ty = self.normalize(hir_ty.span, ty);
884869 let ty = self.tcx.instantiate_bound_regions_with_erased(ty);
885870 if self.can_coerce(expected, ty) {
886 err.subdiagnostic(
887 self.dcx(),
888 errors::ExpectedReturnTypeLabel::Other { span: hir_ty.span, expected },
889 );
871 err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other {
872 span: hir_ty.span,
873 expected,
874 });
890875 self.try_suggest_return_impl_trait(err, expected, found, fn_id);
891876 self.note_caller_chooses_ty_for_ty_param(err, expected, found);
892877 return true;
......@@ -905,13 +890,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
905890 found: Ty<'tcx>,
906891 ) {
907892 if let ty::Param(expected_ty_as_param) = expected.kind() {
908 diag.subdiagnostic(
909 self.dcx(),
910 errors::NoteCallerChoosesTyForTyParam {
911 ty_param_name: expected_ty_as_param.name,
912 found_ty: found,
913 },
914 );
893 diag.subdiagnostic(errors::NoteCallerChoosesTyForTyParam {
894 ty_param_name: expected_ty_as_param.name,
895 found_ty: found,
896 });
915897 }
916898 }
917899
......@@ -1136,7 +1118,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
11361118 let sp = self.tcx.sess.source_map().start_point(expr.span).with_parent(None);
11371119 if let Some(sp) = self.tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp) {
11381120 // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }`
1139 err.subdiagnostic(self.dcx(), ExprParenthesesNeeded::surrounding(*sp));
1121 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
11401122 true
11411123 } else {
11421124 false
......@@ -1250,7 +1232,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
12501232 } else {
12511233 return false;
12521234 };
1253 diag.subdiagnostic(self.dcx(), subdiag);
1235 diag.subdiagnostic(subdiag);
12541236 return true;
12551237 }
12561238 }
compiler/rustc_hir_typeck/src/method/suggest.rs+12-15
......@@ -3729,22 +3729,19 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
37293729 if impls_trait(trait_info.def_id) {
37303730 self.suggest_valid_traits(err, item_name, vec![trait_info.def_id], false);
37313731 } else {
3732 err.subdiagnostic(
3733 self.dcx(),
3734 CandidateTraitNote {
3735 span: self.tcx.def_span(trait_info.def_id),
3736 trait_name: self.tcx.def_path_str(trait_info.def_id),
3737 item_name,
3738 action_or_ty: if trait_missing_method {
3739 "NONE".to_string()
3740 } else {
3741 param_type.map_or_else(
3742 || "implement".to_string(), // FIXME: it might only need to be imported into scope, not implemented.
3743 |p| p.to_string(),
3744 )
3745 },
3732 err.subdiagnostic(CandidateTraitNote {
3733 span: self.tcx.def_span(trait_info.def_id),
3734 trait_name: self.tcx.def_path_str(trait_info.def_id),
3735 item_name,
3736 action_or_ty: if trait_missing_method {
3737 "NONE".to_string()
3738 } else {
3739 param_type.map_or_else(
3740 || "implement".to_string(), // FIXME: it might only need to be imported into scope, not implemented.
3741 |p| p.to_string(),
3742 )
37463743 },
3747 );
3744 });
37483745 }
37493746 }
37503747 trait_infos => {
compiler/rustc_hir_typeck/src/op.rs+1-1
......@@ -820,7 +820,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
820820 // If the previous expression was a block expression, suggest parentheses
821821 // (turning this into a binary subtraction operation instead.)
822822 // for example, `{2} - 2` -> `({2}) - 2` (see src\test\ui\parser\expr-as-stmt.rs)
823 err.subdiagnostic(self.dcx(), ExprParenthesesNeeded::surrounding(*sp));
823 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
824824 } else {
825825 match actual.kind() {
826826 Uint(_) if op == hir::UnOp::Neg => {
compiler/rustc_infer/src/infer/error_reporting/mod.rs+6-6
......@@ -61,8 +61,8 @@ use crate::traits::{
6161use crate::infer::relate::{self, RelateResult, TypeRelation};
6262use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
6363use rustc_errors::{
64 codes::*, pluralize, struct_span_code_err, Applicability, Diag, DiagCtxt, DiagStyledString,
65 ErrorGuaranteed, IntoDiagArg, StringPart,
64 codes::*, pluralize, struct_span_code_err, Applicability, Diag, DiagCtxtHandle,
65 DiagStyledString, ErrorGuaranteed, IntoDiagArg, StringPart,
6666};
6767use rustc_hir::def::DefKind;
6868use rustc_hir::def_id::{DefId, LocalDefId};
......@@ -139,8 +139,8 @@ pub struct TypeErrCtxt<'a, 'tcx> {
139139}
140140
141141impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
142 pub fn dcx(&self) -> &'tcx DiagCtxt {
143 self.infcx.tcx.dcx()
142 pub fn dcx(&self) -> DiagCtxtHandle<'tcx> {
143 self.infcx.dcx()
144144 }
145145
146146 /// This is just to avoid a potential footgun of accidentally
......@@ -892,7 +892,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
892892 arm_ty,
893893 arm_span,
894894 ) {
895 err.subdiagnostic(self.dcx(), subdiag);
895 err.subdiagnostic(subdiag);
896896 }
897897 }
898898 },
......@@ -918,7 +918,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
918918 else_ty,
919919 else_span,
920920 ) {
921 err.subdiagnostic(self.dcx(), subdiag);
921 err.subdiagnostic(subdiag);
922922 }
923923 }
924924 ObligationCauseCode::LetElse => {
compiler/rustc_infer/src/infer/error_reporting/note.rs+1-1
......@@ -369,7 +369,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
369369 trait_predicates: trait_predicates.join(", "),
370370 }
371371 };
372 err.subdiagnostic(self.dcx(), suggestion);
372 err.subdiagnostic(suggestion);
373373 }
374374
375375 pub(super) fn report_placeholder_failure(
compiler/rustc_infer/src/infer/error_reporting/suggest.rs+14-15
......@@ -121,7 +121,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
121121 span_low: cause.span.shrink_to_lo(),
122122 span_high: cause.span.shrink_to_hi(),
123123 };
124 diag.subdiagnostic(self.dcx(), sugg);
124 diag.subdiagnostic(sugg);
125125 }
126126 _ => {
127127 // More than one matching variant.
......@@ -130,7 +130,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
130130 cause_span: cause.span,
131131 compatible_variants,
132132 };
133 diag.subdiagnostic(self.dcx(), sugg);
133 diag.subdiagnostic(sugg);
134134 }
135135 }
136136 }
......@@ -202,10 +202,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
202202 },
203203 (_, Some(ty)) if self.same_type_modulo_infer(exp_found.expected, ty) => {
204204 // FIXME: Seems like we can't have a suggestion and a note with different spans in a single subdiagnostic
205 diag.subdiagnostic(
206 self.dcx(),
207 ConsiderAddingAwait::FutureSugg { span: exp_span.shrink_to_hi() },
208 );
205 diag.subdiagnostic(ConsiderAddingAwait::FutureSugg {
206 span: exp_span.shrink_to_hi(),
207 });
209208 Some(ConsiderAddingAwait::FutureSuggNote { span: exp_span })
210209 }
211210 (Some(ty), _) if self.same_type_modulo_infer(ty, exp_found.found) => match cause.code()
......@@ -233,7 +232,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
233232 _ => None,
234233 };
235234 if let Some(subdiag) = subdiag {
236 diag.subdiagnostic(self.dcx(), subdiag);
235 diag.subdiagnostic(subdiag);
237236 }
238237 }
239238
......@@ -269,7 +268,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
269268 } else {
270269 return;
271270 };
272 diag.subdiagnostic(self.dcx(), suggestion);
271 diag.subdiagnostic(suggestion);
273272 }
274273 }
275274 }
......@@ -401,15 +400,15 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
401400 (true, false) => FunctionPointerSuggestion::UseRef { span, fn_name },
402401 (false, true) => FunctionPointerSuggestion::RemoveRef { span, fn_name },
403402 (true, true) => {
404 diag.subdiagnostic(self.dcx(), FnItemsAreDistinct);
403 diag.subdiagnostic(FnItemsAreDistinct);
405404 FunctionPointerSuggestion::CastRef { span, fn_name, sig: *sig }
406405 }
407406 (false, false) => {
408 diag.subdiagnostic(self.dcx(), FnItemsAreDistinct);
407 diag.subdiagnostic(FnItemsAreDistinct);
409408 FunctionPointerSuggestion::Cast { span, fn_name, sig: *sig }
410409 }
411410 };
412 diag.subdiagnostic(self.dcx(), sugg);
411 diag.subdiagnostic(sugg);
413412 }
414413 (ty::FnDef(did1, args1), ty::FnDef(did2, args2)) => {
415414 let expected_sig =
......@@ -418,7 +417,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
418417 &(self.normalize_fn_sig)(self.tcx.fn_sig(*did2).instantiate(self.tcx, args2));
419418
420419 if self.same_type_modulo_infer(*expected_sig, *found_sig) {
421 diag.subdiagnostic(self.dcx(), FnUniqTypes);
420 diag.subdiagnostic(FnUniqTypes);
422421 }
423422
424423 if !self.same_type_modulo_infer(*found_sig, *expected_sig)
......@@ -447,7 +446,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
447446 }
448447 };
449448
450 diag.subdiagnostic(self.dcx(), sug);
449 diag.subdiagnostic(sug);
451450 }
452451 (ty::FnDef(did, args), ty::FnPtr(sig)) => {
453452 let expected_sig =
......@@ -466,7 +465,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
466465 format!("{fn_name} as {found_sig}")
467466 };
468467
469 diag.subdiagnostic(self.dcx(), FnConsiderCasting { casting });
468 diag.subdiagnostic(FnConsiderCasting { casting });
470469 }
471470 _ => {
472471 return;
......@@ -889,7 +888,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
889888 let diag = self.consider_returning_binding_diag(blk, expected_ty);
890889 match diag {
891890 Some(diag) => {
892 err.subdiagnostic(self.dcx(), diag);
891 err.subdiagnostic(diag);
893892 true
894893 }
895894 None => false,
compiler/rustc_infer/src/infer/mod.rs+3-2
......@@ -4,6 +4,7 @@ pub use lexical_region_resolve::RegionResolutionError;
44pub use relate::combine::CombineFields;
55pub use relate::combine::PredicateEmittingRelation;
66pub use relate::StructurallyRelateAliases;
7use rustc_errors::DiagCtxtHandle;
78pub use rustc_macros::{TypeFoldable, TypeVisitable};
89pub use rustc_middle::ty::IntVarValue;
910pub use BoundRegionConversionTime::*;
......@@ -23,7 +24,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
2324use rustc_data_structures::sync::Lrc;
2425use rustc_data_structures::undo_log::Rollback;
2526use rustc_data_structures::unify as ut;
26use rustc_errors::{Diag, DiagCtxt, ErrorGuaranteed};
27use rustc_errors::{Diag, ErrorGuaranteed};
2728use rustc_hir::def_id::{DefId, LocalDefId};
2829use rustc_macros::extension;
2930use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
......@@ -826,7 +827,7 @@ impl<'tcx> InferOk<'tcx, ()> {
826827}
827828
828829impl<'tcx> InferCtxt<'tcx> {
829 pub fn dcx(&self) -> &'tcx DiagCtxt {
830 pub fn dcx(&self) -> DiagCtxtHandle<'tcx> {
830831 self.tcx.dcx()
831832 }
832833
compiler/rustc_interface/src/interface.rs+6-6
......@@ -9,7 +9,7 @@ use rustc_data_structures::jobserver;
99use rustc_data_structures::stable_hasher::StableHasher;
1010use rustc_data_structures::sync::Lrc;
1111use rustc_errors::registry::Registry;
12use rustc_errors::{DiagCtxt, ErrorGuaranteed};
12use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
1313use rustc_lint::LintStore;
1414use rustc_middle::ty;
1515use rustc_middle::ty::CurrentGcx;
......@@ -46,7 +46,7 @@ pub struct Compiler {
4646}
4747
4848/// Converts strings provided as `--cfg [cfgspec]` into a `Cfg`.
49pub(crate) fn parse_cfg(dcx: &DiagCtxt, cfgs: Vec<String>) -> Cfg {
49pub(crate) fn parse_cfg(dcx: DiagCtxtHandle<'_>, cfgs: Vec<String>) -> Cfg {
5050 cfgs.into_iter()
5151 .map(|s| {
5252 let psess = ParseSess::with_silent_emitter(
......@@ -105,7 +105,7 @@ pub(crate) fn parse_cfg(dcx: &DiagCtxt, cfgs: Vec<String>) -> Cfg {
105105}
106106
107107/// Converts strings provided as `--check-cfg [specs]` into a `CheckCfg`.
108pub(crate) fn parse_check_cfg(dcx: &DiagCtxt, specs: Vec<String>) -> CheckCfg {
108pub(crate) fn parse_check_cfg(dcx: DiagCtxtHandle<'_>, specs: Vec<String>) -> CheckCfg {
109109 // If any --check-cfg is passed then exhaustive_values and exhaustive_names
110110 // are enabled by default.
111111 let exhaustive_names = !specs.is_empty();
......@@ -451,12 +451,12 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
451451
452452 codegen_backend.init(&sess);
453453
454 let cfg = parse_cfg(&sess.dcx(), config.crate_cfg);
454 let cfg = parse_cfg(sess.dcx(), config.crate_cfg);
455455 let mut cfg = config::build_configuration(&sess, cfg);
456456 util::add_configuration(&mut cfg, &mut sess, &*codegen_backend);
457457 sess.psess.config = cfg;
458458
459 let mut check_cfg = parse_check_cfg(&sess.dcx(), config.crate_check_cfg);
459 let mut check_cfg = parse_check_cfg(sess.dcx(), config.crate_check_cfg);
460460 check_cfg.fill_well_known(&sess.target);
461461 sess.psess.check_config = check_cfg;
462462
......@@ -529,7 +529,7 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
529529}
530530
531531pub fn try_print_query_stack(
532 dcx: &DiagCtxt,
532 dcx: DiagCtxtHandle<'_>,
533533 num_frames: Option<usize>,
534534 file: Option<std::fs::File>,
535535) {
compiler/rustc_interface/src/tests.rs+1-1
......@@ -70,7 +70,7 @@ where
7070 Arc::default(),
7171 Default::default(),
7272 );
73 let cfg = parse_cfg(&sess.dcx(), matches.opt_strs("cfg"));
73 let cfg = parse_cfg(sess.dcx(), matches.opt_strs("cfg"));
7474 let cfg = build_configuration(&sess, cfg);
7575 f(sess, cfg)
7676 });
compiler/rustc_lint/src/lints.rs+3-3
......@@ -1405,7 +1405,7 @@ impl<'a> LintDiagnostic<'a, ()> for NonLocalDefinitionsDiag {
14051405 diag.note(fluent::lint_macro_to_change);
14061406 }
14071407 if let Some(cargo_update) = cargo_update {
1408 diag.subdiagnostic(&diag.dcx, cargo_update);
1408 diag.subdiagnostic(cargo_update);
14091409 }
14101410
14111411 if has_trait {
......@@ -1471,7 +1471,7 @@ impl<'a> LintDiagnostic<'a, ()> for NonLocalDefinitionsDiag {
14711471 diag.note(fluent::lint_non_local_definitions_deprecation);
14721472
14731473 if let Some(cargo_update) = cargo_update {
1474 diag.subdiagnostic(&diag.dcx, cargo_update);
1474 diag.subdiagnostic(cargo_update);
14751475 }
14761476 }
14771477 }
......@@ -1957,7 +1957,7 @@ impl<'a> LintDiagnostic<'a, ()> for UnusedDef<'_, '_> {
19571957 diag.note(note.to_string());
19581958 }
19591959 if let Some(sugg) = self.suggestion {
1960 diag.subdiagnostic(diag.dcx, sugg);
1960 diag.subdiagnostic(sugg);
19611961 }
19621962 }
19631963}
compiler/rustc_macros/src/diagnostics/diagnostic.rs+1-1
......@@ -78,7 +78,7 @@ impl<'a> DiagnosticDerive<'a> {
7878 #[track_caller]
7979 fn into_diag(
8080 self,
81 dcx: &'_sess rustc_errors::DiagCtxt,
81 dcx: rustc_errors::DiagCtxtHandle<'_sess>,
8282 level: rustc_errors::Level
8383 ) -> rustc_errors::Diag<'_sess, G> {
8484 #implementation
compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs+1-1
......@@ -335,7 +335,7 @@ impl DiagnosticDeriveVariantBuilder {
335335 }
336336 }
337337 (Meta::Path(_), "subdiagnostic") => {
338 return Ok(quote! { diag.subdiagnostic(diag.dcx, #binding); });
338 return Ok(quote! { diag.subdiagnostic(#binding); });
339339 }
340340 _ => (),
341341 }
compiler/rustc_metadata/src/creader.rs+3-3
......@@ -10,7 +10,7 @@ use rustc_data_structures::fx::FxHashSet;
1010use rustc_data_structures::owned_slice::OwnedSlice;
1111use rustc_data_structures::svh::Svh;
1212use rustc_data_structures::sync::{self, FreezeReadGuard, FreezeWriteGuard};
13use rustc_errors::DiagCtxt;
13use rustc_errors::DiagCtxtHandle;
1414use rustc_expand::base::SyntaxExtension;
1515use rustc_fs_util::try_canonicalize;
1616use rustc_hir::def_id::{CrateNum, LocalDefId, StableCrateId, LOCAL_CRATE};
......@@ -91,8 +91,8 @@ impl<'a, 'tcx> std::ops::Deref for CrateLoader<'a, 'tcx> {
9191}
9292
9393impl<'a, 'tcx> CrateLoader<'a, 'tcx> {
94 fn dcx(&self) -> &'tcx DiagCtxt {
95 &self.tcx.dcx()
94 fn dcx(&self) -> DiagCtxtHandle<'tcx> {
95 self.tcx.dcx()
9696 }
9797}
9898
compiler/rustc_metadata/src/errors.rs+4-4
......@@ -3,7 +3,7 @@ use std::{
33 path::{Path, PathBuf},
44};
55
6use rustc_errors::{codes::*, Diag, DiagCtxt, Diagnostic, EmissionGuarantee, Level};
6use rustc_errors::{codes::*, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level};
77use rustc_macros::{Diagnostic, Subdiagnostic};
88use rustc_span::{sym, Span, Symbol};
99use rustc_target::spec::{PanicStrategy, TargetTriple};
......@@ -503,7 +503,7 @@ pub(crate) struct MultipleCandidates {
503503}
504504
505505impl<G: EmissionGuarantee> Diagnostic<'_, G> for MultipleCandidates {
506 fn into_diag(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
506 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
507507 let mut diag = Diag::new(dcx, level, fluent::metadata_multiple_candidates);
508508 diag.arg("crate_name", self.crate_name);
509509 diag.arg("flavor", self.flavor);
......@@ -602,7 +602,7 @@ pub struct InvalidMetadataFiles {
602602
603603impl<G: EmissionGuarantee> Diagnostic<'_, G> for InvalidMetadataFiles {
604604 #[track_caller]
605 fn into_diag(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
605 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
606606 let mut diag = Diag::new(dcx, level, fluent::metadata_invalid_meta_files);
607607 diag.arg("crate_name", self.crate_name);
608608 diag.arg("add_info", self.add_info);
......@@ -631,7 +631,7 @@ pub struct CannotFindCrate {
631631
632632impl<G: EmissionGuarantee> Diagnostic<'_, G> for CannotFindCrate {
633633 #[track_caller]
634 fn into_diag(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
634 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
635635 let mut diag = Diag::new(dcx, level, fluent::metadata_cannot_find_crate);
636636 diag.arg("crate_name", self.crate_name);
637637 diag.arg("current_crate", self.current_crate);
compiler/rustc_middle/src/macros.rs+4-4
......@@ -4,10 +4,10 @@
44///
55/// If you have a span available, you should use [`span_bug`] instead.
66///
7/// If the bug should only be emitted when compilation didn't fail, [`DiagCtxt::span_delayed_bug`]
7/// If the bug should only be emitted when compilation didn't fail, [`DiagCtxtHandle::span_delayed_bug`]
88/// may be useful.
99///
10/// [`DiagCtxt::span_delayed_bug`]: rustc_errors::DiagCtxt::span_delayed_bug
10/// [`DiagCtxtHandle::span_delayed_bug`]: rustc_errors::DiagCtxtHandle::span_delayed_bug
1111/// [`span_bug`]: crate::span_bug
1212#[macro_export]
1313macro_rules! bug {
......@@ -30,10 +30,10 @@ macro_rules! bug {
3030/// at the code the compiler was compiling when it ICEd. This is the preferred way to trigger
3131/// ICEs.
3232///
33/// If the bug should only be emitted when compilation didn't fail, [`DiagCtxt::span_delayed_bug`]
33/// If the bug should only be emitted when compilation didn't fail, [`DiagCtxtHandle::span_delayed_bug`]
3434/// may be useful.
3535///
36/// [`DiagCtxt::span_delayed_bug`]: rustc_errors::DiagCtxt::span_delayed_bug
36/// [`DiagCtxtHandle::span_delayed_bug`]: rustc_errors::DiagCtxtHandle::span_delayed_bug
3737#[macro_export]
3838macro_rules! span_bug {
3939 ($span:expr, $msg:expr) => (
compiler/rustc_middle/src/middle/stability.rs+1-1
......@@ -176,7 +176,7 @@ impl<'a, G: EmissionGuarantee> rustc_errors::LintDiagnostic<'a, G> for Deprecate
176176 diag.arg("has_note", false);
177177 }
178178 if let Some(sub) = self.sub {
179 diag.subdiagnostic(diag.dcx, sub);
179 diag.subdiagnostic(sub);
180180 }
181181 }
182182}
compiler/rustc_middle/src/ty/context.rs+4-2
......@@ -47,7 +47,9 @@ use rustc_data_structures::sync::{self, FreezeReadGuard, Lock, Lrc, RwLock, Work
4747#[cfg(parallel_compiler)]
4848use rustc_data_structures::sync::{DynSend, DynSync};
4949use rustc_data_structures::unord::UnordSet;
50use rustc_errors::{Applicability, Diag, DiagCtxt, ErrorGuaranteed, LintDiagnostic, MultiSpan};
50use rustc_errors::{
51 Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, LintDiagnostic, MultiSpan,
52};
5153use rustc_hir as hir;
5254use rustc_hir::def::DefKind;
5355use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE};
......@@ -1415,7 +1417,7 @@ impl<'tcx> TyCtxt<'tcx> {
14151417 )
14161418 }
14171419
1418 pub fn dcx(self) -> &'tcx DiagCtxt {
1420 pub fn dcx(self) -> DiagCtxtHandle<'tcx> {
14191421 self.sess.dcx()
14201422 }
14211423}
compiler/rustc_middle/src/ty/layout.rs+2-2
......@@ -5,7 +5,7 @@ use crate::ty::normalize_erasing_regions::NormalizationError;
55use crate::ty::{self, CoroutineArgsExt, Ty, TyCtxt, TypeVisitableExt};
66use rustc_error_messages::DiagMessage;
77use rustc_errors::{
8 Diag, DiagArgValue, DiagCtxt, Diagnostic, EmissionGuarantee, IntoDiagArg, Level,
8 Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, IntoDiagArg, Level,
99};
1010use rustc_hir as hir;
1111use rustc_hir::def_id::DefId;
......@@ -1256,7 +1256,7 @@ pub enum FnAbiError<'tcx> {
12561256}
12571257
12581258impl<'a, 'b, G: EmissionGuarantee> Diagnostic<'a, G> for FnAbiError<'b> {
1259 fn into_diag(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
1259 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
12601260 match self {
12611261 Self::Layout(e) => e.into_diagnostic().into_diag(dcx, level),
12621262 Self::AdjustForForeignAbi(call::AdjustForForeignAbiError::Unsupported {
compiler/rustc_mir_build/src/errors.rs+3-3
......@@ -1,9 +1,9 @@
11use crate::fluent_generated as fluent;
2use rustc_errors::DiagArgValue;
32use rustc_errors::{
4 codes::*, Applicability, Diag, DiagCtxt, Diagnostic, EmissionGuarantee, Level, MultiSpan,
3 codes::*, Applicability, Diag, Diagnostic, EmissionGuarantee, Level, MultiSpan,
54 SubdiagMessageOp, Subdiagnostic,
65};
6use rustc_errors::{DiagArgValue, DiagCtxtHandle};
77use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
88use rustc_middle::ty::{self, Ty};
99use rustc_pattern_analysis::{errors::Uncovered, rustc::RustcPatCtxt};
......@@ -492,7 +492,7 @@ pub(crate) struct NonExhaustivePatternsTypeNotEmpty<'p, 'tcx, 'm> {
492492}
493493
494494impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for NonExhaustivePatternsTypeNotEmpty<'_, '_, '_> {
495 fn into_diag(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'_, G> {
495 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'_, G> {
496496 let mut diag =
497497 Diag::new(dcx, level, fluent::mir_build_non_exhaustive_patterns_type_not_empty);
498498 diag.span(self.scrut_span);
compiler/rustc_mir_build/src/thir/pattern/check_match.rs+1-1
......@@ -1137,7 +1137,7 @@ fn report_non_exhaustive_match<'p, 'tcx>(
11371137
11381138 let all_arms_have_guards = arms.iter().all(|arm_id| thir[*arm_id].guard.is_some());
11391139 if !is_empty_match && all_arms_have_guards {
1140 err.subdiagnostic(cx.tcx.dcx(), NonExhaustiveMatchAllArmsGuarded);
1140 err.subdiagnostic(NonExhaustiveMatchAllArmsGuarded);
11411141 }
11421142 if let Some((span, sugg)) = suggestion {
11431143 err.span_suggestion_verbose(span, msg, sugg, Applicability::HasPlaceholders);
compiler/rustc_mir_transform/src/errors.rs+1-1
......@@ -104,7 +104,7 @@ impl<'a> LintDiagnostic<'a, ()> for MustNotSupend<'_, '_> {
104104 diag.primary_message(fluent::mir_transform_must_not_suspend);
105105 diag.span_label(self.yield_sp, fluent::_subdiag::label);
106106 if let Some(reason) = self.reason {
107 diag.subdiagnostic(diag.dcx, reason);
107 diag.subdiagnostic(reason);
108108 }
109109 diag.span_help(self.src_sp, fluent::_subdiag::help);
110110 diag.arg("pre", self.pre);
compiler/rustc_monomorphize/src/errors.rs+2-2
......@@ -1,7 +1,7 @@
11use std::path::PathBuf;
22
33use crate::fluent_generated as fluent;
4use rustc_errors::{Diag, DiagCtxt, Diagnostic, EmissionGuarantee, Level};
4use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level};
55use rustc_macros::{Diagnostic, LintDiagnostic};
66use rustc_span::{Span, Symbol};
77
......@@ -48,7 +48,7 @@ pub struct UnusedGenericParamsHint {
4848
4949impl<G: EmissionGuarantee> Diagnostic<'_, G> for UnusedGenericParamsHint {
5050 #[track_caller]
51 fn into_diag(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
51 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
5252 let mut diag = Diag::new(dcx, level, fluent::monomorphize_unused_generic_params);
5353 diag.span(self.span);
5454 for (span, name) in self.param_spans.into_iter().zip(self.param_names) {
compiler/rustc_parse/src/errors.rs+3-3
......@@ -3,7 +3,7 @@ use std::borrow::Cow;
33use rustc_ast::token::Token;
44use rustc_ast::{Path, Visibility};
55use rustc_errors::{
6 codes::*, Applicability, Diag, DiagCtxt, Diagnostic, EmissionGuarantee, Level,
6 codes::*, Applicability, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level,
77 SubdiagMessageOp, Subdiagnostic,
88};
99use rustc_macros::{Diagnostic, Subdiagnostic};
......@@ -1052,7 +1052,7 @@ pub(crate) struct ExpectedIdentifier {
10521052
10531053impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for ExpectedIdentifier {
10541054 #[track_caller]
1055 fn into_diag(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
1055 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
10561056 let token_descr = TokenDescription::from_token(&self.token);
10571057
10581058 let mut diag = Diag::new(
......@@ -1112,7 +1112,7 @@ pub(crate) struct ExpectedSemi {
11121112
11131113impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for ExpectedSemi {
11141114 #[track_caller]
1115 fn into_diag(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
1115 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
11161116 let token_descr = TokenDescription::from_token(&self.token);
11171117
11181118 let mut diag = Diag::new(
compiler/rustc_parse/src/lexer/mod.rs+6-7
......@@ -7,7 +7,7 @@ use rustc_ast::ast::{self, AttrStyle};
77use rustc_ast::token::{self, CommentKind, Delimiter, IdentIsRaw, Token, TokenKind};
88use rustc_ast::tokenstream::TokenStream;
99use rustc_ast::util::unicode::contains_text_flow_control_chars;
10use rustc_errors::{codes::*, Applicability, Diag, DiagCtxt, StashKey};
10use rustc_errors::{codes::*, Applicability, Diag, DiagCtxtHandle, StashKey};
1111use rustc_lexer::unescape::{self, EscapeError, Mode};
1212use rustc_lexer::{Base, DocStyle, RawStrError};
1313use rustc_lexer::{Cursor, LiteralKind};
......@@ -113,8 +113,8 @@ struct StringReader<'psess, 'src> {
113113}
114114
115115impl<'psess, 'src> StringReader<'psess, 'src> {
116 fn dcx(&self) -> &'psess DiagCtxt {
117 &self.psess.dcx
116 fn dcx(&self) -> DiagCtxtHandle<'psess> {
117 self.psess.dcx()
118118 }
119119
120120 fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
......@@ -248,8 +248,8 @@ impl<'psess, 'src> StringReader<'psess, 'src> {
248248 let suffix = if suffix_start < self.pos {
249249 let string = self.str_from(suffix_start);
250250 if string == "_" {
251 self.psess
252 .dcx
251 self
252 .dcx()
253253 .emit_err(errors::UnderscoreLiteralSuffix { span: self.mk_sp(suffix_start, self.pos) });
254254 None
255255 } else {
......@@ -597,8 +597,7 @@ impl<'psess, 'src> StringReader<'psess, 'src> {
597597 }
598598
599599 fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! {
600 self.psess
601 .dcx
600 self.dcx()
602601 .struct_span_fatal(
603602 self.mk_sp(start, self.pos),
604603 format!(
compiler/rustc_parse/src/lexer/tokentrees.rs+2-2
......@@ -71,7 +71,7 @@ impl<'psess, 'src> TokenTreesReader<'psess, 'src> {
7171
7272 fn eof_err(&mut self) -> PErr<'psess> {
7373 let msg = "this file contains an unclosed delimiter";
74 let mut err = self.string_reader.psess.dcx.struct_span_err(self.token.span, msg);
74 let mut err = self.string_reader.dcx().struct_span_err(self.token.span, msg);
7575 for &(_, sp) in &self.diag_info.open_braces {
7676 err.span_label(sp, "unclosed delimiter");
7777 self.diag_info.unmatched_delims.push(UnmatchedDelim {
......@@ -290,7 +290,7 @@ impl<'psess, 'src> TokenTreesReader<'psess, 'src> {
290290 // An unexpected closing delimiter (i.e., there is no matching opening delimiter).
291291 let token_str = token_to_string(&self.token);
292292 let msg = format!("unexpected closing delimiter: `{token_str}`");
293 let mut err = self.string_reader.psess.dcx.struct_span_err(self.token.span, msg);
293 let mut err = self.string_reader.dcx().struct_span_err(self.token.span, msg);
294294
295295 report_suspicious_mismatch_block(
296296 &mut err,
compiler/rustc_parse/src/lexer/unescape_error_reporting.rs+2-2
......@@ -3,7 +3,7 @@
33use std::iter::once;
44use std::ops::Range;
55
6use rustc_errors::{Applicability, DiagCtxt, ErrorGuaranteed};
6use rustc_errors::{Applicability, DiagCtxtHandle, ErrorGuaranteed};
77use rustc_lexer::unescape::{EscapeError, Mode};
88use rustc_span::{BytePos, Span};
99use tracing::debug;
......@@ -11,7 +11,7 @@ use tracing::debug;
1111use crate::errors::{MoreThanOneCharNote, MoreThanOneCharSugg, NoBraceUnicodeSub, UnescapeError};
1212
1313pub(crate) fn emit_unescape_error(
14 dcx: &DiagCtxt,
14 dcx: DiagCtxtHandle<'_>,
1515 // interior part of the literal, between quotes
1616 lit: &str,
1717 // full span of the literal, including quotes and any prefix
compiler/rustc_parse/src/lexer/unicode_chars.rs+1-1
......@@ -351,7 +351,7 @@ pub(super) fn check_for_substitution(
351351
352352 let Some((_, ascii_name, token)) = ASCII_ARRAY.iter().find(|&&(s, _, _)| s == ascii_str) else {
353353 let msg = format!("substitution character not found for '{ch}'");
354 reader.psess.dcx.span_bug(span, msg);
354 reader.dcx().span_bug(span, msg);
355355 };
356356
357357 // special help suggestion for "directed" double quotes
compiler/rustc_parse/src/lib.rs+3-3
......@@ -73,7 +73,7 @@ pub fn new_parser_from_file<'a>(
7373) -> Result<Parser<'a>, Vec<Diag<'a>>> {
7474 let source_file = psess.source_map().load_file(path).unwrap_or_else(|e| {
7575 let msg = format!("couldn't read {}: {}", path.display(), e);
76 let mut err = psess.dcx.struct_fatal(msg);
76 let mut err = psess.dcx().struct_fatal(msg);
7777 if let Some(sp) = sp {
7878 err.span(sp);
7979 }
......@@ -115,7 +115,7 @@ fn source_file_to_stream<'psess>(
115115 override_span: Option<Span>,
116116) -> Result<TokenStream, Vec<Diag<'psess>>> {
117117 let src = source_file.src.as_ref().unwrap_or_else(|| {
118 psess.dcx.bug(format!(
118 psess.dcx().bug(format!(
119119 "cannot lex `source_file` without source: {}",
120120 psess.source_map().filename_for_diagnostics(&source_file.name)
121121 ));
......@@ -179,7 +179,7 @@ pub fn parse_cfg_attr(
179179 }
180180 }
181181 _ => {
182 psess.dcx.emit_err(errors::MalformedCfgAttr {
182 psess.dcx().emit_err(errors::MalformedCfgAttr {
183183 span: attr.span,
184184 sugg: CFG_ATTR_GRAMMAR_HELP,
185185 });
compiler/rustc_parse/src/parser/attr_wrapper.rs+1-1
......@@ -41,7 +41,7 @@ impl AttrWrapper {
4141 }
4242
4343 pub(crate) fn take_for_recovery(self, psess: &ParseSess) -> AttrVec {
44 psess.dcx.span_delayed_bug(
44 psess.dcx().span_delayed_bug(
4545 self.attrs.get(0).map(|attr| attr.span).unwrap_or(DUMMY_SP),
4646 "AttrVec is taken for recovery but no error is produced",
4747 );
compiler/rustc_parse/src/parser/diagnostics.rs+5-5
......@@ -34,7 +34,7 @@ use rustc_ast::{
3434use rustc_ast_pretty::pprust;
3535use rustc_data_structures::fx::FxHashSet;
3636use rustc_errors::{
37 pluralize, Applicability, Diag, DiagCtxt, ErrorGuaranteed, FatalError, PErr, PResult,
37 pluralize, Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, PErr, PResult,
3838 Subdiagnostic,
3939};
4040use rustc_session::errors::ExprParenthesesNeeded;
......@@ -240,8 +240,8 @@ impl<'a> DerefMut for SnapshotParser<'a> {
240240}
241241
242242impl<'a> Parser<'a> {
243 pub fn dcx(&self) -> &'a DiagCtxt {
244 &self.psess.dcx
243 pub fn dcx(&self) -> DiagCtxtHandle<'a> {
244 self.psess.dcx()
245245 }
246246
247247 /// Replace `self` with `snapshot.parser`.
......@@ -666,7 +666,7 @@ impl<'a> Parser<'a> {
666666 {
667667 err.note("you may be trying to write a c-string literal");
668668 err.note("c-string literals require Rust 2021 or later");
669 err.subdiagnostic(self.dcx(), HelpUseLatestEdition::new());
669 err.subdiagnostic(HelpUseLatestEdition::new());
670670 }
671671
672672 // `pub` may be used for an item or `pub(crate)`
......@@ -2357,7 +2357,7 @@ impl<'a> Parser<'a> {
23572357 let mut err = self.dcx().struct_span_err(span, msg);
23582358 let sp = self.psess.source_map().start_point(self.token.span);
23592359 if let Some(sp) = self.psess.ambiguous_block_expr_parse.borrow().get(&sp) {
2360 err.subdiagnostic(self.dcx(), ExprParenthesesNeeded::surrounding(*sp));
2360 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
23612361 }
23622362 err.span_label(span, "expected expression");
23632363
compiler/rustc_parse/src/parser/expr.rs+1-1
......@@ -1461,7 +1461,7 @@ impl<'a> Parser<'a> {
14611461 // If the input is something like `if a { 1 } else { 2 } | if a { 3 } else { 4 }`
14621462 // then suggest parens around the lhs.
14631463 if let Some(sp) = this.psess.ambiguous_block_expr_parse.borrow().get(&lo) {
1464 err.subdiagnostic(this.dcx(), ExprParenthesesNeeded::surrounding(*sp));
1464 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
14651465 }
14661466 err
14671467 })
compiler/rustc_parse/src/parser/item.rs+5-8
......@@ -1966,7 +1966,7 @@ impl<'a> Parser<'a> {
19661966 if self.token.kind == token::Not {
19671967 if let Err(mut err) = self.unexpected() {
19681968 // Encounter the macro invocation
1969 err.subdiagnostic(self.dcx(), MacroExpandsToAdtField { adt_ty });
1969 err.subdiagnostic(MacroExpandsToAdtField { adt_ty });
19701970 return Err(err);
19711971 }
19721972 }
......@@ -2382,13 +2382,10 @@ impl<'a> Parser<'a> {
23822382 .into_iter()
23832383 .any(|s| self.prev_token.is_ident_named(s));
23842384
2385 err.subdiagnostic(
2386 self.dcx(),
2387 errors::FnTraitMissingParen {
2388 span: self.prev_token.span,
2389 machine_applicable,
2390 },
2391 );
2385 err.subdiagnostic(errors::FnTraitMissingParen {
2386 span: self.prev_token.span,
2387 machine_applicable,
2388 });
23922389 }
23932390 return Err(err);
23942391 }
compiler/rustc_parse/src/parser/mod.rs+1-1
......@@ -1596,7 +1596,7 @@ pub(crate) fn make_unclosed_delims_error(
15961596 if let Some(sp) = unmatched.unclosed_span {
15971597 spans.push(sp);
15981598 };
1599 let err = psess.dcx.create_err(MismatchedClosingDelimiter {
1599 let err = psess.dcx().create_err(MismatchedClosingDelimiter {
16001600 spans,
16011601 delimiter: pprust::token_kind_to_string(&token::CloseDelim(found_delim)).to_string(),
16021602 unmatched: unmatched.found_span,
compiler/rustc_parse/src/parser/pat.rs+1-1
......@@ -851,7 +851,7 @@ impl<'a> Parser<'a> {
851851
852852 let sp = self.psess.source_map().start_point(self.token.span);
853853 if let Some(sp) = self.psess.ambiguous_block_expr_parse.borrow().get(&sp) {
854 err.subdiagnostic(self.dcx(), ExprParenthesesNeeded::surrounding(*sp));
854 err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
855855 }
856856
857857 Err(err)
compiler/rustc_parse/src/parser/tests.rs+3-3
......@@ -61,7 +61,7 @@ where
6161{
6262 let mut p = string_to_parser(&psess, s);
6363 let x = f(&mut p).unwrap();
64 p.psess.dcx.abort_if_errors();
64 p.dcx().abort_if_errors();
6565 x
6666}
6767
......@@ -193,7 +193,7 @@ impl<T: Write> Write for Shared<T> {
193193#[allow(rustc::untranslatable_diagnostic)] // no translation needed for tests
194194fn test_harness(file_text: &str, span_labels: Vec<SpanLabel>, expected_output: &str) {
195195 create_default_session_globals_then(|| {
196 let (handler, source_map, output) = create_test_handler();
196 let (dcx, source_map, output) = create_test_handler();
197197 source_map.new_source_file(Path::new("test.rs").to_owned().into(), file_text.to_owned());
198198
199199 let primary_span = make_span(&file_text, &span_labels[0].start, &span_labels[0].end);
......@@ -205,7 +205,7 @@ fn test_harness(file_text: &str, span_labels: Vec<SpanLabel>, expected_output: &
205205 println!("text: {:?}", source_map.span_to_snippet(span));
206206 }
207207
208 handler.span_err(msp, "foo");
208 dcx.handle().span_err(msp, "foo");
209209
210210 assert!(
211211 expected_output.chars().next() == Some('\n'),
compiler/rustc_parse/src/validate_attr.rs+5-5
......@@ -65,7 +65,7 @@ pub fn parse_meta<'a>(psess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Met
6565 let res = match res {
6666 Ok(lit) => {
6767 if token_lit.suffix.is_some() {
68 let mut err = psess.dcx.struct_span_err(
68 let mut err = psess.dcx().struct_span_err(
6969 expr.span,
7070 "suffixed literals are not allowed in attributes",
7171 );
......@@ -98,7 +98,7 @@ pub fn parse_meta<'a>(psess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Met
9898 // the error because an earlier error will have already
9999 // been reported.
100100 let msg = "attribute value must be a literal";
101 let mut err = psess.dcx.struct_span_err(expr.span, msg);
101 let mut err = psess.dcx().struct_span_err(expr.span, msg);
102102 if let ast::ExprKind::Err(_) = expr.kind {
103103 err.downgrade_to_delayed_bug();
104104 }
......@@ -114,7 +114,7 @@ fn check_meta_bad_delim(psess: &ParseSess, span: DelimSpan, delim: Delimiter) {
114114 if let Delimiter::Parenthesis = delim {
115115 return;
116116 }
117 psess.dcx.emit_err(errors::MetaBadDelim {
117 psess.dcx().emit_err(errors::MetaBadDelim {
118118 span: span.entire(),
119119 sugg: errors::MetaBadDelimSugg { open: span.open, close: span.close },
120120 });
......@@ -124,7 +124,7 @@ pub(super) fn check_cfg_attr_bad_delim(psess: &ParseSess, span: DelimSpan, delim
124124 if let Delimiter::Parenthesis = delim {
125125 return;
126126 }
127 psess.dcx.emit_err(errors::CfgAttrBadDelim {
127 psess.dcx().emit_err(errors::CfgAttrBadDelim {
128128 span: span.entire(),
129129 sugg: errors::MetaBadDelimSugg { open: span.open, close: span.close },
130130 });
......@@ -191,7 +191,7 @@ fn emit_malformed_attribute(
191191 } else {
192192 suggestions.sort();
193193 psess
194 .dcx
194 .dcx()
195195 .struct_span_err(span, error_msg)
196196 .with_span_suggestions(
197197 span,
compiler/rustc_passes/src/check_attr.rs+3-3
......@@ -8,8 +8,8 @@ use crate::{errors, fluent_generated as fluent};
88use rustc_ast::{ast, AttrKind, AttrStyle, Attribute, LitKind};
99use rustc_ast::{MetaItemKind, MetaItemLit, NestedMetaItem};
1010use rustc_data_structures::fx::FxHashMap;
11use rustc_errors::StashKey;
12use rustc_errors::{Applicability, DiagCtxt, IntoDiagArg, MultiSpan};
11use rustc_errors::{Applicability, IntoDiagArg, MultiSpan};
12use rustc_errors::{DiagCtxtHandle, StashKey};
1313use rustc_feature::{
1414 is_unsafe_attr, AttributeDuplicates, AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP,
1515};
......@@ -99,7 +99,7 @@ struct CheckAttrVisitor<'tcx> {
9999}
100100
101101impl<'tcx> CheckAttrVisitor<'tcx> {
102 fn dcx(&self) -> &'tcx DiagCtxt {
102 fn dcx(&self) -> DiagCtxtHandle<'tcx> {
103103 self.tcx.dcx()
104104 }
105105
compiler/rustc_passes/src/errors.rs+7-7
......@@ -6,8 +6,8 @@ use std::{
66use crate::fluent_generated as fluent;
77use rustc_ast::{ast, Label};
88use rustc_errors::{
9 codes::*, Applicability, Diag, DiagCtxt, DiagSymbolList, Diagnostic, EmissionGuarantee, Level,
10 MultiSpan, SubdiagMessageOp, Subdiagnostic,
9 codes::*, Applicability, Diag, DiagCtxtHandle, DiagSymbolList, Diagnostic, EmissionGuarantee,
10 Level, MultiSpan, SubdiagMessageOp, Subdiagnostic,
1111};
1212use rustc_hir::{self as hir, ExprKind, Target};
1313use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
......@@ -880,7 +880,7 @@ pub struct ItemFollowingInnerAttr {
880880
881881impl<G: EmissionGuarantee> Diagnostic<'_, G> for InvalidAttrAtCrateLevel {
882882 #[track_caller]
883 fn into_diag(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
883 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
884884 let mut diag = Diag::new(dcx, level, fluent::passes_invalid_attr_at_crate_level);
885885 diag.span(self.span);
886886 diag.arg("name", self.name);
......@@ -1030,7 +1030,7 @@ pub struct BreakNonLoop<'a> {
10301030
10311031impl<'a, G: EmissionGuarantee> Diagnostic<'_, G> for BreakNonLoop<'a> {
10321032 #[track_caller]
1033 fn into_diag(self, dcx: &DiagCtxt, level: Level) -> Diag<'_, G> {
1033 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
10341034 let mut diag = Diag::new(dcx, level, fluent::passes_break_non_loop);
10351035 diag.span(self.span);
10361036 diag.code(E0571);
......@@ -1176,7 +1176,7 @@ pub struct NakedFunctionsAsmBlock {
11761176
11771177impl<G: EmissionGuarantee> Diagnostic<'_, G> for NakedFunctionsAsmBlock {
11781178 #[track_caller]
1179 fn into_diag(self, dcx: &DiagCtxt, level: Level) -> Diag<'_, G> {
1179 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
11801180 let mut diag = Diag::new(dcx, level, fluent::passes_naked_functions_asm_block);
11811181 diag.span(self.span);
11821182 diag.code(E0787);
......@@ -1264,7 +1264,7 @@ pub struct NoMainErr {
12641264
12651265impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for NoMainErr {
12661266 #[track_caller]
1267 fn into_diag(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
1267 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
12681268 let mut diag = Diag::new(dcx, level, fluent::passes_no_main_function);
12691269 diag.span(DUMMY_SP);
12701270 diag.code(E0601);
......@@ -1322,7 +1322,7 @@ pub struct DuplicateLangItem {
13221322
13231323impl<G: EmissionGuarantee> Diagnostic<'_, G> for DuplicateLangItem {
13241324 #[track_caller]
1325 fn into_diag(self, dcx: &DiagCtxt, level: Level) -> Diag<'_, G> {
1325 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
13261326 let mut diag = Diag::new(
13271327 dcx,
13281328 level,
compiler/rustc_query_system/src/query/job.rs+2-2
......@@ -4,7 +4,7 @@ use crate::query::plumbing::CycleError;
44use crate::query::DepKind;
55use crate::query::{QueryContext, QueryStackFrame};
66use rustc_data_structures::fx::FxHashMap;
7use rustc_errors::{Diag, DiagCtxt};
7use rustc_errors::{Diag, DiagCtxtHandle};
88use rustc_hir::def::DefKind;
99use rustc_session::Session;
1010use rustc_span::Span;
......@@ -600,7 +600,7 @@ pub fn report_cycle<'a>(
600600pub fn print_query_stack<Qcx: QueryContext>(
601601 qcx: Qcx,
602602 mut current_query: Option<QueryJobId>,
603 dcx: &DiagCtxt,
603 dcx: DiagCtxtHandle<'_>,
604604 num_frames: Option<usize>,
605605 mut file: Option<std::fs::File>,
606606) -> usize {
compiler/rustc_resolve/src/diagnostics.rs+33-43
......@@ -6,7 +6,7 @@ use rustc_ast::{MetaItemKind, NestedMetaItem};
66use rustc_ast_pretty::pprust;
77use rustc_data_structures::fx::FxHashSet;
88use rustc_errors::{
9 codes::*, report_ambiguity_error, struct_span_code_err, Applicability, Diag, DiagCtxt,
9 codes::*, report_ambiguity_error, struct_span_code_err, Applicability, Diag, DiagCtxtHandle,
1010 ErrorGuaranteed, MultiSpan, SuggestionStyle,
1111};
1212use rustc_feature::BUILTIN_ATTRIBUTES;
......@@ -120,7 +120,7 @@ fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span {
120120}
121121
122122impl<'a, 'tcx> Resolver<'a, 'tcx> {
123 pub(crate) fn dcx(&self) -> &'tcx DiagCtxt {
123 pub(crate) fn dcx(&self) -> DiagCtxtHandle<'tcx> {
124124 self.tcx.dcx()
125125 }
126126
......@@ -334,12 +334,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
334334 Some((import, _, true)) if should_remove_import && !import.is_glob() => {
335335 // Simple case - remove the entire import. Due to the above match arm, this can
336336 // only be a single use so just remove it entirely.
337 err.subdiagnostic(
338 self.tcx.dcx(),
339 errors::ToolOnlyRemoveUnnecessaryImport {
340 span: import.use_span_with_attributes,
341 },
342 );
337 err.subdiagnostic(errors::ToolOnlyRemoveUnnecessaryImport {
338 span: import.use_span_with_attributes,
339 });
343340 }
344341 Some((import, span, _)) => {
345342 self.add_suggestion_for_rename_of_use(&mut err, name, import, span);
......@@ -405,12 +402,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
405402 }
406403
407404 if let Some(suggestion) = suggestion {
408 err.subdiagnostic(
409 self.dcx(),
410 ChangeImportBindingSuggestion { span: binding_span, suggestion },
411 );
405 err.subdiagnostic(ChangeImportBindingSuggestion { span: binding_span, suggestion });
412406 } else {
413 err.subdiagnostic(self.dcx(), ChangeImportBinding { span: binding_span });
407 err.subdiagnostic(ChangeImportBinding { span: binding_span });
414408 }
415409 }
416410
......@@ -458,20 +452,19 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
458452 // previous imports.
459453 if found_closing_brace {
460454 if let Some(span) = extend_span_to_previous_binding(self.tcx.sess, span) {
461 err.subdiagnostic(self.dcx(), errors::ToolOnlyRemoveUnnecessaryImport { span });
455 err.subdiagnostic(errors::ToolOnlyRemoveUnnecessaryImport { span });
462456 } else {
463457 // Remove the entire line if we cannot extend the span back, this indicates an
464458 // `issue_52891::{self}` case.
465 err.subdiagnostic(
466 self.dcx(),
467 errors::RemoveUnnecessaryImport { span: import.use_span_with_attributes },
468 );
459 err.subdiagnostic(errors::RemoveUnnecessaryImport {
460 span: import.use_span_with_attributes,
461 });
469462 }
470463
471464 return;
472465 }
473466
474 err.subdiagnostic(self.dcx(), errors::RemoveUnnecessaryImport { span });
467 err.subdiagnostic(errors::RemoveUnnecessaryImport { span });
475468 }
476469
477470 pub(crate) fn lint_if_path_starts_with_module(
......@@ -682,10 +675,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
682675 .dcx()
683676 .create_err(errors::VariableIsNotBoundInAllPatterns { multispan: msp, name });
684677 for sp in target_sp {
685 err.subdiagnostic(self.dcx(), errors::PatternDoesntBindName { span: sp, name });
678 err.subdiagnostic(errors::PatternDoesntBindName { span: sp, name });
686679 }
687680 for sp in origin_sp {
688 err.subdiagnostic(self.dcx(), errors::VariableNotInAllPatterns { span: sp });
681 err.subdiagnostic(errors::VariableNotInAllPatterns { span: sp });
689682 }
690683 if could_be_path {
691684 let import_suggestions = self.lookup_import_candidates(
......@@ -1446,12 +1439,12 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
14461439 );
14471440
14481441 if macro_kind == MacroKind::Bang && ident.name == sym::macro_rules {
1449 err.subdiagnostic(self.dcx(), MaybeMissingMacroRulesName { span: ident.span });
1442 err.subdiagnostic(MaybeMissingMacroRulesName { span: ident.span });
14501443 return;
14511444 }
14521445
14531446 if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
1454 err.subdiagnostic(self.dcx(), ExplicitUnsafeTraits { span: ident.span, ident });
1447 err.subdiagnostic(ExplicitUnsafeTraits { span: ident.span, ident });
14551448 return;
14561449 }
14571450
......@@ -1467,14 +1460,14 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
14671460 let scope = self.local_macro_def_scopes[&def_id];
14681461 let parent_nearest = parent_scope.module.nearest_parent_mod();
14691462 if Some(parent_nearest) == scope.opt_def_id() {
1470 err.subdiagnostic(self.dcx(), MacroDefinedLater { span: unused_ident.span });
1471 err.subdiagnostic(self.dcx(), MacroSuggMovePosition { span: ident.span, ident });
1463 err.subdiagnostic(MacroDefinedLater { span: unused_ident.span });
1464 err.subdiagnostic(MacroSuggMovePosition { span: ident.span, ident });
14721465 return;
14731466 }
14741467 }
14751468
14761469 if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
1477 err.subdiagnostic(self.dcx(), AddedMacroUse);
1470 err.subdiagnostic(AddedMacroUse);
14781471 return;
14791472 }
14801473
......@@ -1484,13 +1477,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
14841477 let span = self.def_span(def_id);
14851478 let source_map = self.tcx.sess.source_map();
14861479 let head_span = source_map.guess_head_span(span);
1487 err.subdiagnostic(
1488 self.dcx(),
1489 ConsiderAddingADerive {
1490 span: head_span.shrink_to_lo(),
1491 suggestion: "#[derive(Default)]\n".to_string(),
1492 },
1493 );
1480 err.subdiagnostic(ConsiderAddingADerive {
1481 span: head_span.shrink_to_lo(),
1482 suggestion: "#[derive(Default)]\n".to_string(),
1483 });
14941484 }
14951485 for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
14961486 if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
......@@ -1533,7 +1523,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
15331523 imported_ident: ident,
15341524 imported_ident_desc: &desc,
15351525 };
1536 err.subdiagnostic(self.tcx.dcx(), note);
1526 err.subdiagnostic(note);
15371527 // Silence the 'unused import' warning we might get,
15381528 // since this diagnostic already covers that import.
15391529 self.record_use(ident, binding, Used::Other);
......@@ -1544,7 +1534,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
15441534 imported_ident: ident,
15451535 imported_ident_desc: &desc,
15461536 };
1547 err.subdiagnostic(self.tcx.dcx(), note);
1537 err.subdiagnostic(note);
15481538 return;
15491539 }
15501540 }
......@@ -1599,7 +1589,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
15991589 }
16001590 };
16011591 did_label_def_span = true;
1602 err.subdiagnostic(self.tcx.dcx(), label);
1592 err.subdiagnostic(label);
16031593 }
16041594
16051595 let (span, msg, sugg) = if let SuggestionTarget::SimilarlyNamed = suggestion.target
......@@ -1790,7 +1780,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
17901780 outer_ident_descr: this_res.descr(),
17911781 outer_ident,
17921782 };
1793 err.subdiagnostic(self.tcx.dcx(), label);
1783 err.subdiagnostic(label);
17941784 }
17951785 }
17961786
......@@ -1805,14 +1795,14 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
18051795 non_exhaustive = Some(attr.span);
18061796 } else if let Some(span) = ctor_fields_span {
18071797 let label = errors::ConstructorPrivateIfAnyFieldPrivate { span };
1808 err.subdiagnostic(self.tcx.dcx(), label);
1798 err.subdiagnostic(label);
18091799 if let Res::Def(_, d) = res
18101800 && let Some(fields) = self.field_visibility_spans.get(&d)
18111801 {
18121802 let spans = fields.iter().map(|span| *span).collect();
18131803 let sugg =
18141804 errors::ConsiderMakingTheFieldPublic { spans, number_of_fields: fields.len() };
1815 err.subdiagnostic(self.tcx.dcx(), sugg);
1805 err.subdiagnostic(sugg);
18161806 }
18171807 }
18181808
......@@ -1921,7 +1911,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
19211911 first,
19221912 dots: next_binding.is_some(),
19231913 };
1924 err.subdiagnostic(self.tcx.dcx(), note);
1914 err.subdiagnostic(note);
19251915 }
19261916 // We prioritize shorter paths, non-core imports and direct imports over the alternatives.
19271917 sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0] == "core", *reexport));
......@@ -1940,7 +1930,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
19401930 } else {
19411931 errors::ImportIdent::Directly { span: dedup_span, ident, path }
19421932 };
1943 err.subdiagnostic(self.tcx.dcx(), sugg);
1933 err.subdiagnostic(sugg);
19441934 break;
19451935 }
19461936
......@@ -2521,14 +2511,14 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
25212511 }
25222512
25232513 let note = errors::FoundItemConfigureOut { span: name.span };
2524 err.subdiagnostic(self.tcx.dcx(), note);
2514 err.subdiagnostic(note);
25252515
25262516 if let MetaItemKind::List(nested) = &cfg.kind
25272517 && let NestedMetaItem::MetaItem(meta_item) = &nested[0]
25282518 && let MetaItemKind::NameValue(feature_name) = &meta_item.kind
25292519 {
25302520 let note = errors::ItemWasBehindFeature { feature: feature_name.symbol };
2531 err.subdiagnostic(self.tcx.dcx(), note);
2521 err.subdiagnostic(note);
25322522 }
25332523 }
25342524 }
compiler/rustc_resolve/src/imports.rs+2-2
......@@ -1294,12 +1294,12 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
12941294 // exclude decl_macro
12951295 if self.get_macro_by_def_id(def_id).macro_rules =>
12961296 {
1297 err.subdiagnostic(self.dcx(), ConsiderAddingMacroExport {
1297 err.subdiagnostic( ConsiderAddingMacroExport {
12981298 span: binding.span,
12991299 });
13001300 }
13011301 _ => {
1302 err.subdiagnostic(self.dcx(), ConsiderMarkingAsPub {
1302 err.subdiagnostic( ConsiderMarkingAsPub {
13031303 span: import.span,
13041304 ident,
13051305 });
compiler/rustc_resolve/src/late/diagnostics.rs+9-15
......@@ -1109,14 +1109,11 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
11091109 Side::Start => (segment.ident.span.between(range.span), " @ ".into()),
11101110 Side::End => (range.span.to(segment.ident.span), format!("{} @ ..", segment.ident)),
11111111 };
1112 err.subdiagnostic(
1113 self.r.dcx(),
1114 errors::UnexpectedResUseAtOpInSlicePatWithRangeSugg {
1115 span,
1116 ident: segment.ident,
1117 snippet,
1118 },
1119 );
1112 err.subdiagnostic(errors::UnexpectedResUseAtOpInSlicePatWithRangeSugg {
1113 span,
1114 ident: segment.ident,
1115 snippet,
1116 });
11201117 }
11211118
11221119 enum Side {
......@@ -1208,13 +1205,10 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
12081205 });
12091206
12101207 if let Some(param) = param {
1211 err.subdiagnostic(
1212 self.r.dcx(),
1213 errors::UnexpectedResChangeTyToConstParamSugg {
1214 span: param.shrink_to_lo(),
1215 applicability,
1216 },
1217 );
1208 err.subdiagnostic(errors::UnexpectedResChangeTyToConstParamSugg {
1209 span: param.shrink_to_lo(),
1210 applicability,
1211 });
12181212 }
12191213 }
12201214
compiler/rustc_session/src/errors.rs+4-4
......@@ -3,8 +3,8 @@ use std::num::NonZero;
33use rustc_ast::token;
44use rustc_ast::util::literal::LitError;
55use rustc_errors::{
6 codes::*, Diag, DiagCtxt, DiagMessage, Diagnostic, EmissionGuarantee, ErrorGuaranteed, Level,
7 MultiSpan,
6 codes::*, Diag, DiagCtxtHandle, DiagMessage, Diagnostic, EmissionGuarantee, ErrorGuaranteed,
7 Level, MultiSpan,
88};
99use rustc_macros::{Diagnostic, Subdiagnostic};
1010use rustc_span::{Span, Symbol};
......@@ -19,7 +19,7 @@ pub(crate) struct FeatureGateError {
1919
2020impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for FeatureGateError {
2121 #[track_caller]
22 fn into_diag(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
22 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
2323 Diag::new(dcx, level, self.explain).with_span(self.span).with_code(E0658)
2424 }
2525}
......@@ -401,7 +401,7 @@ pub fn report_lit_error(
401401 valid.then(|| format!("0{}{}", base_char.to_ascii_lowercase(), &suffix[1..]))
402402 }
403403
404 let dcx = &psess.dcx;
404 let dcx = psess.dcx();
405405 match err {
406406 LitError::InvalidSuffix(suffix) => {
407407 dcx.emit_err(InvalidLiteralSuffix { span, kind: lit.kind.descr(), suffix })
compiler/rustc_session/src/parse.rs+16-12
......@@ -15,8 +15,8 @@ use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};
1515use rustc_data_structures::sync::{AppendOnlyVec, Lock, Lrc};
1616use rustc_errors::emitter::{stderr_destination, HumanEmitter, SilentEmitter};
1717use rustc_errors::{
18 fallback_fluent_bundle, ColorConfig, Diag, DiagCtxt, DiagMessage, EmissionGuarantee, MultiSpan,
19 StashKey,
18 fallback_fluent_bundle, ColorConfig, Diag, DiagCtxt, DiagCtxtHandle, DiagMessage,
19 EmissionGuarantee, MultiSpan, StashKey,
2020};
2121use rustc_feature::{find_feature_issue, GateIssue, UnstableFeatures};
2222use rustc_span::edition::Edition;
......@@ -106,12 +106,12 @@ pub fn feature_err_issue(
106106
107107 // Cancel an earlier warning for this same error, if it exists.
108108 if let Some(span) = span.primary_span() {
109 if let Some(err) = sess.psess.dcx.steal_non_err(span, StashKey::EarlySyntaxWarning) {
109 if let Some(err) = sess.dcx().steal_non_err(span, StashKey::EarlySyntaxWarning) {
110110 err.cancel()
111111 }
112112 }
113113
114 let mut err = sess.psess.dcx.create_err(FeatureGateError { span, explain: explain.into() });
114 let mut err = sess.dcx().create_err(FeatureGateError { span, explain: explain.into() });
115115 add_feature_diagnostics_for_issue(&mut err, sess, feature, issue, false, None);
116116 err
117117}
......@@ -140,7 +140,7 @@ pub fn feature_warn_issue(
140140 issue: GateIssue,
141141 explain: &'static str,
142142) {
143 let mut err = sess.psess.dcx.struct_span_warn(span, explain);
143 let mut err = sess.dcx().struct_span_warn(span, explain);
144144 add_feature_diagnostics_for_issue(&mut err, sess, feature, issue, false, None);
145145
146146 // Decorate this as a future-incompatibility lint as in rustc_middle::lint::lint_level
......@@ -178,30 +178,30 @@ pub fn add_feature_diagnostics_for_issue<G: EmissionGuarantee>(
178178 inject_span: Option<Span>,
179179) {
180180 if let Some(n) = find_feature_issue(feature, issue) {
181 err.subdiagnostic(sess.dcx(), FeatureDiagnosticForIssue { n });
181 err.subdiagnostic(FeatureDiagnosticForIssue { n });
182182 }
183183
184184 // #23973: do not suggest `#![feature(...)]` if we are in beta/stable
185185 if sess.psess.unstable_features.is_nightly_build() {
186186 if feature_from_cli {
187 err.subdiagnostic(sess.dcx(), CliFeatureDiagnosticHelp { feature });
187 err.subdiagnostic(CliFeatureDiagnosticHelp { feature });
188188 } else if let Some(span) = inject_span {
189 err.subdiagnostic(sess.dcx(), FeatureDiagnosticSuggestion { feature, span });
189 err.subdiagnostic(FeatureDiagnosticSuggestion { feature, span });
190190 } else {
191 err.subdiagnostic(sess.dcx(), FeatureDiagnosticHelp { feature });
191 err.subdiagnostic(FeatureDiagnosticHelp { feature });
192192 }
193193
194194 if sess.opts.unstable_opts.ui_testing {
195 err.subdiagnostic(sess.dcx(), SuggestUpgradeCompiler::ui_testing());
195 err.subdiagnostic(SuggestUpgradeCompiler::ui_testing());
196196 } else if let Some(suggestion) = SuggestUpgradeCompiler::new() {
197 err.subdiagnostic(sess.dcx(), suggestion);
197 err.subdiagnostic(suggestion);
198198 }
199199 }
200200}
201201
202202/// Info about a parsing session.
203203pub struct ParseSess {
204 pub dcx: DiagCtxt,
204 dcx: DiagCtxt,
205205 pub unstable_features: UnstableFeatures,
206206 pub config: Cfg,
207207 pub check_config: CheckCfg,
......@@ -326,4 +326,8 @@ impl ParseSess {
326326 // AppendOnlyVec, so we resort to this scheme.
327327 self.proc_macro_quoted_spans.iter_enumerated()
328328 }
329
330 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
331 self.dcx.handle()
332 }
329333}
compiler/rustc_session/src/session.rs+13-13
......@@ -22,8 +22,8 @@ use rustc_errors::emitter::{stderr_destination, DynEmitter, HumanEmitter, HumanR
2222use rustc_errors::json::JsonEmitter;
2323use rustc_errors::registry::Registry;
2424use rustc_errors::{
25 codes::*, fallback_fluent_bundle, Diag, DiagCtxt, DiagMessage, Diagnostic, ErrorGuaranteed,
26 FatalAbort, FluentBundle, LazyFallbackBundle, TerminalUrl,
25 codes::*, fallback_fluent_bundle, Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic,
26 ErrorGuaranteed, FatalAbort, FluentBundle, LazyFallbackBundle, TerminalUrl,
2727};
2828use rustc_macros::HashStable_Generic;
2929pub use rustc_span::def_id::StableCrateId;
......@@ -328,8 +328,8 @@ impl Session {
328328 }
329329
330330 #[inline]
331 pub fn dcx(&self) -> &DiagCtxt {
332 &self.psess.dcx
331 pub fn dcx(&self) -> DiagCtxtHandle<'_> {
332 self.psess.dcx()
333333 }
334334
335335 #[inline]
......@@ -1070,7 +1070,7 @@ pub fn build_session(
10701070 match profiler {
10711071 Ok(profiler) => Some(Arc::new(profiler)),
10721072 Err(e) => {
1073 dcx.emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
1073 dcx.handle().emit_warn(errors::FailedToCreateProfiler { err: e.to_string() });
10741074 None
10751075 }
10761076 }
......@@ -1371,7 +1371,7 @@ impl EarlyDiagCtxt {
13711371 /// format. Any errors prior to that will cause an abort and all stashed diagnostics of the
13721372 /// previous dcx will be emitted.
13731373 pub fn abort_if_error_and_set_error_format(&mut self, output: ErrorOutputType) {
1374 self.dcx.abort_if_errors();
1374 self.dcx.handle().abort_if_errors();
13751375
13761376 let emitter = mk_emitter(output);
13771377 self.dcx = DiagCtxt::new(emitter);
......@@ -1380,44 +1380,44 @@ impl EarlyDiagCtxt {
13801380 #[allow(rustc::untranslatable_diagnostic)]
13811381 #[allow(rustc::diagnostic_outside_of_impl)]
13821382 pub fn early_note(&self, msg: impl Into<DiagMessage>) {
1383 self.dcx.note(msg)
1383 self.dcx.handle().note(msg)
13841384 }
13851385
13861386 #[allow(rustc::untranslatable_diagnostic)]
13871387 #[allow(rustc::diagnostic_outside_of_impl)]
13881388 pub fn early_help(&self, msg: impl Into<DiagMessage>) {
1389 self.dcx.struct_help(msg).emit()
1389 self.dcx.handle().struct_help(msg).emit()
13901390 }
13911391
13921392 #[allow(rustc::untranslatable_diagnostic)]
13931393 #[allow(rustc::diagnostic_outside_of_impl)]
13941394 #[must_use = "ErrorGuaranteed must be returned from `run_compiler` in order to exit with a non-zero status code"]
13951395 pub fn early_err(&self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
1396 self.dcx.err(msg)
1396 self.dcx.handle().err(msg)
13971397 }
13981398
13991399 #[allow(rustc::untranslatable_diagnostic)]
14001400 #[allow(rustc::diagnostic_outside_of_impl)]
14011401 pub fn early_fatal(&self, msg: impl Into<DiagMessage>) -> ! {
1402 self.dcx.fatal(msg)
1402 self.dcx.handle().fatal(msg)
14031403 }
14041404
14051405 #[allow(rustc::untranslatable_diagnostic)]
14061406 #[allow(rustc::diagnostic_outside_of_impl)]
14071407 pub fn early_struct_fatal(&self, msg: impl Into<DiagMessage>) -> Diag<'_, FatalAbort> {
1408 self.dcx.struct_fatal(msg)
1408 self.dcx.handle().struct_fatal(msg)
14091409 }
14101410
14111411 #[allow(rustc::untranslatable_diagnostic)]
14121412 #[allow(rustc::diagnostic_outside_of_impl)]
14131413 pub fn early_warn(&self, msg: impl Into<DiagMessage>) {
1414 self.dcx.warn(msg)
1414 self.dcx.handle().warn(msg)
14151415 }
14161416
14171417 #[allow(rustc::untranslatable_diagnostic)]
14181418 #[allow(rustc::diagnostic_outside_of_impl)]
14191419 pub fn early_struct_warn(&self, msg: impl Into<DiagMessage>) -> Diag<'_, ()> {
1420 self.dcx.struct_warn(msg)
1420 self.dcx.handle().struct_warn(msg)
14211421 }
14221422}
14231423
compiler/rustc_symbol_mangling/src/errors.rs+2-2
......@@ -1,6 +1,6 @@
11//! Errors emitted by symbol_mangling.
22
3use rustc_errors::{Diag, DiagCtxt, Diagnostic, EmissionGuarantee, Level};
3use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level};
44use rustc_span::Span;
55use std::fmt;
66
......@@ -14,7 +14,7 @@ pub struct TestOutput {
1414// natural language, and (b) it's only used in tests. So we construct it
1515// manually and avoid the fluent machinery.
1616impl<G: EmissionGuarantee> Diagnostic<'_, G> for TestOutput {
17 fn into_diag(self, dcx: &'_ DiagCtxt, level: Level) -> Diag<'_, G> {
17 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
1818 let TestOutput { span, kind, content } = self;
1919
2020 #[allow(rustc::untranslatable_diagnostic)]
compiler/rustc_trait_selection/src/errors.rs+2-2
......@@ -1,6 +1,6 @@
11use crate::fluent_generated as fluent;
22use rustc_errors::{
3 codes::*, Applicability, Diag, DiagCtxt, Diagnostic, EmissionGuarantee, Level,
3 codes::*, Applicability, Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level,
44 SubdiagMessageOp, Subdiagnostic,
55};
66use rustc_macros::{Diagnostic, Subdiagnostic};
......@@ -59,7 +59,7 @@ pub struct NegativePositiveConflict<'tcx> {
5959
6060impl<G: EmissionGuarantee> Diagnostic<'_, G> for NegativePositiveConflict<'_> {
6161 #[track_caller]
62 fn into_diag(self, dcx: &DiagCtxt, level: Level) -> Diag<'_, G> {
62 fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> {
6363 let mut diag = Diag::new(dcx, level, fluent::trait_selection_negative_positive_conflict);
6464 diag.arg("trait_desc", self.trait_desc.print_only_trait_path().to_string());
6565 diag.arg("self_desc", self.self_ty.map_or_else(|| "none".to_string(), |ty| ty.to_string()));
compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs+2-5
......@@ -4705,14 +4705,11 @@ fn hint_missing_borrow<'tcx>(
47054705 }
47064706
47074707 if !to_borrow.is_empty() {
4708 err.subdiagnostic(infcx.dcx(), errors::AdjustSignatureBorrow::Borrow { to_borrow });
4708 err.subdiagnostic(errors::AdjustSignatureBorrow::Borrow { to_borrow });
47094709 }
47104710
47114711 if !remove_borrow.is_empty() {
4712 err.subdiagnostic(
4713 infcx.dcx(),
4714 errors::AdjustSignatureBorrow::RemoveBorrow { remove_borrow },
4715 );
4712 err.subdiagnostic(errors::AdjustSignatureBorrow::RemoveBorrow { remove_borrow });
47164713 }
47174714}
47184715
src/librustdoc/config.rs+9-7
......@@ -8,6 +8,7 @@ use std::path::PathBuf;
88use std::str::FromStr;
99
1010use rustc_data_structures::fx::FxHashMap;
11use rustc_errors::DiagCtxtHandle;
1112use rustc_session::config::{
1213 self, parse_crate_types_from_list, parse_externs, parse_target_triple, CrateType,
1314};
......@@ -383,9 +384,10 @@ impl Options {
383384 };
384385
385386 let dcx = new_dcx(error_format, None, diagnostic_width, &unstable_opts);
387 let dcx = dcx.handle();
386388
387389 // check for deprecated options
388 check_deprecated_options(matches, &dcx);
390 check_deprecated_options(matches, dcx);
389391
390392 if matches.opt_strs("passes") == ["list"] {
391393 println!("Available passes for running rustdoc:");
......@@ -458,7 +460,7 @@ impl Options {
458460 println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
459461 for theme_file in to_check.iter() {
460462 print!(" - Checking \"{theme_file}\"...");
461 let (success, differences) = theme::test_theme_against(theme_file, &paths, &dcx);
463 let (success, differences) = theme::test_theme_against(theme_file, &paths, dcx);
462464 if !differences.is_empty() || !success {
463465 println!(" FAILED");
464466 errors += 1;
......@@ -603,7 +605,7 @@ impl Options {
603605 .with_help("arguments to --theme must have a .css extension")
604606 .emit();
605607 }
606 let (success, ret) = theme::test_theme_against(&theme_file, &paths, &dcx);
608 let (success, ret) = theme::test_theme_against(&theme_file, &paths, dcx);
607609 if !success {
608610 dcx.fatal(format!("error loading theme file: \"{theme_s}\""));
609611 } else if !ret.is_empty() {
......@@ -630,7 +632,7 @@ impl Options {
630632 &matches.opt_strs("markdown-before-content"),
631633 &matches.opt_strs("markdown-after-content"),
632634 nightly_options::match_is_nightly_build(matches),
633 &dcx,
635 dcx,
634636 &mut id_map,
635637 edition,
636638 &None,
......@@ -741,9 +743,9 @@ impl Options {
741743 );
742744 }
743745
744 let scrape_examples_options = ScrapeExamplesOptions::new(matches, &dcx);
746 let scrape_examples_options = ScrapeExamplesOptions::new(matches, dcx);
745747 let with_examples = matches.opt_strs("with-examples");
746 let call_locations = crate::scrape_examples::load_call_locations(with_examples, &dcx);
748 let call_locations = crate::scrape_examples::load_call_locations(with_examples, dcx);
747749
748750 let unstable_features =
749751 rustc_feature::UnstableFeatures::from_environment(crate_name.as_deref());
......@@ -847,7 +849,7 @@ fn parse_remap_path_prefix(
847849}
848850
849851/// Prints deprecation warnings for deprecated options
850fn check_deprecated_options(matches: &getopts::Matches, dcx: &rustc_errors::DiagCtxt) {
852fn check_deprecated_options(matches: &getopts::Matches, dcx: DiagCtxtHandle<'_>) {
851853 let deprecated_flags = [];
852854
853855 for &flag in deprecated_flags.iter() {
src/librustdoc/core.rs+2-2
......@@ -3,7 +3,7 @@ use rustc_data_structures::sync::Lrc;
33use rustc_data_structures::unord::UnordSet;
44use rustc_errors::emitter::{stderr_destination, DynEmitter, HumanEmitter};
55use rustc_errors::json::JsonEmitter;
6use rustc_errors::{codes::*, ErrorGuaranteed, TerminalUrl};
6use rustc_errors::{codes::*, DiagCtxtHandle, ErrorGuaranteed, TerminalUrl};
77use rustc_feature::UnstableFeatures;
88use rustc_hir::def::Res;
99use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LocalDefId};
......@@ -379,7 +379,7 @@ pub(crate) fn run_global_ctxt(
379379 );
380380 }
381381
382 fn report_deprecated_attr(name: &str, dcx: &rustc_errors::DiagCtxt, sp: Span) {
382 fn report_deprecated_attr(name: &str, dcx: DiagCtxtHandle<'_>, sp: Span) {
383383 let mut msg =
384384 dcx.struct_span_warn(sp, format!("the `#![doc({name})]` attribute is deprecated"));
385385 msg.note(
src/librustdoc/doctest.rs+2-5
......@@ -7,7 +7,7 @@ pub(crate) use markdown::test as test_markdown;
77
88use rustc_ast as ast;
99use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10use rustc_errors::{ColorConfig, ErrorGuaranteed, FatalError};
10use rustc_errors::{ColorConfig, DiagCtxtHandle, ErrorGuaranteed, FatalError};
1111use rustc_hir::def_id::LOCAL_CRATE;
1212use rustc_hir::CRATE_HIR_ID;
1313use rustc_interface::interface;
......@@ -90,10 +90,7 @@ fn get_doctest_dir() -> io::Result<TempDir> {
9090 TempFileBuilder::new().prefix("rustdoctest").tempdir()
9191}
9292
93pub(crate) fn run(
94 dcx: &rustc_errors::DiagCtxt,
95 options: RustdocOptions,
96) -> Result<(), ErrorGuaranteed> {
93pub(crate) fn run(dcx: DiagCtxtHandle<'_>, options: RustdocOptions) -> Result<(), ErrorGuaranteed> {
9794 let invalid_codeblock_attributes_name = crate::lint::INVALID_CODEBLOCK_ATTRIBUTES.name;
9895
9996 // See core::create_config for what's going on here.
src/librustdoc/doctest/make.rs+1-1
......@@ -229,7 +229,7 @@ fn check_for_main_and_extern_crate(
229229 // dcx. Any errors in the tests will be reported when the test file is compiled,
230230 // Note that we still need to cancel the errors above otherwise `Diag` will panic on
231231 // drop.
232 psess.dcx.reset_err_count();
232 psess.dcx().reset_err_count();
233233
234234 (found_main, found_extern_crate, found_macro)
235235 })
src/librustdoc/externalfiles.rs+4-3
......@@ -1,4 +1,5 @@
11use crate::html::markdown::{ErrorCodes, HeadingOffset, IdMap, Markdown, Playground};
2use rustc_errors::DiagCtxtHandle;
23use rustc_span::edition::Edition;
34use std::fs;
45use std::path::Path;
......@@ -27,7 +28,7 @@ impl ExternalHtml {
2728 md_before_content: &[String],
2829 md_after_content: &[String],
2930 nightly_build: bool,
30 dcx: &rustc_errors::DiagCtxt,
31 dcx: DiagCtxtHandle<'_>,
3132 id_map: &mut IdMap,
3233 edition: Edition,
3334 playground: &Option<Playground>,
......@@ -75,7 +76,7 @@ pub(crate) enum LoadStringError {
7576
7677pub(crate) fn load_string<P: AsRef<Path>>(
7778 file_path: P,
78 dcx: &rustc_errors::DiagCtxt,
79 dcx: DiagCtxtHandle<'_>,
7980) -> Result<String, LoadStringError> {
8081 let file_path = file_path.as_ref();
8182 let contents = match fs::read(file_path) {
......@@ -98,7 +99,7 @@ pub(crate) fn load_string<P: AsRef<Path>>(
9899 }
99100}
100101
101fn load_external_files(names: &[String], dcx: &rustc_errors::DiagCtxt) -> Option<String> {
102fn load_external_files(names: &[String], dcx: DiagCtxtHandle<'_>) -> Option<String> {
102103 let mut out = String::new();
103104 for name in names {
104105 let Ok(s) = load_string(name, dcx) else { return None };
src/librustdoc/lib.rs+7-6
......@@ -77,7 +77,7 @@ use std::io::{self, IsTerminal};
7777use std::process;
7878use std::sync::{atomic::AtomicBool, Arc};
7979
80use rustc_errors::{ErrorGuaranteed, FatalError};
80use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, FatalError};
8181use rustc_interface::interface;
8282use rustc_middle::ty::TyCtxt;
8383use rustc_session::config::{make_crate_type_option, ErrorOutputType, RustcOptGroup};
......@@ -670,7 +670,7 @@ fn usage(argv0: &str) {
670670/// A result type used by several functions under `main()`.
671671type MainResult = Result<(), ErrorGuaranteed>;
672672
673pub(crate) fn wrap_return(dcx: &rustc_errors::DiagCtxt, res: Result<(), String>) -> MainResult {
673pub(crate) fn wrap_return(dcx: DiagCtxtHandle<'_>, res: Result<(), String>) -> MainResult {
674674 match res {
675675 Ok(()) => dcx.has_errors().map_or(Ok(()), Err),
676676 Err(err) => Err(dcx.err(err)),
......@@ -732,12 +732,13 @@ fn main_args(
732732 None => return Ok(()),
733733 };
734734
735 let diag =
735 let dcx =
736736 core::new_dcx(options.error_format, None, options.diagnostic_width, &options.unstable_opts);
737 let dcx = dcx.handle();
737738
738739 match (options.should_test, options.markdown_input()) {
739 (true, Some(_)) => return wrap_return(&diag, doctest::test_markdown(options)),
740 (true, None) => return doctest::run(&diag, options),
740 (true, Some(_)) => return wrap_return(dcx, doctest::test_markdown(options)),
741 (true, None) => return doctest::run(dcx, options),
741742 (false, Some(input)) => {
742743 let input = input.to_owned();
743744 let edition = options.edition;
......@@ -747,7 +748,7 @@ fn main_args(
747748 // requires session globals and a thread pool, so we use
748749 // `run_compiler`.
749750 return wrap_return(
750 &diag,
751 dcx,
751752 interface::run_compiler(config, |_compiler| {
752753 markdown::render(&input, render_options, edition)
753754 }),
src/librustdoc/scrape_examples.rs+3-2
......@@ -7,6 +7,7 @@ use crate::formats::renderer::FormatRenderer;
77use crate::html::render::Context;
88
99use rustc_data_structures::fx::FxHashMap;
10use rustc_errors::DiagCtxtHandle;
1011use rustc_hir::{
1112 self as hir,
1213 intravisit::{self, Visitor},
......@@ -38,7 +39,7 @@ pub(crate) struct ScrapeExamplesOptions {
3839}
3940
4041impl ScrapeExamplesOptions {
41 pub(crate) fn new(matches: &getopts::Matches, dcx: &rustc_errors::DiagCtxt) -> Option<Self> {
42 pub(crate) fn new(matches: &getopts::Matches, dcx: DiagCtxtHandle<'_>) -> Option<Self> {
4243 let output_path = matches.opt_str("scrape-examples-output-path");
4344 let target_crates = matches.opt_strs("scrape-examples-target-crate");
4445 let scrape_tests = matches.opt_present("scrape-tests");
......@@ -336,7 +337,7 @@ pub(crate) fn run(
336337// options.
337338pub(crate) fn load_call_locations(
338339 with_examples: Vec<String>,
339 dcx: &rustc_errors::DiagCtxt,
340 dcx: DiagCtxtHandle<'_>,
340341) -> AllCallLocations {
341342 let mut all_calls: AllCallLocations = FxHashMap::default();
342343 for path in with_examples {
src/librustdoc/theme.rs+2-2
......@@ -5,7 +5,7 @@ use std::iter::Peekable;
55use std::path::Path;
66use std::str::Chars;
77
8use rustc_errors::DiagCtxt;
8use rustc_errors::DiagCtxtHandle;
99
1010#[cfg(test)]
1111mod tests;
......@@ -236,7 +236,7 @@ pub(crate) fn get_differences(
236236pub(crate) fn test_theme_against<P: AsRef<Path>>(
237237 f: &P,
238238 origin: &FxHashMap<String, CssPath>,
239 dcx: &DiagCtxt,
239 dcx: DiagCtxtHandle<'_>,
240240) -> (bool, Vec<String>) {
241241 let against = match fs::read_to_string(f)
242242 .map_err(|e| e.to_string())
src/tools/clippy/src/driver.rs+2-2
......@@ -180,12 +180,12 @@ pub fn main() {
180180
181181 rustc_driver::init_rustc_env_logger(&early_dcx);
182182
183 let using_internal_features = rustc_driver::install_ice_hook(BUG_REPORT_URL, |handler| {
183 let using_internal_features = rustc_driver::install_ice_hook(BUG_REPORT_URL, |dcx| {
184184 // FIXME: this macro calls unwrap internally but is called in a panicking context! It's not
185185 // as simple as moving the call from the hook to main, because `install_ice_hook` doesn't
186186 // accept a generic closure.
187187 let version_info = rustc_tools_util::get_version_info!();
188 handler.note(format!("Clippy version: {version_info}"));
188 dcx.handle().note(format!("Clippy version: {version_info}"));
189189 });
190190
191191 exit(rustc_driver::catch_with_exit_code(move || {
src/tools/miri/src/diagnostics.rs+1-1
......@@ -566,7 +566,7 @@ pub fn report_msg<'tcx>(
566566 let is_local = machine.is_local(frame_info);
567567 // No span for non-local frames and the first frame (which is the error site).
568568 if is_local && idx > 0 {
569 err.subdiagnostic(err.dcx, frame_info.as_note(machine.tcx));
569 err.subdiagnostic(frame_info.as_note(machine.tcx));
570570 } else {
571571 let sm = sess.source_map();
572572 let span = sm.span_to_embeddable_string(frame_info.span);
src/tools/rustfmt/src/parse/macros/cfg_if.rs+1-1
......@@ -67,7 +67,7 @@ fn parse_cfg_if_inner<'a>(
6767 Ok(None) => continue,
6868 Err(err) => {
6969 err.cancel();
70 parser.psess.dcx.reset_err_count();
70 parser.psess.dcx().reset_err_count();
7171 return Err(
7272 "Expected item inside cfg_if block, but failed to parse it as an item",
7373 );
src/tools/rustfmt/src/parse/macros/lazy_static.rs+3-3
......@@ -16,8 +16,8 @@ pub(crate) fn parse_lazy_static(
1616 ($method:ident $(,)* $($arg:expr),* $(,)*) => {
1717 match parser.$method($($arg,)*) {
1818 Ok(val) => {
19 if parser.psess.dcx.has_errors().is_some() {
20 parser.psess.dcx.reset_err_count();
19 if parser.psess.dcx().has_errors().is_some() {
20 parser.psess.dcx().reset_err_count();
2121 return None;
2222 } else {
2323 val
......@@ -25,7 +25,7 @@ pub(crate) fn parse_lazy_static(
2525 }
2626 Err(err) => {
2727 err.cancel();
28 parser.psess.dcx.reset_err_count();
28 parser.psess.dcx().reset_err_count();
2929 return None;
3030 }
3131 }
src/tools/rustfmt/src/parse/macros/mod.rs+3-3
......@@ -29,8 +29,8 @@ fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
2929 if Parser::nonterminal_may_begin_with($nt_kind, &cloned_parser.token) {
3030 match $try_parse(&mut cloned_parser) {
3131 Ok(x) => {
32 if parser.psess.dcx.has_errors().is_some() {
33 parser.psess.dcx.reset_err_count();
32 if parser.psess.dcx().has_errors().is_some() {
33 parser.psess.dcx().reset_err_count();
3434 } else {
3535 // Parsing succeeded.
3636 *parser = cloned_parser;
......@@ -39,7 +39,7 @@ fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
3939 }
4040 Err(e) => {
4141 e.cancel();
42 parser.psess.dcx.reset_err_count();
42 parser.psess.dcx().reset_err_count();
4343 }
4444 }
4545 }
src/tools/rustfmt/src/parse/session.rs+5-3
......@@ -210,7 +210,9 @@ impl ParseSess {
210210 rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(),
211211 false,
212212 );
213 self.raw_psess.dcx.make_silent(fallback_bundle, None, false);
213 self.raw_psess
214 .dcx()
215 .make_silent(fallback_bundle, None, false);
214216 }
215217
216218 pub(crate) fn span_to_filename(&self, span: Span) -> FileName {
......@@ -286,11 +288,11 @@ impl ParseSess {
286288 }
287289
288290 pub(super) fn has_errors(&self) -> bool {
289 self.raw_psess.dcx.has_errors().is_some()
291 self.raw_psess.dcx().has_errors().is_some()
290292 }
291293
292294 pub(super) fn reset_errors(&self) {
293 self.raw_psess.dcx.reset_err_count();
295 self.raw_psess.dcx().reset_err_count();
294296 }
295297}
296298
tests/ui-fulldeps/internal-lints/diagnostics.rs+7-7
......@@ -14,8 +14,8 @@ extern crate rustc_session;
1414extern crate rustc_span;
1515
1616use rustc_errors::{
17 Diag, DiagCtxt, DiagInner, DiagMessage, Diagnostic, EmissionGuarantee, Level, LintDiagnostic,
18 SubdiagMessageOp, SubdiagMessage, Subdiagnostic,
17 Diag, DiagCtxtHandle, DiagInner, DiagMessage, Diagnostic, EmissionGuarantee, Level,
18 LintDiagnostic, SubdiagMessage, SubdiagMessageOp, Subdiagnostic,
1919};
2020use rustc_macros::{Diagnostic, Subdiagnostic};
2121use rustc_span::Span;
......@@ -39,7 +39,7 @@ struct Note {
3939pub struct UntranslatableInDiagnostic;
4040
4141impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for UntranslatableInDiagnostic {
42 fn into_diag(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
42 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
4343 Diag::new(dcx, level, "untranslatable diagnostic")
4444 //~^ ERROR diagnostics should be created using translatable messages
4545 }
......@@ -48,7 +48,7 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for UntranslatableInDiagnostic
4848pub struct TranslatableInDiagnostic;
4949
5050impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for TranslatableInDiagnostic {
51 fn into_diag(self, dcx: &'a DiagCtxt, level: Level) -> Diag<'a, G> {
51 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
5252 Diag::new(dcx, level, crate::fluent_generated::no_crate_example)
5353 }
5454}
......@@ -81,7 +81,7 @@ impl Subdiagnostic for TranslatableInAddtoDiag {
8181pub struct UntranslatableInLintDiagnostic;
8282
8383impl<'a> LintDiagnostic<'a, ()> for UntranslatableInLintDiagnostic {
84 fn decorate_lint<'b, >(self, diag: &'b mut Diag<'a, ()>) {
84 fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, ()>) {
8585 diag.note("untranslatable diagnostic");
8686 //~^ ERROR diagnostics should be created using translatable messages
8787 }
......@@ -95,7 +95,7 @@ impl<'a> LintDiagnostic<'a, ()> for TranslatableInLintDiagnostic {
9595 }
9696}
9797
98pub fn make_diagnostics<'a>(dcx: &'a DiagCtxt) {
98pub fn make_diagnostics<'a>(dcx: DiagCtxtHandle<'a>) {
9999 let _diag = dcx.struct_err(crate::fluent_generated::no_crate_example);
100100 //~^ ERROR diagnostics should only be created in `Diagnostic`/`Subdiagnostic`/`LintDiagnostic` impls
101101
......@@ -107,7 +107,7 @@ pub fn make_diagnostics<'a>(dcx: &'a DiagCtxt) {
107107// Check that `rustc_lint_diagnostics`-annotated functions aren't themselves linted for
108108// `diagnostic_outside_of_impl`.
109109#[rustc_lint_diagnostics]
110pub fn skipped_because_of_annotation<'a>(dcx: &'a DiagCtxt) {
110pub fn skipped_because_of_annotation<'a>(dcx: DiagCtxtHandle<'a>) {
111111 #[allow(rustc::untranslatable_diagnostic)]
112112 let _diag = dcx.struct_err("untranslatable diagnostic"); // okay!
113113}