1
Fork 0

Auto merge of #119146 - nnethercote:rm-DiagCtxt-api-duplication, r=compiler-errors

Remove `DiagCtxt` API duplication

`DiagCtxt` defines the internal API for creating and emitting diagnostics: methods like `struct_err`, `struct_span_warn`, `note`, `create_fatal`, `emit_bug`. There are over 50 methods.

Some of these methods are then duplicated across several other types: `Session`, `ParseSess`, `Parser`, `ExtCtxt`, and `MirBorrowckCtxt`. `Session` duplicates the most, though half the ones it does are unused. Each duplicated method just calls forward to the corresponding method in `DiagCtxt`. So this duplication exists to (in the best case) shorten chains like `ecx.tcx.sess.parse_sess.dcx.emit_err()` to `ecx.emit_err()`.

This API duplication is ugly and has been bugging me for a while. And it's inconsistent: there's no real logic about which methods are duplicated, and the use of `#[rustc_lint_diagnostic]` and `#[track_caller]` attributes vary across the duplicates.

This PR removes the duplicated API methods and makes all diagnostic creation and emission go through `DiagCtxt`. It also adds `dcx` getter methods to several types to shorten chains. This approach scales *much* better than API duplication; indeed, the PR adds `dcx()` to numerous types that didn't have API duplication: `TyCtxt`, `LoweringCtxt`, `ConstCx`, `FnCtxt`, `TypeErrCtxt`, `InferCtxt`, `CrateLoader`, `CheckAttrVisitor`, and `Resolver`. These result in a lot of changes from `foo.tcx.sess.emit_err()` to `foo.dcx().emit_err()`. (You could do this with more types, but it gets into diminishing returns territory for types that don't emit many diagnostics.)

After all these changes, some call sites are more verbose, some are less verbose, and many are the same. The total number of lines is reduced, mostly because of the removed API duplication. And consistency is increased, because calls to `emit_err` and friends are always preceded with `.dcx()` or `.dcx`.

r? `@compiler-errors`
This commit is contained in:
bors 2023-12-26 02:24:39 +00:00
commit 2271c26e4a
347 changed files with 2334 additions and 2696 deletions

View file

@ -32,7 +32,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
let asm_arch = let asm_arch =
if self.tcx.sess.opts.actually_rustdoc { None } else { self.tcx.sess.asm_arch }; if self.tcx.sess.opts.actually_rustdoc { None } else { self.tcx.sess.asm_arch };
if asm_arch.is_none() && !self.tcx.sess.opts.actually_rustdoc { if asm_arch.is_none() && !self.tcx.sess.opts.actually_rustdoc {
self.tcx.sess.emit_err(InlineAsmUnsupportedTarget { span: sp }); self.dcx().emit_err(InlineAsmUnsupportedTarget { span: sp });
} }
if let Some(asm_arch) = asm_arch { if let Some(asm_arch) = asm_arch {
// Inline assembly is currently only stable for these architectures. // Inline assembly is currently only stable for these architectures.
@ -60,7 +60,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
&& !matches!(asm_arch, Some(asm::InlineAsmArch::X86 | asm::InlineAsmArch::X86_64)) && !matches!(asm_arch, Some(asm::InlineAsmArch::X86 | asm::InlineAsmArch::X86_64))
&& !self.tcx.sess.opts.actually_rustdoc && !self.tcx.sess.opts.actually_rustdoc
{ {
self.tcx.sess.emit_err(AttSyntaxOnlyX86 { span: sp }); self.dcx().emit_err(AttSyntaxOnlyX86 { span: sp });
} }
if asm.options.contains(InlineAsmOptions::MAY_UNWIND) && !self.tcx.features().asm_unwind { if asm.options.contains(InlineAsmOptions::MAY_UNWIND) && !self.tcx.features().asm_unwind {
feature_err( feature_err(
@ -87,7 +87,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
!= source_map.span_to_snippet(*abi_span)) != source_map.span_to_snippet(*abi_span))
.then_some(()); .then_some(());
self.tcx.sess.emit_err(AbiSpecifiedMultipleTimes { self.dcx().emit_err(AbiSpecifiedMultipleTimes {
abi_span: *abi_span, abi_span: *abi_span,
prev_name: *prev_name, prev_name: *prev_name,
prev_span: *prev_sp, prev_span: *prev_sp,
@ -100,14 +100,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
} }
} }
Err(&[]) => { Err(&[]) => {
self.tcx.sess.emit_err(ClobberAbiNotSupported { abi_span: *abi_span }); self.dcx().emit_err(ClobberAbiNotSupported { abi_span: *abi_span });
} }
Err(supported_abis) => { Err(supported_abis) => {
let mut abis = format!("`{}`", supported_abis[0]); let mut abis = format!("`{}`", supported_abis[0]);
for m in &supported_abis[1..] { for m in &supported_abis[1..] {
let _ = write!(abis, ", `{m}`"); let _ = write!(abis, ", `{m}`");
} }
self.tcx.sess.emit_err(InvalidAbiClobberAbi { self.dcx().emit_err(InvalidAbiClobberAbi {
abi_span: *abi_span, abi_span: *abi_span,
supported_abis: abis, supported_abis: abis,
}); });
@ -128,7 +128,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
InlineAsmRegOrRegClass::Reg(reg) => { InlineAsmRegOrRegClass::Reg(reg) => {
asm::InlineAsmRegOrRegClass::Reg(if let Some(asm_arch) = asm_arch { asm::InlineAsmRegOrRegClass::Reg(if let Some(asm_arch) = asm_arch {
asm::InlineAsmReg::parse(asm_arch, reg).unwrap_or_else(|error| { asm::InlineAsmReg::parse(asm_arch, reg).unwrap_or_else(|error| {
sess.emit_err(InvalidRegister { op_span: *op_sp, reg, error }); self.dcx().emit_err(InvalidRegister {
op_span: *op_sp,
reg,
error,
});
asm::InlineAsmReg::Err asm::InlineAsmReg::Err
}) })
} else { } else {
@ -139,7 +143,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
asm::InlineAsmRegOrRegClass::RegClass(if let Some(asm_arch) = asm_arch { asm::InlineAsmRegOrRegClass::RegClass(if let Some(asm_arch) = asm_arch {
asm::InlineAsmRegClass::parse(asm_arch, reg_class).unwrap_or_else( asm::InlineAsmRegClass::parse(asm_arch, reg_class).unwrap_or_else(
|error| { |error| {
sess.emit_err(InvalidRegisterClass { self.dcx().emit_err(InvalidRegisterClass {
op_span: *op_sp, op_span: *op_sp,
reg_class, reg_class,
error, error,
@ -276,7 +280,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
class_name: class.name(), class_name: class.name(),
} }
}; };
sess.emit_err(InvalidAsmTemplateModifierRegClass { self.dcx().emit_err(InvalidAsmTemplateModifierRegClass {
placeholder_span, placeholder_span,
op_span: op_sp, op_span: op_sp,
sub, sub,
@ -284,14 +288,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
} }
} }
hir::InlineAsmOperand::Const { .. } => { hir::InlineAsmOperand::Const { .. } => {
sess.emit_err(InvalidAsmTemplateModifierConst { self.dcx().emit_err(InvalidAsmTemplateModifierConst {
placeholder_span, placeholder_span,
op_span: op_sp, op_span: op_sp,
}); });
} }
hir::InlineAsmOperand::SymFn { .. } hir::InlineAsmOperand::SymFn { .. }
| hir::InlineAsmOperand::SymStatic { .. } => { | hir::InlineAsmOperand::SymStatic { .. } => {
sess.emit_err(InvalidAsmTemplateModifierSym { self.dcx().emit_err(InvalidAsmTemplateModifierSym {
placeholder_span, placeholder_span,
op_span: op_sp, op_span: op_sp,
}); });
@ -315,7 +319,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
// require that the operand name an explicit register, not a // require that the operand name an explicit register, not a
// register class. // register class.
if reg_class.is_clobber_only(asm_arch.unwrap()) && !op.is_clobber() { if reg_class.is_clobber_only(asm_arch.unwrap()) && !op.is_clobber() {
sess.emit_err(RegisterClassOnlyClobber { self.dcx().emit_err(RegisterClassOnlyClobber {
op_span: op_sp, op_span: op_sp,
reg_class_name: reg_class.name(), reg_class_name: reg_class.name(),
}); });
@ -384,7 +388,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
} }
}; };
sess.emit_err(RegisterConflict { self.dcx().emit_err(RegisterConflict {
op_span1: op_sp, op_span1: op_sp,
op_span2: op_sp2, op_span2: op_sp2,
reg1_name: reg_str(idx), reg1_name: reg_str(idx),

View file

@ -249,7 +249,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), *lims) self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), *lims)
} }
ExprKind::Underscore => { ExprKind::Underscore => {
let guar = self.tcx.sess.emit_err(UnderscoreExprLhsAssign { span: e.span }); let guar = self.dcx().emit_err(UnderscoreExprLhsAssign { span: e.span });
hir::ExprKind::Err(guar) hir::ExprKind::Err(guar)
} }
ExprKind::Path(qself, path) => { ExprKind::Path(qself, path) => {
@ -294,8 +294,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let rest = match &se.rest { let rest = match &se.rest {
StructRest::Base(e) => Some(self.lower_expr(e)), StructRest::Base(e) => Some(self.lower_expr(e)),
StructRest::Rest(sp) => { StructRest::Rest(sp) => {
let guar = let guar = self.dcx().emit_err(BaseExpressionDoubleDot { span: *sp });
self.tcx.sess.emit_err(BaseExpressionDoubleDot { span: *sp });
Some(&*self.arena.alloc(self.expr_err(*sp, guar))) Some(&*self.arena.alloc(self.expr_err(*sp, guar)))
} }
StructRest::None => None, StructRest::None => None,
@ -332,9 +331,9 @@ impl<'hir> LoweringContext<'_, 'hir> {
|this| this.with_new_scopes(e.span, |this| this.lower_block_expr(block)), |this| this.with_new_scopes(e.span, |this| this.lower_block_expr(block)),
), ),
ExprKind::Yield(opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()), ExprKind::Yield(opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
ExprKind::Err => hir::ExprKind::Err( ExprKind::Err => {
self.tcx.sess.span_delayed_bug(e.span, "lowered ExprKind::Err"), hir::ExprKind::Err(self.dcx().span_delayed_bug(e.span, "lowered ExprKind::Err"))
), }
ExprKind::Try(sub_expr) => self.lower_expr_try(e.span, sub_expr), ExprKind::Try(sub_expr) => self.lower_expr_try(e.span, sub_expr),
ExprKind::Paren(_) | ExprKind::ForLoop { .. } => { ExprKind::Paren(_) | ExprKind::ForLoop { .. } => {
@ -584,13 +583,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
if self.tcx.features().never_patterns { if self.tcx.features().never_patterns {
// If the feature is off we already emitted the error after parsing. // If the feature is off we already emitted the error after parsing.
let suggestion = span.shrink_to_hi(); let suggestion = span.shrink_to_hi();
self.tcx.sess.emit_err(MatchArmWithNoBody { span, suggestion }); self.dcx().emit_err(MatchArmWithNoBody { span, suggestion });
} }
} else if let Some(body) = &arm.body { } else if let Some(body) = &arm.body {
self.tcx.sess.emit_err(NeverPatternWithBody { span: body.span }); self.dcx().emit_err(NeverPatternWithBody { span: body.span });
guard = None; guard = None;
} else if let Some(g) = &arm.guard { } else if let Some(g) = &arm.guard {
self.tcx.sess.emit_err(NeverPatternWithGuard { span: g.span }); self.dcx().emit_err(NeverPatternWithGuard { span: g.span });
guard = None; guard = None;
} }
@ -902,7 +901,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
Some(hir::CoroutineKind::Coroutine) Some(hir::CoroutineKind::Coroutine)
| Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)) | Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _))
| None => { | None => {
return hir::ExprKind::Err(self.tcx.sess.emit_err(AwaitOnlyInAsyncFnAndBlocks { return hir::ExprKind::Err(self.dcx().emit_err(AwaitOnlyInAsyncFnAndBlocks {
await_kw_span, await_kw_span,
item_span: self.current_item, item_span: self.current_item,
})); }));
@ -1129,7 +1128,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
match coroutine_kind { match coroutine_kind {
Some(hir::CoroutineKind::Coroutine) => { Some(hir::CoroutineKind::Coroutine) => {
if decl.inputs.len() > 1 { if decl.inputs.len() > 1 {
self.tcx.sess.emit_err(CoroutineTooManyParameters { fn_decl_span }); self.dcx().emit_err(CoroutineTooManyParameters { fn_decl_span });
} }
Some(movability) Some(movability)
} }
@ -1142,7 +1141,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
} }
None => { None => {
if movability == Movability::Static { if movability == Movability::Static {
self.tcx.sess.emit_err(ClosureCannotBeStatic { fn_decl_span }); self.dcx().emit_err(ClosureCannotBeStatic { fn_decl_span });
} }
None None
} }
@ -1181,7 +1180,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
}; };
if let &ClosureBinder::For { span, .. } = binder { if let &ClosureBinder::For { span, .. } = binder {
self.tcx.sess.emit_err(NotSupportedForLifetimeBinderAsyncClosure { span }); self.dcx().emit_err(NotSupportedForLifetimeBinderAsyncClosure { span });
} }
let (binder_clause, generic_params) = self.lower_closure_binder(binder); let (binder_clause, generic_params) = self.lower_closure_binder(binder);
@ -1192,7 +1191,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let body = self.with_new_scopes(fn_decl_span, |this| { let body = self.with_new_scopes(fn_decl_span, |this| {
// FIXME(cramertj): allow `async` non-`move` closures with arguments. // FIXME(cramertj): allow `async` non-`move` closures with arguments.
if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() { if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
this.tcx.sess.emit_err(AsyncNonMoveClosureNotSupported { fn_decl_span }); this.dcx().emit_err(AsyncNonMoveClosureNotSupported { fn_decl_span });
} }
// Transform `async |x: u8| -> X { ... }` into // Transform `async |x: u8| -> X { ... }` into
@ -1448,7 +1447,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
); );
let fields_omitted = match &se.rest { let fields_omitted = match &se.rest {
StructRest::Base(e) => { StructRest::Base(e) => {
self.tcx.sess.emit_err(FunctionalRecordUpdateDestructuringAssignment { self.dcx().emit_err(FunctionalRecordUpdateDestructuringAssignment {
span: e.span, span: e.span,
}); });
true true
@ -1544,7 +1543,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
(None, Some(..), Closed) => hir::LangItem::RangeToInclusive, (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
(Some(..), Some(..), Closed) => unreachable!(), (Some(..), Some(..), Closed) => unreachable!(),
(start, None, Closed) => { (start, None, Closed) => {
self.tcx.sess.emit_err(InclusiveRangeWithNoEnd { span }); self.dcx().emit_err(InclusiveRangeWithNoEnd { span });
match start { match start {
Some(..) => hir::LangItem::RangeFrom, Some(..) => hir::LangItem::RangeFrom,
None => hir::LangItem::RangeFull, None => hir::LangItem::RangeFull,
@ -1653,7 +1652,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => true, Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => true,
Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => { Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
return hir::ExprKind::Err( return hir::ExprKind::Err(
self.tcx.sess.emit_err(AsyncCoroutinesNotSupported { span }), self.dcx().emit_err(AsyncCoroutinesNotSupported { span }),
); );
} }
Some(hir::CoroutineKind::Coroutine) | None => { Some(hir::CoroutineKind::Coroutine) | None => {

View file

@ -267,7 +267,7 @@ fn make_count<'hir>(
ctx.expr( ctx.expr(
sp, sp,
hir::ExprKind::Err( hir::ExprKind::Err(
ctx.tcx.sess.span_delayed_bug(sp, "lowered bad format_args count"), ctx.dcx().span_delayed_bug(sp, "lowered bad format_args count"),
), ),
) )
} }
@ -306,7 +306,7 @@ fn make_format_spec<'hir>(
} }
Err(_) => ctx.expr( Err(_) => ctx.expr(
sp, sp,
hir::ExprKind::Err(ctx.tcx.sess.span_delayed_bug(sp, "lowered bad format_args count")), hir::ExprKind::Err(ctx.dcx().span_delayed_bug(sp, "lowered bad format_args count")),
), ),
}; };
let &FormatOptions { let &FormatOptions {

View file

@ -265,7 +265,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
&ImplTraitContext::Disallowed(ImplTraitPosition::Generic), &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
|this| match ty { |this| match ty {
None => { None => {
let guar = this.tcx.sess.span_delayed_bug( let guar = this.dcx().span_delayed_bug(
span, span,
"expected to lower type alias type, but it was missing", "expected to lower type alias type, but it was missing",
); );
@ -879,7 +879,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
&ImplTraitContext::Disallowed(ImplTraitPosition::Generic), &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
|this| match ty { |this| match ty {
None => { None => {
let guar = this.tcx.sess.span_delayed_bug( let guar = this.dcx().span_delayed_bug(
i.span, i.span,
"expected to lower associated type, but it was missing", "expected to lower associated type, but it was missing",
); );
@ -1012,7 +1012,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> { fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
match block { match block {
Some(block) => self.lower_block_expr(block), Some(block) => self.lower_block_expr(block),
None => self.expr_err(span, self.tcx.sess.span_delayed_bug(span, "no block")), None => self.expr_err(span, self.dcx().span_delayed_bug(span, "no block")),
} }
} }
@ -1022,7 +1022,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
&[], &[],
match expr { match expr {
Some(expr) => this.lower_expr_mut(expr), Some(expr) => this.lower_expr_mut(expr),
None => this.expr_err(span, this.tcx.sess.span_delayed_bug(span, "no block")), None => this.expr_err(span, this.dcx().span_delayed_bug(span, "no block")),
}, },
) )
}) })
@ -1296,7 +1296,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
.map(|s| Symbol::intern(s)) .map(|s| Symbol::intern(s))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let suggested_name = find_best_match_for_name(&abi_names, abi.symbol_unescaped, None); let suggested_name = find_best_match_for_name(&abi_names, abi.symbol_unescaped, None);
self.tcx.sess.emit_err(InvalidAbi { self.dcx().emit_err(InvalidAbi {
abi: abi.symbol_unescaped, abi: abi.symbol_unescaped,
span: abi.span, span: abi.span,
explain: match err { explain: match err {
@ -1383,7 +1383,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
} }
let is_param = *is_param.get_or_insert_with(compute_is_param); let is_param = *is_param.get_or_insert_with(compute_is_param);
if !is_param { if !is_param {
self.tcx.sess.emit_err(MisplacedRelaxTraitBound { span: bound.span() }); self.dcx().emit_err(MisplacedRelaxTraitBound { span: bound.span() });
} }
} }
} }

View file

@ -53,7 +53,7 @@ use rustc_data_structures::fingerprint::Fingerprint;
use rustc_data_structures::sorted_map::SortedMap; use rustc_data_structures::sorted_map::SortedMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::sync::Lrc; use rustc_data_structures::sync::Lrc;
use rustc_errors::{DiagnosticArgFromDisplay, StashKey}; use rustc_errors::{DiagCtxt, DiagnosticArgFromDisplay, StashKey};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res}; use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res};
use rustc_hir::def_id::{LocalDefId, LocalDefIdMap, CRATE_DEF_ID, LOCAL_CRATE}; use rustc_hir::def_id::{LocalDefId, LocalDefIdMap, CRATE_DEF_ID, LOCAL_CRATE};
@ -183,6 +183,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
host_param_id: None, host_param_id: None,
} }
} }
pub(crate) fn dcx(&self) -> &'hir DiagCtxt {
self.tcx.dcx()
}
} }
trait ResolverAstLoweringExt { trait ResolverAstLoweringExt {
@ -1035,11 +1039,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
&& first_char.is_ascii_lowercase() && first_char.is_ascii_lowercase()
{ {
let mut err = if !data.inputs.is_empty() { let mut err = if !data.inputs.is_empty() {
self.tcx.sess.create_err(errors::BadReturnTypeNotation::Inputs { self.dcx().create_err(errors::BadReturnTypeNotation::Inputs {
span: data.inputs_span, span: data.inputs_span,
}) })
} else if let FnRetTy::Ty(ty) = &data.output { } else if let FnRetTy::Ty(ty) = &data.output {
self.tcx.sess.create_err(errors::BadReturnTypeNotation::Output { self.dcx().create_err(errors::BadReturnTypeNotation::Output {
span: data.inputs_span.shrink_to_hi().to(ty.span), span: data.inputs_span.shrink_to_hi().to(ty.span),
}) })
} else { } else {
@ -1163,7 +1167,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
hir::TypeBindingKind::Constraint { bounds } hir::TypeBindingKind::Constraint { bounds }
} }
DesugarKind::Error(position) => { DesugarKind::Error(position) => {
let guar = self.tcx.sess.emit_err(errors::MisplacedAssocTyBinding { let guar = self.dcx().emit_err(errors::MisplacedAssocTyBinding {
span: constraint.span, span: constraint.span,
position: DiagnosticArgFromDisplay(position), position: DiagnosticArgFromDisplay(position),
}); });
@ -1205,7 +1209,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
data.inputs.last().unwrap().span.shrink_to_hi().to(data.inputs_span.shrink_to_hi()); data.inputs.last().unwrap().span.shrink_to_hi().to(data.inputs_span.shrink_to_hi());
AssocTyParenthesesSub::NotEmpty { open_param, close_param } AssocTyParenthesesSub::NotEmpty { open_param, close_param }
}; };
self.tcx.sess.emit_err(AssocTyParentheses { span: data.span, sub }); self.dcx().emit_err(AssocTyParentheses { span: data.span, sub });
} }
#[instrument(level = "debug", skip(self))] #[instrument(level = "debug", skip(self))]
@ -1347,20 +1351,20 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
let kind = match &t.kind { let kind = match &t.kind {
TyKind::Infer => hir::TyKind::Infer, TyKind::Infer => hir::TyKind::Infer,
TyKind::Err => { TyKind::Err => {
hir::TyKind::Err(self.tcx.sess.span_delayed_bug(t.span, "TyKind::Err lowered")) hir::TyKind::Err(self.dcx().span_delayed_bug(t.span, "TyKind::Err lowered"))
} }
// FIXME(unnamed_fields): IMPLEMENTATION IN PROGRESS // FIXME(unnamed_fields): IMPLEMENTATION IN PROGRESS
#[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::untranslatable_diagnostic)]
#[allow(rustc::diagnostic_outside_of_impl)] #[allow(rustc::diagnostic_outside_of_impl)]
TyKind::AnonStruct(ref _fields) => hir::TyKind::Err( TyKind::AnonStruct(ref _fields) => {
self.tcx.sess.span_err(t.span, "anonymous structs are unimplemented"), hir::TyKind::Err(self.dcx().span_err(t.span, "anonymous structs are unimplemented"))
), }
// FIXME(unnamed_fields): IMPLEMENTATION IN PROGRESS // FIXME(unnamed_fields): IMPLEMENTATION IN PROGRESS
#[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::untranslatable_diagnostic)]
#[allow(rustc::diagnostic_outside_of_impl)] #[allow(rustc::diagnostic_outside_of_impl)]
TyKind::AnonUnion(ref _fields) => hir::TyKind::Err( TyKind::AnonUnion(ref _fields) => {
self.tcx.sess.span_err(t.span, "anonymous unions are unimplemented"), hir::TyKind::Err(self.dcx().span_err(t.span, "anonymous unions are unimplemented"))
), }
TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)), TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)), TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
TyKind::Ref(region, mt) => { TyKind::Ref(region, mt) => {
@ -1518,7 +1522,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
hir::TyKind::Err(guar) hir::TyKind::Err(guar)
} }
ImplTraitContext::Disallowed(position) => { ImplTraitContext::Disallowed(position) => {
let guar = self.tcx.sess.emit_err(MisplacedImplTrait { let guar = self.dcx().emit_err(MisplacedImplTrait {
span: t.span, span: t.span,
position: DiagnosticArgFromDisplay(position), position: DiagnosticArgFromDisplay(position),
}); });
@ -1528,7 +1532,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
} }
TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"), TyKind::MacCall(_) => panic!("`TyKind::MacCall` should have been expanded by now"),
TyKind::CVarArgs => { TyKind::CVarArgs => {
let guar = self.tcx.sess.span_delayed_bug( let guar = self.dcx().span_delayed_bug(
t.span, t.span,
"`TyKind::CVarArgs` should have been handled elsewhere", "`TyKind::CVarArgs` should have been handled elsewhere",
); );
@ -1672,8 +1676,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
if let Some(old_def_id) = self.orig_opt_local_def_id(param) { if let Some(old_def_id) = self.orig_opt_local_def_id(param) {
old_def_id old_def_id
} else { } else {
self.tcx self.dcx()
.sess
.span_delayed_bug(lifetime.ident.span, "no def-id for fresh lifetime"); .span_delayed_bug(lifetime.ident.span, "no def-id for fresh lifetime");
continue; continue;
} }
@ -2569,7 +2572,7 @@ impl<'hir> GenericArgsCtor<'hir> {
let hir_id = lcx.next_id(); let hir_id = lcx.next_id();
let Some(host_param_id) = lcx.host_param_id else { let Some(host_param_id) = lcx.host_param_id else {
lcx.tcx.sess.span_delayed_bug( lcx.dcx().span_delayed_bug(
span, span,
"no host param id for call in const yet no errors reported", "no host param id for call in const yet no errors reported",
); );

View file

@ -140,7 +140,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
// This is not allowed as a sub-tuple pattern // This is not allowed as a sub-tuple pattern
PatKind::Ident(_, ident, Some(sub)) if sub.is_rest() => { PatKind::Ident(_, ident, Some(sub)) if sub.is_rest() => {
let sp = pat.span; let sp = pat.span;
self.tcx.sess.emit_err(SubTupleBinding { self.dcx().emit_err(SubTupleBinding {
span: sp, span: sp,
ident_name: ident.name, ident_name: ident.name,
ident: *ident, ident: *ident,
@ -289,12 +289,12 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
/// Emit a friendly error for extra `..` patterns in a tuple/tuple struct/slice pattern. /// Emit a friendly error for extra `..` patterns in a tuple/tuple struct/slice pattern.
pub(crate) fn ban_extra_rest_pat(&self, sp: Span, prev_sp: Span, ctx: &str) { pub(crate) fn ban_extra_rest_pat(&self, sp: Span, prev_sp: Span, ctx: &str) {
self.tcx.sess.emit_err(ExtraDoubleDot { span: sp, prev_span: prev_sp, ctx }); self.dcx().emit_err(ExtraDoubleDot { span: sp, prev_span: prev_sp, ctx });
} }
/// Used to ban the `..` pattern in places it shouldn't be semantically. /// Used to ban the `..` pattern in places it shouldn't be semantically.
fn ban_illegal_rest_pat(&self, sp: Span) -> hir::PatKind<'hir> { fn ban_illegal_rest_pat(&self, sp: Span) -> hir::PatKind<'hir> {
self.tcx.sess.emit_err(MisplacedDoubleDot { span: sp }); self.dcx().emit_err(MisplacedDoubleDot { span: sp });
// We're not in a list context so `..` can be reasonably treated // We're not in a list context so `..` can be reasonably treated
// as `_` because it should always be valid and roughly matches the // as `_` because it should always be valid and roughly matches the
@ -334,7 +334,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
ExprKind::Path(..) if allow_paths => {} ExprKind::Path(..) if allow_paths => {}
ExprKind::Unary(UnOp::Neg, inner) if matches!(inner.kind, ExprKind::Lit(_)) => {} ExprKind::Unary(UnOp::Neg, inner) if matches!(inner.kind, ExprKind::Lit(_)) => {}
_ => { _ => {
let guar = self.tcx.sess.emit_err(ArbitraryExpressionInPattern { span: expr.span }); let guar = self.dcx().emit_err(ArbitraryExpressionInPattern { span: expr.span });
return self.arena.alloc(self.expr_err(expr.span, guar)); return self.arena.alloc(self.expr_err(expr.span, guar));
} }
} }

View file

@ -140,7 +140,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
// We should've returned in the for loop above. // We should've returned in the for loop above.
self.tcx.sess.dcx().span_bug( self.dcx().span_bug(
p.span, p.span,
format!( format!(
"lower_qpath: no final extension segment in {}..{}", "lower_qpath: no final extension segment in {}..{}",
@ -214,7 +214,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
} else { } else {
None None
}; };
self.tcx.sess.emit_err(GenericTypeWithParentheses { span: data.span, sub }); self.dcx().emit_err(GenericTypeWithParentheses { span: data.span, sub });
( (
self.lower_angle_bracketed_parameter_data( self.lower_angle_bracketed_parameter_data(
&data.as_angle_bracketed_args(), &data.as_angle_bracketed_args(),

View file

@ -228,13 +228,13 @@ impl<'a> AstValidator<'a> {
fn check_lifetime(&self, ident: Ident) { fn check_lifetime(&self, ident: Ident) {
let valid_names = [kw::UnderscoreLifetime, kw::StaticLifetime, kw::Empty]; let valid_names = [kw::UnderscoreLifetime, kw::StaticLifetime, kw::Empty];
if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() { if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() {
self.session.emit_err(errors::KeywordLifetime { span: ident.span }); self.dcx().emit_err(errors::KeywordLifetime { span: ident.span });
} }
} }
fn check_label(&self, ident: Ident) { fn check_label(&self, ident: Ident) {
if ident.without_first_quote().is_reserved() { if ident.without_first_quote().is_reserved() {
self.session.emit_err(errors::InvalidLabel { span: ident.span, name: ident.name }); self.dcx().emit_err(errors::InvalidLabel { span: ident.span, name: ident.name });
} }
} }
@ -243,7 +243,7 @@ impl<'a> AstValidator<'a> {
return; return;
} }
self.session.emit_err(errors::VisibilityNotPermitted { span: vis.span, note }); self.dcx().emit_err(errors::VisibilityNotPermitted { span: vis.span, note });
} }
fn check_decl_no_pat(decl: &FnDecl, mut report_err: impl FnMut(Span, Option<Ident>, bool)) { fn check_decl_no_pat(decl: &FnDecl, mut report_err: impl FnMut(Span, Option<Ident>, bool)) {
@ -293,7 +293,7 @@ impl<'a> AstValidator<'a> {
fn check_trait_fn_not_const(&self, constness: Const) { fn check_trait_fn_not_const(&self, constness: Const) {
if let Const::Yes(span) = constness { if let Const::Yes(span) = constness {
self.session.emit_err(errors::TraitFnConst { span }); self.dcx().emit_err(errors::TraitFnConst { span });
} }
} }
@ -310,7 +310,7 @@ impl<'a> AstValidator<'a> {
let max_num_args: usize = u16::MAX.into(); let max_num_args: usize = u16::MAX.into();
if fn_decl.inputs.len() > max_num_args { if fn_decl.inputs.len() > max_num_args {
let Param { span, .. } = fn_decl.inputs[0]; let Param { span, .. } = fn_decl.inputs[0];
self.session.emit_fatal(errors::FnParamTooMany { span, max_num_args }); self.dcx().emit_fatal(errors::FnParamTooMany { span, max_num_args });
} }
} }
@ -318,13 +318,13 @@ impl<'a> AstValidator<'a> {
match &*fn_decl.inputs { match &*fn_decl.inputs {
[Param { ty, span, .. }] => { [Param { ty, span, .. }] => {
if let TyKind::CVarArgs = ty.kind { if let TyKind::CVarArgs = ty.kind {
self.session.emit_err(errors::FnParamCVarArgsOnly { span: *span }); self.dcx().emit_err(errors::FnParamCVarArgsOnly { span: *span });
} }
} }
[ps @ .., _] => { [ps @ .., _] => {
for Param { ty, span, .. } in ps { for Param { ty, span, .. } in ps {
if let TyKind::CVarArgs = ty.kind { if let TyKind::CVarArgs = ty.kind {
self.session.emit_err(errors::FnParamCVarArgsNotLast { span: *span }); self.dcx().emit_err(errors::FnParamCVarArgsNotLast { span: *span });
} }
} }
} }
@ -351,9 +351,9 @@ impl<'a> AstValidator<'a> {
}) })
.for_each(|attr| { .for_each(|attr| {
if attr.is_doc_comment() { if attr.is_doc_comment() {
self.session.emit_err(errors::FnParamDocComment { span: attr.span }); self.dcx().emit_err(errors::FnParamDocComment { span: attr.span });
} else { } else {
self.session.emit_err(errors::FnParamForbiddenAttr { span: attr.span }); self.dcx().emit_err(errors::FnParamForbiddenAttr { span: attr.span });
} }
}); });
} }
@ -361,7 +361,7 @@ impl<'a> AstValidator<'a> {
fn check_decl_self_param(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) { fn check_decl_self_param(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) {
if let (SelfSemantic::No, [param, ..]) = (self_semantic, &*fn_decl.inputs) { if let (SelfSemantic::No, [param, ..]) = (self_semantic, &*fn_decl.inputs) {
if param.is_self() { if param.is_self() {
self.session.emit_err(errors::FnParamForbiddenSelf { span: param.span }); self.dcx().emit_err(errors::FnParamForbiddenSelf { span: param.span });
} }
} }
} }
@ -369,7 +369,7 @@ impl<'a> AstValidator<'a> {
fn check_defaultness(&self, span: Span, defaultness: Defaultness) { fn check_defaultness(&self, span: Span, defaultness: Defaultness) {
if let Defaultness::Default(def_span) = defaultness { if let Defaultness::Default(def_span) = defaultness {
let span = self.session.source_map().guess_head_span(span); let span = self.session.source_map().guess_head_span(span);
self.session.emit_err(errors::ForbiddenDefault { span, def_span }); self.dcx().emit_err(errors::ForbiddenDefault { span, def_span });
} }
} }
@ -532,24 +532,24 @@ impl<'a> AstValidator<'a> {
return; return;
} }
let span = self.session.source_map().guess_head_span(item_span); let span = self.session.source_map().guess_head_span(item_span);
self.session.emit_err(errors::NoMangleAscii { span }); self.dcx().emit_err(errors::NoMangleAscii { span });
} }
fn check_mod_file_item_asciionly(&self, ident: Ident) { fn check_mod_file_item_asciionly(&self, ident: Ident) {
if ident.name.as_str().is_ascii() { if ident.name.as_str().is_ascii() {
return; return;
} }
self.session.emit_err(errors::ModuleNonAscii { span: ident.span, name: ident.name }); self.dcx().emit_err(errors::ModuleNonAscii { span: ident.span, name: ident.name });
} }
fn deny_generic_params(&self, generics: &Generics, ident: Span) { fn deny_generic_params(&self, generics: &Generics, ident: Span) {
if !generics.params.is_empty() { if !generics.params.is_empty() {
self.session.emit_err(errors::AutoTraitGeneric { span: generics.span, ident }); self.dcx().emit_err(errors::AutoTraitGeneric { span: generics.span, ident });
} }
} }
fn emit_e0568(&self, span: Span, ident: Span) { fn emit_e0568(&self, span: Span, ident: Span) {
self.session.emit_err(errors::AutoTraitBounds { span, ident }); self.dcx().emit_err(errors::AutoTraitBounds { span, ident });
} }
fn deny_super_traits(&self, bounds: &GenericBounds, ident_span: Span) { fn deny_super_traits(&self, bounds: &GenericBounds, ident_span: Span) {
@ -569,7 +569,7 @@ impl<'a> AstValidator<'a> {
if !trait_items.is_empty() { if !trait_items.is_empty() {
let spans: Vec<_> = trait_items.iter().map(|i| i.ident.span).collect(); let spans: Vec<_> = trait_items.iter().map(|i| i.ident.span).collect();
let total = trait_items.first().unwrap().span.to(trait_items.last().unwrap().span); let total = trait_items.first().unwrap().span.to(trait_items.last().unwrap().span);
self.session.emit_err(errors::AutoTraitItems { spans, total, ident }); self.dcx().emit_err(errors::AutoTraitItems { spans, total, ident });
} }
} }
@ -633,7 +633,7 @@ impl<'a> AstValidator<'a> {
TyKind::BareFn(bfty) => { TyKind::BareFn(bfty) => {
self.check_fn_decl(&bfty.decl, SelfSemantic::No); self.check_fn_decl(&bfty.decl, SelfSemantic::No);
Self::check_decl_no_pat(&bfty.decl, |span, _, _| { Self::check_decl_no_pat(&bfty.decl, |span, _, _| {
self.session.emit_err(errors::PatternFnPointer { span }); self.dcx().emit_err(errors::PatternFnPointer { span });
}); });
if let Extern::Implicit(_) = bfty.ext { if let Extern::Implicit(_) = bfty.ext {
let sig_span = self.session.source_map().next_point(ty.span.shrink_to_lo()); let sig_span = self.session.source_map().next_point(ty.span.shrink_to_lo());
@ -645,7 +645,7 @@ impl<'a> AstValidator<'a> {
for bound in bounds { for bound in bounds {
if let GenericBound::Outlives(lifetime) = bound { if let GenericBound::Outlives(lifetime) = bound {
if any_lifetime_bounds { if any_lifetime_bounds {
self.session self.dcx()
.emit_err(errors::TraitObjectBound { span: lifetime.ident.span }); .emit_err(errors::TraitObjectBound { span: lifetime.ident.span });
break; break;
} }
@ -655,11 +655,11 @@ impl<'a> AstValidator<'a> {
} }
TyKind::ImplTrait(_, bounds) => { TyKind::ImplTrait(_, bounds) => {
if self.is_impl_trait_banned { if self.is_impl_trait_banned {
self.session.emit_err(errors::ImplTraitPath { span: ty.span }); self.dcx().emit_err(errors::ImplTraitPath { span: ty.span });
} }
if let Some(outer_impl_trait_sp) = self.outer_impl_trait { if let Some(outer_impl_trait_sp) = self.outer_impl_trait {
self.session.emit_err(errors::NestedImplTrait { self.dcx().emit_err(errors::NestedImplTrait {
span: ty.span, span: ty.span,
outer: outer_impl_trait_sp, outer: outer_impl_trait_sp,
inner: ty.span, inner: ty.span,
@ -827,7 +827,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
} }
if let (&Unsafe::Yes(span), &ImplPolarity::Negative(sp)) = (unsafety, polarity) if let (&Unsafe::Yes(span), &ImplPolarity::Negative(sp)) = (unsafety, polarity)
{ {
this.session.emit_err(errors::UnsafeNegativeImpl { this.dcx().emit_err(errors::UnsafeNegativeImpl {
span: sp.to(t.path.span), span: sp.to(t.path.span),
negative: sp, negative: sp,
r#unsafe: span, r#unsafe: span,
@ -902,7 +902,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
self.check_defaultness(item.span, *defaultness); self.check_defaultness(item.span, *defaultness);
if body.is_none() { if body.is_none() {
self.session.emit_err(errors::FnWithoutBody { self.dcx().emit_err(errors::FnWithoutBody {
span: item.span, span: item.span,
replace_span: self.ending_semi_or_hi(item.span), replace_span: self.ending_semi_or_hi(item.span),
extern_block_suggestion: match sig.header.ext { extern_block_suggestion: match sig.header.ext {
@ -1031,14 +1031,14 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
ItemKind::Const(box ConstItem { defaultness, expr, .. }) => { ItemKind::Const(box ConstItem { defaultness, expr, .. }) => {
self.check_defaultness(item.span, *defaultness); self.check_defaultness(item.span, *defaultness);
if expr.is_none() { if expr.is_none() {
self.session.emit_err(errors::ConstWithoutBody { self.dcx().emit_err(errors::ConstWithoutBody {
span: item.span, span: item.span,
replace_span: self.ending_semi_or_hi(item.span), replace_span: self.ending_semi_or_hi(item.span),
}); });
} }
} }
ItemKind::Static(box StaticItem { expr: None, .. }) => { ItemKind::Static(box StaticItem { expr: None, .. }) => {
self.session.emit_err(errors::StaticWithoutBody { self.dcx().emit_err(errors::StaticWithoutBody {
span: item.span, span: item.span,
replace_span: self.ending_semi_or_hi(item.span), replace_span: self.ending_semi_or_hi(item.span),
}); });
@ -1048,7 +1048,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
) => { ) => {
self.check_defaultness(item.span, *defaultness); self.check_defaultness(item.span, *defaultness);
if ty.is_none() { if ty.is_none() {
self.session.emit_err(errors::TyAliasWithoutBody { self.dcx().emit_err(errors::TyAliasWithoutBody {
span: item.span, span: item.span,
replace_span: self.ending_semi_or_hi(item.span), replace_span: self.ending_semi_or_hi(item.span),
}); });
@ -1357,14 +1357,14 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
if ctxt == AssocCtxt::Impl { if ctxt == AssocCtxt::Impl {
match &item.kind { match &item.kind {
AssocItemKind::Const(box ConstItem { expr: None, .. }) => { AssocItemKind::Const(box ConstItem { expr: None, .. }) => {
self.session.emit_err(errors::AssocConstWithoutBody { self.dcx().emit_err(errors::AssocConstWithoutBody {
span: item.span, span: item.span,
replace_span: self.ending_semi_or_hi(item.span), replace_span: self.ending_semi_or_hi(item.span),
}); });
} }
AssocItemKind::Fn(box Fn { body, .. }) => { AssocItemKind::Fn(box Fn { body, .. }) => {
if body.is_none() { if body.is_none() {
self.session.emit_err(errors::AssocFnWithoutBody { self.dcx().emit_err(errors::AssocFnWithoutBody {
span: item.span, span: item.span,
replace_span: self.ending_semi_or_hi(item.span), replace_span: self.ending_semi_or_hi(item.span),
}); });
@ -1372,7 +1372,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
} }
AssocItemKind::Type(box TyAlias { bounds, ty, .. }) => { AssocItemKind::Type(box TyAlias { bounds, ty, .. }) => {
if ty.is_none() { if ty.is_none() {
self.session.emit_err(errors::AssocTypeWithoutBody { self.dcx().emit_err(errors::AssocTypeWithoutBody {
span: item.span, span: item.span,
replace_span: self.ending_semi_or_hi(item.span), replace_span: self.ending_semi_or_hi(item.span),
}); });

View file

@ -168,7 +168,7 @@ impl<'a> PostExpansionVisitor<'a> {
for param in params { for param in params {
if !param.bounds.is_empty() { if !param.bounds.is_empty() {
let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect(); let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
self.sess.emit_err(errors::ForbiddenBound { spans }); self.sess.dcx().emit_err(errors::ForbiddenBound { spans });
} }
} }
} }
@ -226,7 +226,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
|| attr.has_name(sym::rustc_const_stable) || attr.has_name(sym::rustc_const_stable)
|| attr.has_name(sym::rustc_default_body_unstable) || attr.has_name(sym::rustc_default_body_unstable)
{ {
self.sess.emit_err(errors::StabilityOutsideStd { span: attr.span }); self.sess.dcx().emit_err(errors::StabilityOutsideStd { span: attr.span });
} }
} }
} }
@ -579,7 +579,7 @@ pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) {
.emit(); .emit();
} else { } else {
let suggestion = span.shrink_to_hi(); let suggestion = span.shrink_to_hi();
sess.emit_err(errors::MatchArmWithNoBody { span, suggestion }); sess.dcx().emit_err(errors::MatchArmWithNoBody { span, suggestion });
} }
} }
} }
@ -587,7 +587,7 @@ pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) {
if !visitor.features.negative_bounds { if !visitor.features.negative_bounds {
for &span in spans.get(&sym::negative_bounds).iter().copied().flatten() { for &span in spans.get(&sym::negative_bounds).iter().copied().flatten() {
sess.emit_err(errors::NegativeBoundUnsupported { span }); sess.dcx().emit_err(errors::NegativeBoundUnsupported { span });
} }
} }
@ -677,7 +677,11 @@ fn check_incompatible_features(sess: &Session, features: &Features) {
if let Some((f2_name, f2_span)) = declared_features.clone().find(|(name, _)| name == f2) if let Some((f2_name, f2_span)) = declared_features.clone().find(|(name, _)| name == f2)
{ {
let spans = vec![f1_span, f2_span]; let spans = vec![f1_span, f2_span];
sess.emit_err(errors::IncompatibleFeatures { spans, f1: f1_name, f2: f2_name }); sess.dcx().emit_err(errors::IncompatibleFeatures {
spans,
f1: f1_name,
f2: f2_name,
});
} }
} }
} }

View file

@ -207,7 +207,8 @@ pub fn find_stability(
sym::rustc_allowed_through_unstable_modules => allowed_through_unstable_modules = true, sym::rustc_allowed_through_unstable_modules => allowed_through_unstable_modules = true,
sym::unstable => { sym::unstable => {
if stab.is_some() { if stab.is_some() {
sess.emit_err(session_diagnostics::MultipleStabilityLevels { span: attr.span }); sess.dcx()
.emit_err(session_diagnostics::MultipleStabilityLevels { span: attr.span });
break; break;
} }
@ -217,7 +218,8 @@ pub fn find_stability(
} }
sym::stable => { sym::stable => {
if stab.is_some() { if stab.is_some() {
sess.emit_err(session_diagnostics::MultipleStabilityLevels { span: attr.span }); sess.dcx()
.emit_err(session_diagnostics::MultipleStabilityLevels { span: attr.span });
break; break;
} }
if let Some((feature, level)) = parse_stability(sess, attr) { if let Some((feature, level)) = parse_stability(sess, attr) {
@ -238,7 +240,8 @@ pub fn find_stability(
_, _,
)) => *allowed_through_unstable_modules = true, )) => *allowed_through_unstable_modules = true,
_ => { _ => {
sess.emit_err(session_diagnostics::RustcAllowedUnstablePairing { span: item_sp }); sess.dcx()
.emit_err(session_diagnostics::RustcAllowedUnstablePairing { span: item_sp });
} }
} }
} }
@ -261,7 +264,8 @@ pub fn find_const_stability(
sym::rustc_promotable => promotable = true, sym::rustc_promotable => promotable = true,
sym::rustc_const_unstable => { sym::rustc_const_unstable => {
if const_stab.is_some() { if const_stab.is_some() {
sess.emit_err(session_diagnostics::MultipleStabilityLevels { span: attr.span }); sess.dcx()
.emit_err(session_diagnostics::MultipleStabilityLevels { span: attr.span });
break; break;
} }
@ -272,7 +276,8 @@ pub fn find_const_stability(
} }
sym::rustc_const_stable => { sym::rustc_const_stable => {
if const_stab.is_some() { if const_stab.is_some() {
sess.emit_err(session_diagnostics::MultipleStabilityLevels { span: attr.span }); sess.dcx()
.emit_err(session_diagnostics::MultipleStabilityLevels { span: attr.span });
break; break;
} }
if let Some((feature, level)) = parse_stability(sess, attr) { if let Some((feature, level)) = parse_stability(sess, attr) {
@ -288,7 +293,11 @@ pub fn find_const_stability(
if promotable { if promotable {
match &mut const_stab { match &mut const_stab {
Some((stab, _)) => stab.promotable = promotable, Some((stab, _)) => stab.promotable = promotable,
_ => _ = sess.emit_err(session_diagnostics::RustcPromotablePairing { span: item_sp }), _ => {
_ = sess
.dcx()
.emit_err(session_diagnostics::RustcPromotablePairing { span: item_sp })
}
} }
} }
@ -306,7 +315,8 @@ pub fn find_body_stability(
for attr in attrs { for attr in attrs {
if attr.has_name(sym::rustc_default_body_unstable) { if attr.has_name(sym::rustc_default_body_unstable) {
if body_stab.is_some() { if body_stab.is_some() {
sess.emit_err(session_diagnostics::MultipleStabilityLevels { span: attr.span }); sess.dcx()
.emit_err(session_diagnostics::MultipleStabilityLevels { span: attr.span });
break; break;
} }
@ -321,7 +331,7 @@ pub fn find_body_stability(
fn insert_or_error(sess: &Session, meta: &MetaItem, item: &mut Option<Symbol>) -> Option<()> { fn insert_or_error(sess: &Session, meta: &MetaItem, item: &mut Option<Symbol>) -> Option<()> {
if item.is_some() { if item.is_some() {
sess.emit_err(session_diagnostics::MultipleItem { sess.dcx().emit_err(session_diagnostics::MultipleItem {
span: meta.span, span: meta.span,
item: pprust::path_to_string(&meta.path), item: pprust::path_to_string(&meta.path),
}); });
@ -330,7 +340,7 @@ fn insert_or_error(sess: &Session, meta: &MetaItem, item: &mut Option<Symbol>) -
*item = Some(v); *item = Some(v);
Some(()) Some(())
} else { } else {
sess.emit_err(session_diagnostics::IncorrectMetaItem { span: meta.span }); sess.dcx().emit_err(session_diagnostics::IncorrectMetaItem { span: meta.span });
None None
} }
} }
@ -345,7 +355,7 @@ fn parse_stability(sess: &Session, attr: &Attribute) -> Option<(Symbol, Stabilit
let mut since = None; let mut since = None;
for meta in metas { for meta in metas {
let Some(mi) = meta.meta_item() else { let Some(mi) = meta.meta_item() else {
sess.emit_err(session_diagnostics::UnsupportedLiteral { sess.dcx().emit_err(session_diagnostics::UnsupportedLiteral {
span: meta.span(), span: meta.span(),
reason: UnsupportedLiteralReason::Generic, reason: UnsupportedLiteralReason::Generic,
is_bytestr: false, is_bytestr: false,
@ -358,7 +368,7 @@ fn parse_stability(sess: &Session, attr: &Attribute) -> Option<(Symbol, Stabilit
sym::feature => insert_or_error(sess, mi, &mut feature)?, sym::feature => insert_or_error(sess, mi, &mut feature)?,
sym::since => insert_or_error(sess, mi, &mut since)?, sym::since => insert_or_error(sess, mi, &mut since)?,
_ => { _ => {
sess.emit_err(session_diagnostics::UnknownMetaItem { sess.dcx().emit_err(session_diagnostics::UnknownMetaItem {
span: meta.span(), span: meta.span(),
item: pprust::path_to_string(&mi.path), item: pprust::path_to_string(&mi.path),
expected: &["feature", "since"], expected: &["feature", "since"],
@ -371,9 +381,9 @@ fn parse_stability(sess: &Session, attr: &Attribute) -> Option<(Symbol, Stabilit
let feature = match feature { let feature = match feature {
Some(feature) if rustc_lexer::is_ident(feature.as_str()) => Ok(feature), Some(feature) if rustc_lexer::is_ident(feature.as_str()) => Ok(feature),
Some(_bad_feature) => { Some(_bad_feature) => {
Err(sess.emit_err(session_diagnostics::NonIdentFeature { span: attr.span })) Err(sess.dcx().emit_err(session_diagnostics::NonIdentFeature { span: attr.span }))
} }
None => Err(sess.emit_err(session_diagnostics::MissingFeature { span: attr.span })), None => Err(sess.dcx().emit_err(session_diagnostics::MissingFeature { span: attr.span })),
}; };
let since = if let Some(since) = since { let since = if let Some(since) = since {
@ -382,11 +392,11 @@ fn parse_stability(sess: &Session, attr: &Attribute) -> Option<(Symbol, Stabilit
} else if let Some(version) = parse_version(since) { } else if let Some(version) = parse_version(since) {
StableSince::Version(version) StableSince::Version(version)
} else { } else {
sess.emit_err(session_diagnostics::InvalidSince { span: attr.span }); sess.dcx().emit_err(session_diagnostics::InvalidSince { span: attr.span });
StableSince::Err StableSince::Err
} }
} else { } else {
sess.emit_err(session_diagnostics::MissingSince { span: attr.span }); sess.dcx().emit_err(session_diagnostics::MissingSince { span: attr.span });
StableSince::Err StableSince::Err
}; };
@ -413,7 +423,7 @@ fn parse_unstability(sess: &Session, attr: &Attribute) -> Option<(Symbol, Stabil
let mut implied_by = None; let mut implied_by = None;
for meta in metas { for meta in metas {
let Some(mi) = meta.meta_item() else { let Some(mi) = meta.meta_item() else {
sess.emit_err(session_diagnostics::UnsupportedLiteral { sess.dcx().emit_err(session_diagnostics::UnsupportedLiteral {
span: meta.span(), span: meta.span(),
reason: UnsupportedLiteralReason::Generic, reason: UnsupportedLiteralReason::Generic,
is_bytestr: false, is_bytestr: false,
@ -435,7 +445,7 @@ fn parse_unstability(sess: &Session, attr: &Attribute) -> Option<(Symbol, Stabil
issue => match issue.parse::<NonZeroU32>() { issue => match issue.parse::<NonZeroU32>() {
Ok(num) => Some(num), Ok(num) => Some(num),
Err(err) => { Err(err) => {
sess.emit_err( sess.dcx().emit_err(
session_diagnostics::InvalidIssueString { session_diagnostics::InvalidIssueString {
span: mi.span, span: mi.span,
cause: session_diagnostics::InvalidIssueStringCause::from_int_error_kind( cause: session_diagnostics::InvalidIssueStringCause::from_int_error_kind(
@ -451,13 +461,13 @@ fn parse_unstability(sess: &Session, attr: &Attribute) -> Option<(Symbol, Stabil
} }
sym::soft => { sym::soft => {
if !mi.is_word() { if !mi.is_word() {
sess.emit_err(session_diagnostics::SoftNoArgs { span: mi.span }); sess.dcx().emit_err(session_diagnostics::SoftNoArgs { span: mi.span });
} }
is_soft = true; is_soft = true;
} }
sym::implied_by => insert_or_error(sess, mi, &mut implied_by)?, sym::implied_by => insert_or_error(sess, mi, &mut implied_by)?,
_ => { _ => {
sess.emit_err(session_diagnostics::UnknownMetaItem { sess.dcx().emit_err(session_diagnostics::UnknownMetaItem {
span: meta.span(), span: meta.span(),
item: pprust::path_to_string(&mi.path), item: pprust::path_to_string(&mi.path),
expected: &["feature", "reason", "issue", "soft", "implied_by"], expected: &["feature", "reason", "issue", "soft", "implied_by"],
@ -470,13 +480,13 @@ fn parse_unstability(sess: &Session, attr: &Attribute) -> Option<(Symbol, Stabil
let feature = match feature { let feature = match feature {
Some(feature) if rustc_lexer::is_ident(feature.as_str()) => Ok(feature), Some(feature) if rustc_lexer::is_ident(feature.as_str()) => Ok(feature),
Some(_bad_feature) => { Some(_bad_feature) => {
Err(sess.emit_err(session_diagnostics::NonIdentFeature { span: attr.span })) Err(sess.dcx().emit_err(session_diagnostics::NonIdentFeature { span: attr.span }))
} }
None => Err(sess.emit_err(session_diagnostics::MissingFeature { span: attr.span })), None => Err(sess.dcx().emit_err(session_diagnostics::MissingFeature { span: attr.span })),
}; };
let issue = let issue = issue
issue.ok_or_else(|| sess.emit_err(session_diagnostics::MissingIssue { span: attr.span })); .ok_or_else(|| sess.dcx().emit_err(session_diagnostics::MissingIssue { span: attr.span }));
match (feature, issue) { match (feature, issue) {
(Ok(feature), Ok(_)) => { (Ok(feature), Ok(_)) => {
@ -588,6 +598,7 @@ pub fn eval_condition(
features: Option<&Features>, features: Option<&Features>,
eval: &mut impl FnMut(Condition) -> bool, eval: &mut impl FnMut(Condition) -> bool,
) -> bool { ) -> bool {
let dcx = &sess.dcx;
match &cfg.kind { match &cfg.kind {
ast::MetaItemKind::List(mis) if cfg.name_or_empty() == sym::version => { ast::MetaItemKind::List(mis) if cfg.name_or_empty() == sym::version => {
try_gate_cfg(sym::version, cfg.span, sess, features); try_gate_cfg(sym::version, cfg.span, sess, features);
@ -599,18 +610,18 @@ pub fn eval_condition(
NestedMetaItem::Lit(MetaItemLit { span, .. }) NestedMetaItem::Lit(MetaItemLit { span, .. })
| NestedMetaItem::MetaItem(MetaItem { span, .. }), | NestedMetaItem::MetaItem(MetaItem { span, .. }),
] => { ] => {
sess.emit_err(session_diagnostics::ExpectedVersionLiteral { span: *span }); dcx.emit_err(session_diagnostics::ExpectedVersionLiteral { span: *span });
return false; return false;
} }
[..] => { [..] => {
sess.emit_err(session_diagnostics::ExpectedSingleVersionLiteral { dcx.emit_err(session_diagnostics::ExpectedSingleVersionLiteral {
span: cfg.span, span: cfg.span,
}); });
return false; return false;
} }
}; };
let Some(min_version) = parse_version(*min_version) else { let Some(min_version) = parse_version(*min_version) else {
sess.emit_warning(session_diagnostics::UnknownVersionLiteral { span: *span }); dcx.emit_warning(session_diagnostics::UnknownVersionLiteral { span: *span });
return false; return false;
}; };
@ -624,7 +635,7 @@ pub fn eval_condition(
ast::MetaItemKind::List(mis) => { ast::MetaItemKind::List(mis) => {
for mi in mis.iter() { for mi in mis.iter() {
if !mi.is_meta_item() { if !mi.is_meta_item() {
sess.emit_err(session_diagnostics::UnsupportedLiteral { dcx.emit_err(session_diagnostics::UnsupportedLiteral {
span: mi.span(), span: mi.span(),
reason: UnsupportedLiteralReason::Generic, reason: UnsupportedLiteralReason::Generic,
is_bytestr: false, is_bytestr: false,
@ -653,9 +664,7 @@ pub fn eval_condition(
}), }),
sym::not => { sym::not => {
if mis.len() != 1 { if mis.len() != 1 {
sess.emit_err(session_diagnostics::ExpectedOneCfgPattern { dcx.emit_err(session_diagnostics::ExpectedOneCfgPattern { span: cfg.span });
span: cfg.span,
});
return false; return false;
} }
@ -684,7 +693,7 @@ pub fn eval_condition(
}) })
} }
_ => { _ => {
sess.emit_err(session_diagnostics::InvalidPredicate { dcx.emit_err(session_diagnostics::InvalidPredicate {
span: cfg.span, span: cfg.span,
predicate: pprust::path_to_string(&cfg.path), predicate: pprust::path_to_string(&cfg.path),
}); });
@ -693,11 +702,11 @@ pub fn eval_condition(
} }
} }
ast::MetaItemKind::Word | MetaItemKind::NameValue(..) if cfg.path.segments.len() != 1 => { ast::MetaItemKind::Word | MetaItemKind::NameValue(..) if cfg.path.segments.len() != 1 => {
sess.emit_err(session_diagnostics::CfgPredicateIdentifier { span: cfg.path.span }); dcx.emit_err(session_diagnostics::CfgPredicateIdentifier { span: cfg.path.span });
true true
} }
MetaItemKind::NameValue(lit) if !lit.kind.is_str() => { MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
sess.emit_err(session_diagnostics::UnsupportedLiteral { dcx.emit_err(session_diagnostics::UnsupportedLiteral {
span: lit.span, span: lit.span,
reason: UnsupportedLiteralReason::CfgString, reason: UnsupportedLiteralReason::CfgString,
is_bytestr: lit.kind.is_bytestr(), is_bytestr: lit.kind.is_bytestr(),
@ -791,7 +800,7 @@ pub fn find_deprecation(
MetaItemKind::List(list) => { MetaItemKind::List(list) => {
let get = |meta: &MetaItem, item: &mut Option<Symbol>| { let get = |meta: &MetaItem, item: &mut Option<Symbol>| {
if item.is_some() { if item.is_some() {
sess.emit_err(session_diagnostics::MultipleItem { sess.dcx().emit_err(session_diagnostics::MultipleItem {
span: meta.span, span: meta.span,
item: pprust::path_to_string(&meta.path), item: pprust::path_to_string(&meta.path),
}); });
@ -802,14 +811,14 @@ pub fn find_deprecation(
true true
} else { } else {
if let Some(lit) = meta.name_value_literal() { if let Some(lit) = meta.name_value_literal() {
sess.emit_err(session_diagnostics::UnsupportedLiteral { sess.dcx().emit_err(session_diagnostics::UnsupportedLiteral {
span: lit.span, span: lit.span,
reason: UnsupportedLiteralReason::DeprecatedString, reason: UnsupportedLiteralReason::DeprecatedString,
is_bytestr: lit.kind.is_bytestr(), is_bytestr: lit.kind.is_bytestr(),
start_point_span: sess.source_map().start_point(lit.span), start_point_span: sess.source_map().start_point(lit.span),
}); });
} else { } else {
sess.emit_err(session_diagnostics::IncorrectMetaItem { sess.dcx().emit_err(session_diagnostics::IncorrectMetaItem {
span: meta.span, span: meta.span,
}); });
} }
@ -833,11 +842,13 @@ pub fn find_deprecation(
} }
sym::suggestion => { sym::suggestion => {
if !features.deprecated_suggestion { if !features.deprecated_suggestion {
sess.emit_err(session_diagnostics::DeprecatedItemSuggestion { sess.dcx().emit_err(
span: mi.span, session_diagnostics::DeprecatedItemSuggestion {
is_nightly: sess.is_nightly_build().then_some(()), span: mi.span,
details: (), is_nightly: sess.is_nightly_build().then_some(()),
}); details: (),
},
);
} }
if !get(mi, &mut suggestion) { if !get(mi, &mut suggestion) {
@ -845,7 +856,7 @@ pub fn find_deprecation(
} }
} }
_ => { _ => {
sess.emit_err(session_diagnostics::UnknownMetaItem { sess.dcx().emit_err(session_diagnostics::UnknownMetaItem {
span: meta.span(), span: meta.span(),
item: pprust::path_to_string(&mi.path), item: pprust::path_to_string(&mi.path),
expected: if features.deprecated_suggestion { expected: if features.deprecated_suggestion {
@ -858,7 +869,7 @@ pub fn find_deprecation(
} }
}, },
NestedMetaItem::Lit(lit) => { NestedMetaItem::Lit(lit) => {
sess.emit_err(session_diagnostics::UnsupportedLiteral { sess.dcx().emit_err(session_diagnostics::UnsupportedLiteral {
span: lit.span, span: lit.span,
reason: UnsupportedLiteralReason::DeprecatedKvPair, reason: UnsupportedLiteralReason::DeprecatedKvPair,
is_bytestr: false, is_bytestr: false,
@ -879,18 +890,18 @@ pub fn find_deprecation(
} else if let Some(version) = parse_version(since) { } else if let Some(version) = parse_version(since) {
DeprecatedSince::RustcVersion(version) DeprecatedSince::RustcVersion(version)
} else { } else {
sess.emit_err(session_diagnostics::InvalidSince { span: attr.span }); sess.dcx().emit_err(session_diagnostics::InvalidSince { span: attr.span });
DeprecatedSince::Err DeprecatedSince::Err
} }
} else if is_rustc { } else if is_rustc {
sess.emit_err(session_diagnostics::MissingSince { span: attr.span }); sess.dcx().emit_err(session_diagnostics::MissingSince { span: attr.span });
DeprecatedSince::Err DeprecatedSince::Err
} else { } else {
DeprecatedSince::Unspecified DeprecatedSince::Unspecified
}; };
if is_rustc && note.is_none() { if is_rustc && note.is_none() {
sess.emit_err(session_diagnostics::MissingNote { span: attr.span }); sess.dcx().emit_err(session_diagnostics::MissingNote { span: attr.span });
continue; continue;
} }
@ -945,7 +956,7 @@ pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
assert!(attr.has_name(sym::repr), "expected `#[repr(..)]`, found: {attr:?}"); assert!(attr.has_name(sym::repr), "expected `#[repr(..)]`, found: {attr:?}");
use ReprAttr::*; use ReprAttr::*;
let mut acc = Vec::new(); let mut acc = Vec::new();
let diagnostic = sess.dcx(); let dcx = sess.dcx();
if let Some(items) = attr.meta_item_list() { if let Some(items) = attr.meta_item_list() {
for item in items { for item in items {
@ -958,7 +969,7 @@ pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
sym::simd => Some(ReprSimd), sym::simd => Some(ReprSimd),
sym::transparent => Some(ReprTransparent), sym::transparent => Some(ReprTransparent),
sym::align => { sym::align => {
sess.emit_err(session_diagnostics::InvalidReprAlignNeedArg { sess.dcx().emit_err(session_diagnostics::InvalidReprAlignNeedArg {
span: item.span(), span: item.span(),
}); });
recognised = true; recognised = true;
@ -989,13 +1000,13 @@ pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
|| int_type_of_word(name).is_some() || int_type_of_word(name).is_some()
{ {
recognised = true; recognised = true;
sess.emit_err(session_diagnostics::InvalidReprHintNoParen { sess.dcx().emit_err(session_diagnostics::InvalidReprHintNoParen {
span: item.span(), span: item.span(),
name: name.to_ident_string(), name: name.to_ident_string(),
}); });
} }
if let Some(literal_error) = literal_error { if let Some(literal_error) = literal_error {
sess.emit_err(session_diagnostics::InvalidReprGeneric { sess.dcx().emit_err(session_diagnostics::InvalidReprGeneric {
span: item.span(), span: item.span(),
repr_arg: name.to_ident_string(), repr_arg: name.to_ident_string(),
error_part: literal_error, error_part: literal_error,
@ -1007,7 +1018,7 @@ pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
if meta_item.has_name(sym::align) || meta_item.has_name(sym::packed) { if meta_item.has_name(sym::align) || meta_item.has_name(sym::packed) {
let name = meta_item.name_or_empty().to_ident_string(); let name = meta_item.name_or_empty().to_ident_string();
recognised = true; recognised = true;
sess.emit_err(session_diagnostics::IncorrectReprFormatGeneric { sess.dcx().emit_err(session_diagnostics::IncorrectReprFormatGeneric {
span: item.span(), span: item.span(),
repr_arg: &name, repr_arg: &name,
cause: IncorrectReprFormatGenericCause::from_lit_kind( cause: IncorrectReprFormatGenericCause::from_lit_kind(
@ -1022,7 +1033,7 @@ pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
) || int_type_of_word(meta_item.name_or_empty()).is_some() ) || int_type_of_word(meta_item.name_or_empty()).is_some()
{ {
recognised = true; recognised = true;
sess.emit_err(session_diagnostics::InvalidReprHintNoValue { sess.dcx().emit_err(session_diagnostics::InvalidReprHintNoValue {
span: meta_item.span, span: meta_item.span,
name: meta_item.name_or_empty().to_ident_string(), name: meta_item.name_or_empty().to_ident_string(),
}); });
@ -1031,12 +1042,14 @@ pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
MetaItemKind::List(_) => { MetaItemKind::List(_) => {
if meta_item.has_name(sym::align) { if meta_item.has_name(sym::align) {
recognised = true; recognised = true;
sess.emit_err(session_diagnostics::IncorrectReprFormatAlignOneArg { sess.dcx().emit_err(
span: meta_item.span, session_diagnostics::IncorrectReprFormatAlignOneArg {
}); span: meta_item.span,
},
);
} else if meta_item.has_name(sym::packed) { } else if meta_item.has_name(sym::packed) {
recognised = true; recognised = true;
sess.emit_err( sess.dcx().emit_err(
session_diagnostics::IncorrectReprFormatPackedOneOrZeroArg { session_diagnostics::IncorrectReprFormatPackedOneOrZeroArg {
span: meta_item.span, span: meta_item.span,
}, },
@ -1047,7 +1060,7 @@ pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
) || int_type_of_word(meta_item.name_or_empty()).is_some() ) || int_type_of_word(meta_item.name_or_empty()).is_some()
{ {
recognised = true; recognised = true;
sess.emit_err(session_diagnostics::InvalidReprHintNoParen { sess.dcx().emit_err(session_diagnostics::InvalidReprHintNoParen {
span: meta_item.span, span: meta_item.span,
name: meta_item.name_or_empty().to_ident_string(), name: meta_item.name_or_empty().to_ident_string(),
}); });
@ -1062,7 +1075,7 @@ pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
// (e.g. if we only pretty-print the source), so we have to gate // (e.g. if we only pretty-print the source), so we have to gate
// the `span_delayed_bug` call as follows: // the `span_delayed_bug` call as follows:
if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) { if sess.opts.pretty.map_or(true, |pp| pp.needs_analysis()) {
diagnostic.span_delayed_bug(item.span(), "unrecognized representation hint"); dcx.span_delayed_bug(item.span(), "unrecognized representation hint");
} }
} }
} }
@ -1149,7 +1162,7 @@ fn allow_unstable<'a>(
let list = attrs let list = attrs
.filter_map(move |attr| { .filter_map(move |attr| {
attr.meta_item_list().or_else(|| { attr.meta_item_list().or_else(|| {
sess.emit_err(session_diagnostics::ExpectsFeatureList { sess.dcx().emit_err(session_diagnostics::ExpectsFeatureList {
span: attr.span, span: attr.span,
name: symbol.to_ident_string(), name: symbol.to_ident_string(),
}); });
@ -1161,7 +1174,7 @@ fn allow_unstable<'a>(
list.into_iter().filter_map(move |it| { list.into_iter().filter_map(move |it| {
let name = it.ident().map(|ident| ident.name); let name = it.ident().map(|ident| ident.name);
if name.is_none() { if name.is_none() {
sess.emit_err(session_diagnostics::ExpectsFeatures { sess.dcx().emit_err(session_diagnostics::ExpectsFeatures {
span: it.span(), span: it.span(),
name: symbol.to_ident_string(), name: symbol.to_ident_string(),
}); });

View file

@ -1,10 +1,12 @@
use rustc_errors::{ use rustc_errors::{struct_span_err, DiagCtxt, DiagnosticBuilder};
struct_span_err, DiagnosticBuilder, DiagnosticId, DiagnosticMessage, MultiSpan,
};
use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::Span; use rustc_span::Span;
impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> { impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
pub fn dcx(&self) -> &'tcx DiagCtxt {
self.infcx.dcx()
}
pub(crate) fn cannot_move_when_borrowed( pub(crate) fn cannot_move_when_borrowed(
&self, &self,
span: Span, span: Span,
@ -13,7 +15,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
borrow_place: &str, borrow_place: &str,
value_place: &str, value_place: &str,
) -> DiagnosticBuilder<'tcx> { ) -> DiagnosticBuilder<'tcx> {
self.infcx.tcx.sess.create_err(crate::session_diagnostics::MoveBorrow { self.dcx().create_err(crate::session_diagnostics::MoveBorrow {
place, place,
span, span,
borrow_place, borrow_place,
@ -30,7 +32,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
borrow_desc: &str, borrow_desc: &str,
) -> DiagnosticBuilder<'tcx> { ) -> DiagnosticBuilder<'tcx> {
let mut err = struct_span_err!( let mut err = struct_span_err!(
self, self.dcx(),
span, span,
E0503, E0503,
"cannot use {} because it was mutably borrowed", "cannot use {} because it was mutably borrowed",
@ -53,7 +55,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
) -> DiagnosticBuilder<'tcx> { ) -> DiagnosticBuilder<'tcx> {
let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {msg})") }; let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {msg})") };
let mut err = struct_span_err!( let mut err = struct_span_err!(
self, self.dcx(),
new_loan_span, new_loan_span,
E0499, E0499,
"cannot borrow {}{} as mutable more than once at a time", "cannot borrow {}{} as mutable more than once at a time",
@ -99,7 +101,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
old_load_end_span: Option<Span>, old_load_end_span: Option<Span>,
) -> DiagnosticBuilder<'tcx> { ) -> DiagnosticBuilder<'tcx> {
let mut err = struct_span_err!( let mut err = struct_span_err!(
self, self.dcx(),
new_loan_span, new_loan_span,
E0524, E0524,
"two closures require unique access to {} at the same time", "two closures require unique access to {} at the same time",
@ -132,7 +134,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
previous_end_span: Option<Span>, previous_end_span: Option<Span>,
) -> DiagnosticBuilder<'cx> { ) -> DiagnosticBuilder<'cx> {
let mut err = struct_span_err!( let mut err = struct_span_err!(
self, self.dcx(),
new_loan_span, new_loan_span,
E0500, E0500,
"closure requires unique access to {} but {} is already borrowed{}", "closure requires unique access to {} but {} is already borrowed{}",
@ -164,7 +166,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
second_borrow_desc: &str, second_borrow_desc: &str,
) -> DiagnosticBuilder<'cx> { ) -> DiagnosticBuilder<'cx> {
let mut err = struct_span_err!( let mut err = struct_span_err!(
self, self.dcx(),
new_loan_span, new_loan_span,
E0501, E0501,
"cannot borrow {}{} as {} because previous closure requires unique access", "cannot borrow {}{} as {} because previous closure requires unique access",
@ -197,7 +199,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
) -> DiagnosticBuilder<'cx> { ) -> DiagnosticBuilder<'cx> {
let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {msg})") }; let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {msg})") };
let mut err = struct_span_err!( let mut err = struct_span_err!(
self, self.dcx(),
span, span,
E0502, E0502,
"cannot borrow {}{} as {} because {} is also borrowed as {}{}", "cannot borrow {}{} as {} because {} is also borrowed as {}{}",
@ -237,7 +239,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
desc: &str, desc: &str,
) -> DiagnosticBuilder<'cx> { ) -> DiagnosticBuilder<'cx> {
let mut err = struct_span_err!( let mut err = struct_span_err!(
self, self.dcx(),
span, span,
E0506, E0506,
"cannot assign to {} because it is borrowed", "cannot assign to {} because it is borrowed",
@ -256,11 +258,11 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
is_arg: bool, is_arg: bool,
) -> DiagnosticBuilder<'cx> { ) -> DiagnosticBuilder<'cx> {
let msg = if is_arg { "to immutable argument" } else { "twice to immutable variable" }; let msg = if is_arg { "to immutable argument" } else { "twice to immutable variable" };
struct_span_err!(self, span, E0384, "cannot assign {} {}", msg, desc) struct_span_err!(self.dcx(), span, E0384, "cannot assign {} {}", msg, desc)
} }
pub(crate) fn cannot_assign(&self, span: Span, desc: &str) -> DiagnosticBuilder<'tcx> { pub(crate) fn cannot_assign(&self, span: Span, desc: &str) -> DiagnosticBuilder<'tcx> {
struct_span_err!(self, span, E0594, "cannot assign to {}", desc) struct_span_err!(self.dcx(), span, E0594, "cannot assign to {}", desc)
} }
pub(crate) fn cannot_move_out_of( pub(crate) fn cannot_move_out_of(
@ -268,7 +270,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
move_from_span: Span, move_from_span: Span,
move_from_desc: &str, move_from_desc: &str,
) -> DiagnosticBuilder<'cx> { ) -> DiagnosticBuilder<'cx> {
struct_span_err!(self, move_from_span, E0507, "cannot move out of {}", move_from_desc) struct_span_err!(self.dcx(), move_from_span, E0507, "cannot move out of {}", move_from_desc)
} }
/// Signal an error due to an attempt to move out of the interior /// Signal an error due to an attempt to move out of the interior
@ -286,7 +288,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
_ => span_bug!(move_from_span, "this path should not cause illegal move"), _ => span_bug!(move_from_span, "this path should not cause illegal move"),
}; };
let mut err = struct_span_err!( let mut err = struct_span_err!(
self, self.dcx(),
move_from_span, move_from_span,
E0508, E0508,
"cannot move out of type `{}`, a non-copy {}", "cannot move out of type `{}`, a non-copy {}",
@ -303,7 +305,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
container_ty: Ty<'_>, container_ty: Ty<'_>,
) -> DiagnosticBuilder<'cx> { ) -> DiagnosticBuilder<'cx> {
let mut err = struct_span_err!( let mut err = struct_span_err!(
self, self.dcx(),
move_from_span, move_from_span,
E0509, E0509,
"cannot move out of type `{}`, which implements the `Drop` trait", "cannot move out of type `{}`, which implements the `Drop` trait",
@ -323,7 +325,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
let moved_path = moved_path.map(|mp| format!(": `{mp}`")).unwrap_or_default(); let moved_path = moved_path.map(|mp| format!(": `{mp}`")).unwrap_or_default();
struct_span_err!( struct_span_err!(
self, self.dcx(),
use_span, use_span,
E0382, E0382,
"{} of {}moved value{}", "{} of {}moved value{}",
@ -339,7 +341,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
path: &str, path: &str,
reason: &str, reason: &str,
) -> DiagnosticBuilder<'tcx> { ) -> DiagnosticBuilder<'tcx> {
struct_span_err!(self, span, E0596, "cannot borrow {} as mutable{}", path, reason,) struct_span_err!(self.dcx(), span, E0596, "cannot borrow {} as mutable{}", path, reason)
} }
pub(crate) fn cannot_mutate_in_immutable_section( pub(crate) fn cannot_mutate_in_immutable_section(
@ -351,7 +353,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
action: &str, action: &str,
) -> DiagnosticBuilder<'tcx> { ) -> DiagnosticBuilder<'tcx> {
let mut err = struct_span_err!( let mut err = struct_span_err!(
self, self.dcx(),
mutate_span, mutate_span,
E0510, E0510,
"cannot {} {} in {}", "cannot {} {} in {}",
@ -371,7 +373,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
) -> DiagnosticBuilder<'tcx> { ) -> DiagnosticBuilder<'tcx> {
let coroutine_kind = self.body.coroutine.as_ref().unwrap().coroutine_kind; let coroutine_kind = self.body.coroutine.as_ref().unwrap().coroutine_kind;
let mut err = struct_span_err!( let mut err = struct_span_err!(
self, self.dcx(),
span, span,
E0626, E0626,
"borrow may still be in use when {coroutine_kind:#} yields", "borrow may still be in use when {coroutine_kind:#} yields",
@ -385,7 +387,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
borrow_span: Span, borrow_span: Span,
) -> DiagnosticBuilder<'tcx> { ) -> DiagnosticBuilder<'tcx> {
struct_span_err!( struct_span_err!(
self, self.dcx(),
borrow_span, borrow_span,
E0713, E0713,
"borrow may still be in use when destructor runs", "borrow may still be in use when destructor runs",
@ -397,7 +399,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
span: Span, span: Span,
path: &str, path: &str,
) -> DiagnosticBuilder<'tcx> { ) -> DiagnosticBuilder<'tcx> {
struct_span_err!(self, span, E0597, "{} does not live long enough", path,) struct_span_err!(self.dcx(), span, E0597, "{} does not live long enough", path,)
} }
pub(crate) fn cannot_return_reference_to_local( pub(crate) fn cannot_return_reference_to_local(
@ -408,7 +410,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
path_desc: &str, path_desc: &str,
) -> DiagnosticBuilder<'tcx> { ) -> DiagnosticBuilder<'tcx> {
let mut err = struct_span_err!( let mut err = struct_span_err!(
self, self.dcx(),
span, span,
E0515, E0515,
"cannot {RETURN} {REFERENCE} {LOCAL}", "cannot {RETURN} {REFERENCE} {LOCAL}",
@ -434,7 +436,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
scope: &str, scope: &str,
) -> DiagnosticBuilder<'tcx> { ) -> DiagnosticBuilder<'tcx> {
let mut err = struct_span_err!( let mut err = struct_span_err!(
self, self.dcx(),
closure_span, closure_span,
E0373, E0373,
"{closure_kind} may outlive the current {scope}, but it borrows {borrowed_path}, \ "{closure_kind} may outlive the current {scope}, but it borrows {borrowed_path}, \
@ -449,25 +451,19 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
&self, &self,
span: Span, span: Span,
) -> DiagnosticBuilder<'tcx> { ) -> DiagnosticBuilder<'tcx> {
struct_span_err!(self, span, E0712, "thread-local variable borrowed past end of function",) struct_span_err!(
self.dcx(),
span,
E0712,
"thread-local variable borrowed past end of function",
)
} }
pub(crate) fn temporary_value_borrowed_for_too_long( pub(crate) fn temporary_value_borrowed_for_too_long(
&self, &self,
span: Span, span: Span,
) -> DiagnosticBuilder<'tcx> { ) -> DiagnosticBuilder<'tcx> {
struct_span_err!(self, span, E0716, "temporary value dropped while borrowed",) struct_span_err!(self.dcx(), span, E0716, "temporary value dropped while borrowed",)
}
#[rustc_lint_diagnostics]
#[track_caller]
pub(crate) fn struct_span_err_with_code<S: Into<MultiSpan>>(
&self,
sp: S,
msg: impl Into<DiagnosticMessage>,
code: DiagnosticId,
) -> DiagnosticBuilder<'tcx> {
self.infcx.tcx.sess.struct_span_err_with_code(sp, msg, code)
} }
} }
@ -477,7 +473,7 @@ pub(crate) fn borrowed_data_escapes_closure<'tcx>(
escapes_from: &str, escapes_from: &str,
) -> DiagnosticBuilder<'tcx> { ) -> DiagnosticBuilder<'tcx> {
struct_span_err!( struct_span_err!(
tcx.sess, tcx.dcx(),
escape_span, escape_span,
E0521, E0521,
"borrowed data escapes outside of {}", "borrowed data escapes outside of {}",

View file

@ -77,7 +77,7 @@ impl<'tcx> UniverseInfo<'tcx> {
// up in the existing UI tests. Consider investigating this // up in the existing UI tests. Consider investigating this
// some more. // some more.
mbcx.buffer_error( mbcx.buffer_error(
mbcx.infcx.tcx.sess.create_err(HigherRankedSubtypeError { span: cause.span }), mbcx.dcx().create_err(HigherRankedSubtypeError { span: cause.span }),
); );
} }
} }
@ -221,7 +221,7 @@ struct PredicateQuery<'tcx> {
impl<'tcx> TypeOpInfo<'tcx> for PredicateQuery<'tcx> { impl<'tcx> TypeOpInfo<'tcx> for PredicateQuery<'tcx> {
fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> DiagnosticBuilder<'tcx> {
tcx.sess.create_err(HigherRankedLifetimeError { tcx.dcx().create_err(HigherRankedLifetimeError {
cause: Some(HigherRankedErrorCause::CouldNotProve { cause: Some(HigherRankedErrorCause::CouldNotProve {
predicate: self.canonical_query.value.value.predicate.to_string(), predicate: self.canonical_query.value.value.predicate.to_string(),
}), }),
@ -258,7 +258,7 @@ where
T: Copy + fmt::Display + TypeFoldable<TyCtxt<'tcx>> + 'tcx, T: Copy + fmt::Display + TypeFoldable<TyCtxt<'tcx>> + 'tcx,
{ {
fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> DiagnosticBuilder<'tcx> {
tcx.sess.create_err(HigherRankedLifetimeError { tcx.dcx().create_err(HigherRankedLifetimeError {
cause: Some(HigherRankedErrorCause::CouldNotNormalize { cause: Some(HigherRankedErrorCause::CouldNotNormalize {
value: self.canonical_query.value.value.value.to_string(), value: self.canonical_query.value.value.value.to_string(),
}), }),
@ -303,7 +303,7 @@ impl<'tcx> TypeOpInfo<'tcx> for AscribeUserTypeQuery<'tcx> {
fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> DiagnosticBuilder<'tcx> {
// FIXME: This error message isn't great, but it doesn't show up in the existing UI tests, // FIXME: This error message isn't great, but it doesn't show up in the existing UI tests,
// and is only the fallback when the nice error fails. Consider improving this some more. // and is only the fallback when the nice error fails. Consider improving this some more.
tcx.sess.create_err(HigherRankedLifetimeError { cause: None, span }) tcx.dcx().create_err(HigherRankedLifetimeError { cause: None, span })
} }
fn base_universe(&self) -> ty::UniverseIndex { fn base_universe(&self) -> ty::UniverseIndex {
@ -329,7 +329,7 @@ impl<'tcx> TypeOpInfo<'tcx> for crate::type_check::InstantiateOpaqueType<'tcx> {
fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> DiagnosticBuilder<'tcx> { fn fallback_error(&self, tcx: TyCtxt<'tcx>, span: Span) -> DiagnosticBuilder<'tcx> {
// FIXME: This error message isn't great, but it doesn't show up in the existing UI tests, // FIXME: This error message isn't great, but it doesn't show up in the existing UI tests,
// and is only the fallback when the nice error fails. Consider improving this some more. // and is only the fallback when the nice error fails. Consider improving this some more.
tcx.sess.create_err(HigherRankedLifetimeError { cause: None, span }) tcx.dcx().create_err(HigherRankedLifetimeError { cause: None, span })
} }
fn base_universe(&self) -> ty::UniverseIndex { fn base_universe(&self) -> ty::UniverseIndex {

View file

@ -551,7 +551,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
let used = desired_action.as_general_verb_in_past_tense(); let used = desired_action.as_general_verb_in_past_tense();
let mut err = let mut err =
struct_span_err!(self, span, E0381, "{used} binding {desc}{isnt_initialized}"); struct_span_err!(self.dcx(), span, E0381, "{used} binding {desc}{isnt_initialized}");
use_spans.var_path_only_subdiag(&mut err, desired_action); use_spans.var_path_only_subdiag(&mut err, desired_action);
if let InitializationRequiringAction::PartialAssignment if let InitializationRequiringAction::PartialAssignment
@ -1136,7 +1136,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
}); });
} else { } else {
issued_spans.var_subdiag( issued_spans.var_subdiag(
Some(self.infcx.tcx.sess.dcx()), Some(self.dcx()),
&mut err, &mut err,
Some(issued_borrow.kind), Some(issued_borrow.kind),
|kind, var_span| { |kind, var_span| {
@ -1153,7 +1153,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
); );
borrow_spans.var_subdiag( borrow_spans.var_subdiag(
Some(self.infcx.tcx.sess.dcx()), Some(self.dcx()),
&mut err, &mut err,
Some(gen_borrow_kind), Some(gen_borrow_kind),
|kind, var_span| { |kind, var_span| {

View file

@ -124,7 +124,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
let did = did.expect_local(); let did = did.expect_local();
if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) { if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) {
diag.eager_subdiagnostic( diag.eager_subdiagnostic(
self.infcx.tcx.sess.dcx(), self.dcx(),
OnClosureNote::InvokedTwice { OnClosureNote::InvokedTwice {
place_name: &ty::place_to_string_for_capture( place_name: &ty::place_to_string_for_capture(
self.infcx.tcx, self.infcx.tcx,
@ -146,7 +146,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
let did = did.expect_local(); let did = did.expect_local();
if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) { if let Some((span, hir_place)) = self.infcx.tcx.closure_kind_origin(did) {
diag.eager_subdiagnostic( diag.eager_subdiagnostic(
self.infcx.tcx.sess.dcx(), self.dcx(),
OnClosureNote::MovedTwice { OnClosureNote::MovedTwice {
place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place), place_name: &ty::place_to_string_for_capture(self.infcx.tcx, hir_place),
span: *span, span: *span,
@ -1150,7 +1150,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
&& self.infcx.can_eq(self.param_env, ty, self_ty) && self.infcx.can_eq(self.param_env, ty, self_ty)
{ {
err.eager_subdiagnostic( err.eager_subdiagnostic(
self.infcx.tcx.sess.dcx(), self.dcx(),
CaptureReasonSuggest::FreshReborrow { CaptureReasonSuggest::FreshReborrow {
span: move_span.shrink_to_hi(), span: move_span.shrink_to_hi(),
}, },

View file

@ -206,7 +206,7 @@ impl OutlivesSuggestionBuilder {
// If there is exactly one suggestable constraints, then just suggest it. Otherwise, emit a // If there is exactly one suggestable constraints, then just suggest it. Otherwise, emit a
// list of diagnostics. // list of diagnostics.
let mut diag = if suggested.len() == 1 { let mut diag = if suggested.len() == 1 {
mbcx.infcx.tcx.sess.dcx().struct_help(match suggested.last().unwrap() { mbcx.dcx().struct_help(match suggested.last().unwrap() {
SuggestedConstraint::Outlives(a, bs) => { SuggestedConstraint::Outlives(a, bs) => {
let bs: SmallVec<[String; 2]> = bs.iter().map(|r| r.to_string()).collect(); let bs: SmallVec<[String; 2]> = bs.iter().map(|r| r.to_string()).collect();
format!("add bound `{a}: {}`", bs.join(" + ")) format!("add bound `{a}: {}`", bs.join(" + "))
@ -222,7 +222,6 @@ impl OutlivesSuggestionBuilder {
let mut diag = mbcx let mut diag = mbcx
.infcx .infcx
.tcx .tcx
.sess
.dcx() .dcx()
.struct_help("the following changes may resolve your lifetime errors"); .struct_help("the following changes may resolve your lifetime errors");

View file

@ -84,7 +84,7 @@ impl<'tcx> RegionErrors<'tcx> {
#[track_caller] #[track_caller]
pub fn push(&mut self, val: impl Into<RegionErrorKind<'tcx>>) { pub fn push(&mut self, val: impl Into<RegionErrorKind<'tcx>>) {
let val = val.into(); let val = val.into();
self.1.sess.span_delayed_bug(DUMMY_SP, format!("{val:?}")); self.1.sess.dcx().span_delayed_bug(DUMMY_SP, format!("{val:?}"));
self.0.push(val); self.0.push(val);
} }
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
@ -327,11 +327,10 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
// to report it; we could probably handle it by // to report it; we could probably handle it by
// iterating over the universal regions and reporting // iterating over the universal regions and reporting
// an error that multiple bounds are required. // an error that multiple bounds are required.
let mut diag = let mut diag = self.dcx().create_err(GenericDoesNotLiveLongEnough {
self.infcx.tcx.sess.create_err(GenericDoesNotLiveLongEnough { kind: type_test.generic_kind.to_string(),
kind: type_test.generic_kind.to_string(), span: type_test_span,
span: type_test_span, });
});
// Add notes and suggestions for the case of 'static lifetime // Add notes and suggestions for the case of 'static lifetime
// implied but not specified when a generic associated types // implied but not specified when a generic associated types
@ -596,7 +595,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
}, },
}; };
let mut diag = self.infcx.tcx.sess.create_err(err); let mut diag = self.dcx().create_err(err);
if let ReturnConstraint::ClosureUpvar(upvar_field) = kind { if let ReturnConstraint::ClosureUpvar(upvar_field) = kind {
let def_id = match self.regioncx.universal_regions().defining_ty { let def_id = match self.regioncx.universal_regions().defining_ty {
@ -758,7 +757,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
let mir_def_name = self.infcx.tcx.def_descr(self.mir_def_id().to_def_id()); let mir_def_name = self.infcx.tcx.def_descr(self.mir_def_id().to_def_id());
let err = LifetimeOutliveErr { span: *span }; let err = LifetimeOutliveErr { span: *span };
let mut diag = self.infcx.tcx.sess.create_err(err); let mut diag = self.dcx().create_err(err);
// In certain scenarios, such as the one described in issue #118021, // In certain scenarios, such as the one described in issue #118021,
// we might encounter a lifetime that cannot be named. // we might encounter a lifetime that cannot be named.

View file

@ -620,7 +620,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {
) => { ) => {
// HIR lowering sometimes doesn't catch this in erroneous // HIR lowering sometimes doesn't catch this in erroneous
// programs, so we need to use span_delayed_bug here. See #82126. // programs, so we need to use span_delayed_bug here. See #82126.
self.infcx.tcx.sess.span_delayed_bug( self.dcx().span_delayed_bug(
hir_arg.span(), hir_arg.span(),
format!("unmatched arg and hir arg: found {kind:?} vs {hir_arg:?}"), format!("unmatched arg and hir arg: found {kind:?} vs {hir_arg:?}"),
); );

View file

@ -2134,7 +2134,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
// dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug` // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug`
// enabled. We don't want to ICE for that case, as other errors will have // enabled. We don't want to ICE for that case, as other errors will have
// been emitted (#52262). // been emitted (#52262).
self.infcx.tcx.sess.span_delayed_bug( self.dcx().span_delayed_bug(
span, span,
format!( format!(
"Accessing `{place:?}` with the kind `{kind:?}` shouldn't be possible", "Accessing `{place:?}` with the kind `{kind:?}` shouldn't be possible",
@ -2428,7 +2428,7 @@ mod error {
pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_>) { pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_>) {
if let None = self.tainted_by_errors { if let None = self.tainted_by_errors {
self.tainted_by_errors = Some(self.tcx.sess.span_delayed_bug( self.tainted_by_errors = Some(self.tcx.dcx().span_delayed_bug(
t.span.clone_ignoring_labels(), t.span.clone_ignoring_labels(),
"diagnostic buffered but not emitted", "diagnostic buffered but not emitted",
)) ))
@ -2497,8 +2497,9 @@ mod error {
if !self.errors.buffered.is_empty() { if !self.errors.buffered.is_empty() {
self.errors.buffered.sort_by_key(|diag| diag.sort_span); self.errors.buffered.sort_by_key(|diag| diag.sort_span);
let dcx = self.dcx();
for diag in self.errors.buffered.drain(..) { for diag in self.errors.buffered.drain(..) {
self.infcx.tcx.sess.dcx().emit_diagnostic(diag); dcx.emit_diagnostic(diag);
} }
} }

View file

@ -187,7 +187,7 @@ pub(crate) fn compute_regions<'cx, 'tcx>(
if !nll_errors.is_empty() { if !nll_errors.is_empty() {
// Suppress unhelpful extra errors in `infer_opaque_types`. // Suppress unhelpful extra errors in `infer_opaque_types`.
infcx.set_tainted_by_errors(infcx.tcx.sess.span_delayed_bug( infcx.set_tainted_by_errors(infcx.dcx().span_delayed_bug(
body.span, body.span,
"`compute_regions` tainted `infcx` with errors but did not emit any errors", "`compute_regions` tainted `infcx` with errors but did not emit any errors",
)); ));
@ -280,7 +280,7 @@ pub(super) fn dump_annotation<'tcx>(
let def_span = tcx.def_span(body.source.def_id()); let def_span = tcx.def_span(body.source.def_id());
let mut err = if let Some(closure_region_requirements) = closure_region_requirements { let mut err = if let Some(closure_region_requirements) = closure_region_requirements {
let mut err = tcx.sess.dcx().struct_span_note(def_span, "external requirements"); let mut err = tcx.dcx().struct_span_note(def_span, "external requirements");
regioncx.annotate(tcx, &mut err); regioncx.annotate(tcx, &mut err);
@ -299,7 +299,7 @@ pub(super) fn dump_annotation<'tcx>(
err err
} else { } else {
let mut err = tcx.sess.dcx().struct_span_note(def_span, "no external requirements"); let mut err = tcx.dcx().struct_span_note(def_span, "no external requirements");
regioncx.annotate(tcx, &mut err); regioncx.annotate(tcx, &mut err);
err err

View file

@ -402,7 +402,7 @@ fn check_opaque_type_parameter_valid(
let opaque_param = opaque_generics.param_at(i, tcx); let opaque_param = opaque_generics.param_at(i, tcx);
let kind = opaque_param.kind.descr(); let kind = opaque_param.kind.descr();
return Err(tcx.sess.emit_err(NonGenericOpaqueTypeParam { return Err(tcx.dcx().emit_err(NonGenericOpaqueTypeParam {
ty: arg, ty: arg,
kind, kind,
span, span,
@ -419,7 +419,7 @@ fn check_opaque_type_parameter_valid(
.map(|i| tcx.def_span(opaque_generics.param_at(i, tcx).def_id)) .map(|i| tcx.def_span(opaque_generics.param_at(i, tcx).def_id))
.collect(); .collect();
return Err(tcx return Err(tcx
.sess .dcx()
.struct_span_err(span, "non-defining opaque type use in defining scope") .struct_span_err(span, "non-defining opaque type use in defining scope")
.span_note(spans, format!("{descr} used multiple times")) .span_note(spans, format!("{descr} used multiple times"))
.emit()); .emit());

View file

@ -76,7 +76,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
for (argument_index, &normalized_input_ty) in normalized_input_tys.iter().enumerate() { for (argument_index, &normalized_input_ty) in normalized_input_tys.iter().enumerate() {
if argument_index + 1 >= body.local_decls.len() { if argument_index + 1 >= body.local_decls.len() {
self.tcx() self.tcx()
.sess .dcx()
.span_delayed_bug(body.span, "found more normalized_input_ty than local_decls"); .span_delayed_bug(body.span, "found more normalized_input_ty than local_decls");
break; break;
} }
@ -104,7 +104,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
// outside of a coroutine and return an `impl Trait`, so emit a span_delayed_bug // outside of a coroutine and return an `impl Trait`, so emit a span_delayed_bug
// because we don't want to panic in an assert here if we've already got errors. // because we don't want to panic in an assert here if we've already got errors.
if body.yield_ty().is_some() != universal_regions.yield_ty.is_some() { if body.yield_ty().is_some() != universal_regions.yield_ty.is_some() {
self.tcx().sess.span_delayed_bug( self.tcx().dcx().span_delayed_bug(
body.span, body.span,
format!( format!(
"Expected body to have yield_ty ({:?}) iff we have a UR yield_ty ({:?})", "Expected body to have yield_ty ({:?}) iff we have a UR yield_ty ({:?})",

View file

@ -224,7 +224,7 @@ pub(crate) fn type_check<'mir, 'tcx>(
let mut hidden_type = infcx.resolve_vars_if_possible(decl.hidden_type); let mut hidden_type = infcx.resolve_vars_if_possible(decl.hidden_type);
trace!("finalized opaque type {:?} to {:#?}", opaque_type_key, hidden_type.ty.kind()); trace!("finalized opaque type {:?} to {:#?}", opaque_type_key, hidden_type.ty.kind());
if hidden_type.has_non_region_infer() { if hidden_type.has_non_region_infer() {
let reported = infcx.tcx.sess.span_delayed_bug( let reported = infcx.dcx().span_delayed_bug(
decl.hidden_type.span, decl.hidden_type.span,
format!("could not resolve {:#?}", hidden_type.ty.kind()), format!("could not resolve {:#?}", hidden_type.ty.kind()),
); );
@ -268,7 +268,7 @@ fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: String) {
// We sometimes see MIR failures (notably predicate failures) due to // We sometimes see MIR failures (notably predicate failures) due to
// the fact that we check rvalue sized predicates here. So use `span_delayed_bug` // the fact that we check rvalue sized predicates here. So use `span_delayed_bug`
// to avoid reporting bugs in those cases. // to avoid reporting bugs in those cases.
tcx.sess.dcx().span_delayed_bug(span, msg); tcx.dcx().span_delayed_bug(span, msg);
} }
enum FieldAccessError { enum FieldAccessError {
@ -1067,7 +1067,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
); );
if result.is_err() { if result.is_err() {
self.infcx.tcx.sess.span_delayed_bug( self.infcx.dcx().span_delayed_bug(
self.body.span, self.body.span,
"failed re-defining predefined opaques in mir typeck", "failed re-defining predefined opaques in mir typeck",
); );
@ -1573,7 +1573,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
sym::simd_shuffle => { sym::simd_shuffle => {
if !matches!(args[2], Operand::Constant(_)) { if !matches!(args[2], Operand::Constant(_)) {
self.tcx() self.tcx()
.sess .dcx()
.emit_err(SimdShuffleLastConst { span: term.source_info.span }); .emit_err(SimdShuffleLastConst { span: term.source_info.span });
} }
} }
@ -1752,7 +1752,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
// While this is located in `nll::typeck` this error is not // While this is located in `nll::typeck` this error is not
// an NLL error, it's a required check to prevent creation // an NLL error, it's a required check to prevent creation
// of unsized rvalues in a call expression. // of unsized rvalues in a call expression.
self.tcx().sess.emit_err(MoveUnsized { ty, span }); self.tcx().dcx().emit_err(MoveUnsized { ty, span });
} }
} }
} }

View file

@ -31,7 +31,7 @@ pub fn expand(
{ {
(item, true, ecx.with_def_site_ctxt(fn_kind.sig.span)) (item, true, ecx.with_def_site_ctxt(fn_kind.sig.span))
} else { } else {
ecx.sess.dcx().emit_err(errors::AllocErrorMustBeFn { span: item.span() }); ecx.dcx().emit_err(errors::AllocErrorMustBeFn { span: item.span() });
return vec![orig_item]; return vec![orig_item];
}; };

View file

@ -422,7 +422,7 @@ fn parse_reg<'a>(
ast::InlineAsmRegOrRegClass::Reg(symbol) ast::InlineAsmRegOrRegClass::Reg(symbol)
} }
_ => { _ => {
return Err(p.sess.create_err(errors::ExpectedRegisterClassOrExplicitRegister { return Err(p.dcx().create_err(errors::ExpectedRegisterClassOrExplicitRegister {
span: p.token.span, span: p.token.span,
})); }));
} }
@ -541,7 +541,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
let err = parser.errors.remove(0); let err = parser.errors.remove(0);
let err_sp = template_span.from_inner(InnerSpan::new(err.span.start, err.span.end)); let err_sp = template_span.from_inner(InnerSpan::new(err.span.start, err.span.end));
let msg = format!("invalid asm template string: {}", err.description); let msg = format!("invalid asm template string: {}", err.description);
let mut e = ecx.struct_span_err(err_sp, msg); let mut e = ecx.dcx().struct_span_err(err_sp, msg);
e.span_label(err_sp, err.label + " in asm template string"); e.span_label(err_sp, err.label + " in asm template string");
if let Some(note) = err.note { if let Some(note) = err.note {
e.note(note); e.note(note);
@ -575,7 +575,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
|| args.reg_args.contains(idx) || args.reg_args.contains(idx)
{ {
let msg = format!("invalid reference to argument at index {idx}"); let msg = format!("invalid reference to argument at index {idx}");
let mut err = ecx.struct_span_err(span, msg); let mut err = ecx.dcx().struct_span_err(span, msg);
err.span_label(span, "from here"); err.span_label(span, "from here");
let positional_args = args.operands.len() let positional_args = args.operands.len()
@ -625,12 +625,13 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
None => { None => {
let msg = format!("there is no argument named `{name}`"); let msg = format!("there is no argument named `{name}`");
let span = arg.position_span; let span = arg.position_span;
ecx.struct_span_err( ecx.dcx()
template_span .struct_span_err(
.from_inner(InnerSpan::new(span.start, span.end)), template_span
msg, .from_inner(InnerSpan::new(span.start, span.end)),
) msg,
.emit(); )
.emit();
None None
} }
} }
@ -645,7 +646,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
.ty_span .ty_span
.map(|sp| template_sp.from_inner(InnerSpan::new(sp.start, sp.end))) .map(|sp| template_sp.from_inner(InnerSpan::new(sp.start, sp.end)))
.unwrap_or(template_sp); .unwrap_or(template_sp);
ecx.emit_err(errors::AsmModifierInvalid { span }); ecx.dcx().emit_err(errors::AsmModifierInvalid { span });
modifier = None; modifier = None;
} }
@ -692,7 +693,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
0 => {} 0 => {}
1 => { 1 => {
let (sp, msg) = unused_operands.into_iter().next().unwrap(); let (sp, msg) = unused_operands.into_iter().next().unwrap();
let mut err = ecx.struct_span_err(sp, msg); let mut err = ecx.dcx().struct_span_err(sp, msg);
err.span_label(sp, msg); err.span_label(sp, msg);
err.help(format!( err.help(format!(
"if this argument is intentionally unused, \ "if this argument is intentionally unused, \
@ -701,7 +702,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
err.emit(); err.emit();
} }
_ => { _ => {
let mut err = ecx.struct_span_err( let mut err = ecx.dcx().struct_span_err(
unused_operands.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(), unused_operands.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
"multiple unused asm arguments", "multiple unused asm arguments",
); );

View file

@ -115,7 +115,7 @@ fn parse_assert<'a>(cx: &mut ExtCtxt<'a>, sp: Span, stream: TokenStream) -> PRes
let mut parser = cx.new_parser_from_tts(stream); let mut parser = cx.new_parser_from_tts(stream);
if parser.token == token::Eof { if parser.token == token::Eof {
return Err(cx.create_err(errors::AssertRequiresBoolean { span: sp })); return Err(cx.dcx().create_err(errors::AssertRequiresBoolean { span: sp }));
} }
let cond_expr = parser.parse_expr()?; let cond_expr = parser.parse_expr()?;
@ -128,7 +128,7 @@ fn parse_assert<'a>(cx: &mut ExtCtxt<'a>, sp: Span, stream: TokenStream) -> PRes
// //
// Emit an error about semicolon and suggest removing it. // Emit an error about semicolon and suggest removing it.
if parser.token == token::Semi { if parser.token == token::Semi {
cx.emit_err(errors::AssertRequiresExpression { span: sp, token: parser.token.span }); cx.dcx().emit_err(errors::AssertRequiresExpression { span: sp, token: parser.token.span });
parser.bump(); parser.bump();
} }
@ -141,7 +141,7 @@ fn parse_assert<'a>(cx: &mut ExtCtxt<'a>, sp: Span, stream: TokenStream) -> PRes
let custom_message = let custom_message =
if let token::Literal(token::Lit { kind: token::Str, .. }) = parser.token.kind { if let token::Literal(token::Lit { kind: token::Str, .. }) = parser.token.kind {
let comma = parser.prev_token.span.shrink_to_hi(); let comma = parser.prev_token.span.shrink_to_hi();
cx.emit_err(errors::AssertMissingComma { span: parser.token.span, comma }); cx.dcx().emit_err(errors::AssertMissingComma { span: parser.token.span, comma });
parse_custom_message(&mut parser) parse_custom_message(&mut parser)
} else if parser.eat(&token::Comma) { } else if parser.eat(&token::Comma) {

View file

@ -39,7 +39,7 @@ fn parse_cfg<'a>(cx: &mut ExtCtxt<'a>, span: Span, tts: TokenStream) -> PResult<
let mut p = cx.new_parser_from_tts(tts); let mut p = cx.new_parser_from_tts(tts);
if p.token == token::Eof { if p.token == token::Eof {
return Err(cx.create_err(errors::RequiresCfgPattern { span })); return Err(cx.dcx().create_err(errors::RequiresCfgPattern { span }));
} }
let cfg = p.parse_meta_item()?; let cfg = p.parse_meta_item()?;
@ -47,7 +47,7 @@ fn parse_cfg<'a>(cx: &mut ExtCtxt<'a>, span: Span, tts: TokenStream) -> PResult<
let _ = p.eat(&token::Comma); let _ = p.eat(&token::Comma);
if !p.eat(&token::Eof) { if !p.eat(&token::Eof) {
return Err(cx.create_err(errors::OneCfgPattern { span })); return Err(cx.dcx().create_err(errors::OneCfgPattern { span }));
} }
Ok(cfg) Ok(cfg)

View file

@ -15,18 +15,18 @@ fn validate_input<'a>(ecx: &mut ExtCtxt<'_>, mi: &'a ast::MetaItem) -> Option<&'
match mi.meta_item_list() { match mi.meta_item_list() {
None => {} None => {}
Some([]) => { Some([]) => {
ecx.emit_err(UnspecifiedPath(mi.span)); ecx.dcx().emit_err(UnspecifiedPath(mi.span));
} }
Some([_, .., l]) => { Some([_, .., l]) => {
ecx.emit_err(MultiplePaths(l.span())); ecx.dcx().emit_err(MultiplePaths(l.span()));
} }
Some([nmi]) => match nmi.meta_item() { Some([nmi]) => match nmi.meta_item() {
None => { None => {
ecx.emit_err(LiteralPath(nmi.span())); ecx.dcx().emit_err(LiteralPath(nmi.span()));
} }
Some(mi) => { Some(mi) => {
if !mi.is_word() { if !mi.is_word() {
ecx.emit_err(HasArguments(mi.span)); ecx.dcx().emit_err(HasArguments(mi.span));
} }
return Some(&mi.path); return Some(&mi.path);
} }
@ -61,7 +61,7 @@ impl MultiItemModifier for Expander {
Ok(true) => ExpandResult::Ready(vec![item]), Ok(true) => ExpandResult::Ready(vec![item]),
Ok(false) => ExpandResult::Ready(Vec::new()), Ok(false) => ExpandResult::Ready(Vec::new()),
Err(Indeterminate) if ecx.force_mode => { Err(Indeterminate) if ecx.force_mode => {
ecx.emit_err(errors::CfgAccessibleIndeterminate { span }); ecx.dcx().emit_err(errors::CfgAccessibleIndeterminate { span });
ExpandResult::Ready(vec![item]) ExpandResult::Ready(vec![item])
} }
Err(Indeterminate) => ExpandResult::Retry(item), Err(Indeterminate) => ExpandResult::Retry(item),

View file

@ -18,7 +18,7 @@ pub fn expand_compile_error<'cx>(
reason = "diagnostic message is specified by user" reason = "diagnostic message is specified by user"
)] )]
#[expect(rustc::untranslatable_diagnostic, reason = "diagnostic message is specified by user")] #[expect(rustc::untranslatable_diagnostic, reason = "diagnostic message is specified by user")]
cx.span_err(sp, var.to_string()); cx.dcx().span_err(sp, var.to_string());
DummyResult::any(sp) DummyResult::any(sp)
} }

View file

@ -33,11 +33,11 @@ pub fn expand_concat(
accumulator.push_str(&b.to_string()); accumulator.push_str(&b.to_string());
} }
Ok(ast::LitKind::CStr(..)) => { Ok(ast::LitKind::CStr(..)) => {
cx.emit_err(errors::ConcatCStrLit { span: e.span }); cx.dcx().emit_err(errors::ConcatCStrLit { span: e.span });
has_errors = true; has_errors = true;
} }
Ok(ast::LitKind::Byte(..) | ast::LitKind::ByteStr(..)) => { Ok(ast::LitKind::Byte(..) | ast::LitKind::ByteStr(..)) => {
cx.emit_err(errors::ConcatBytestr { span: e.span }); cx.dcx().emit_err(errors::ConcatBytestr { span: e.span });
has_errors = true; has_errors = true;
} }
Ok(ast::LitKind::Err) => { Ok(ast::LitKind::Err) => {
@ -63,7 +63,7 @@ pub fn expand_concat(
} }
} }
ast::ExprKind::IncludedBytes(..) => { ast::ExprKind::IncludedBytes(..) => {
cx.emit_err(errors::ConcatBytestr { span: e.span }); cx.dcx().emit_err(errors::ConcatBytestr { span: e.span });
} }
ast::ExprKind::Err => { ast::ExprKind::Err => {
has_errors = true; has_errors = true;
@ -75,7 +75,7 @@ pub fn expand_concat(
} }
if !missing_literal.is_empty() { if !missing_literal.is_empty() {
cx.emit_err(errors::ConcatMissingLiteral { spans: missing_literal }); cx.dcx().emit_err(errors::ConcatMissingLiteral { spans: missing_literal });
return DummyResult::any(sp); return DummyResult::any(sp);
} else if has_errors { } else if has_errors {
return DummyResult::any(sp); return DummyResult::any(sp);

View file

@ -17,16 +17,17 @@ fn invalid_type_err(
ConcatBytesInvalid, ConcatBytesInvalidSuggestion, ConcatBytesNonU8, ConcatBytesOob, ConcatBytesInvalid, ConcatBytesInvalidSuggestion, ConcatBytesNonU8, ConcatBytesOob,
}; };
let snippet = cx.sess.source_map().span_to_snippet(span).ok(); let snippet = cx.sess.source_map().span_to_snippet(span).ok();
let dcx = cx.dcx();
match ast::LitKind::from_token_lit(token_lit) { match ast::LitKind::from_token_lit(token_lit) {
Ok(ast::LitKind::CStr(_, _)) => { Ok(ast::LitKind::CStr(_, _)) => {
// Avoid ambiguity in handling of terminal `NUL` by refusing to // Avoid ambiguity in handling of terminal `NUL` by refusing to
// concatenate C string literals as bytes. // concatenate C string literals as bytes.
cx.emit_err(errors::ConcatCStrLit { span: span }); dcx.emit_err(errors::ConcatCStrLit { span: span });
} }
Ok(ast::LitKind::Char(_)) => { Ok(ast::LitKind::Char(_)) => {
let sugg = let sugg =
snippet.map(|snippet| ConcatBytesInvalidSuggestion::CharLit { span, snippet }); snippet.map(|snippet| ConcatBytesInvalidSuggestion::CharLit { span, snippet });
cx.sess.emit_err(ConcatBytesInvalid { span, lit_kind: "character", sugg }); dcx.emit_err(ConcatBytesInvalid { span, lit_kind: "character", sugg });
} }
Ok(ast::LitKind::Str(_, _)) => { Ok(ast::LitKind::Str(_, _)) => {
// suggestion would be invalid if we are nested // suggestion would be invalid if we are nested
@ -35,29 +36,29 @@ fn invalid_type_err(
} else { } else {
None None
}; };
cx.emit_err(ConcatBytesInvalid { span, lit_kind: "string", sugg }); dcx.emit_err(ConcatBytesInvalid { span, lit_kind: "string", sugg });
} }
Ok(ast::LitKind::Float(_, _)) => { Ok(ast::LitKind::Float(_, _)) => {
cx.emit_err(ConcatBytesInvalid { span, lit_kind: "float", sugg: None }); dcx.emit_err(ConcatBytesInvalid { span, lit_kind: "float", sugg: None });
} }
Ok(ast::LitKind::Bool(_)) => { Ok(ast::LitKind::Bool(_)) => {
cx.emit_err(ConcatBytesInvalid { span, lit_kind: "boolean", sugg: None }); dcx.emit_err(ConcatBytesInvalid { span, lit_kind: "boolean", sugg: None });
} }
Ok(ast::LitKind::Err) => {} Ok(ast::LitKind::Err) => {}
Ok(ast::LitKind::Int(_, _)) if !is_nested => { Ok(ast::LitKind::Int(_, _)) if !is_nested => {
let sugg = let sugg =
snippet.map(|snippet| ConcatBytesInvalidSuggestion::IntLit { span: span, snippet }); snippet.map(|snippet| ConcatBytesInvalidSuggestion::IntLit { span: span, snippet });
cx.emit_err(ConcatBytesInvalid { span, lit_kind: "numeric", sugg }); dcx.emit_err(ConcatBytesInvalid { span, lit_kind: "numeric", sugg });
} }
Ok(ast::LitKind::Int( Ok(ast::LitKind::Int(
val, val,
ast::LitIntType::Unsuffixed | ast::LitIntType::Unsigned(ast::UintTy::U8), ast::LitIntType::Unsuffixed | ast::LitIntType::Unsigned(ast::UintTy::U8),
)) => { )) => {
assert!(val > u8::MAX.into()); // must be an error assert!(val > u8::MAX.into()); // must be an error
cx.emit_err(ConcatBytesOob { span }); dcx.emit_err(ConcatBytesOob { span });
} }
Ok(ast::LitKind::Int(_, _)) => { Ok(ast::LitKind::Int(_, _)) => {
cx.emit_err(ConcatBytesNonU8 { span }); dcx.emit_err(ConcatBytesNonU8 { span });
} }
Ok(ast::LitKind::ByteStr(..) | ast::LitKind::Byte(_)) => unreachable!(), Ok(ast::LitKind::ByteStr(..) | ast::LitKind::Byte(_)) => unreachable!(),
Err(err) => { Err(err) => {
@ -72,10 +73,11 @@ fn handle_array_element(
missing_literals: &mut Vec<rustc_span::Span>, missing_literals: &mut Vec<rustc_span::Span>,
expr: &P<rustc_ast::Expr>, expr: &P<rustc_ast::Expr>,
) -> Option<u8> { ) -> Option<u8> {
let dcx = cx.dcx();
match expr.kind { match expr.kind {
ast::ExprKind::Array(_) | ast::ExprKind::Repeat(_, _) => { ast::ExprKind::Array(_) | ast::ExprKind::Repeat(_, _) => {
if !*has_errors { if !*has_errors {
cx.emit_err(errors::ConcatBytesArray { span: expr.span, bytestr: false }); dcx.emit_err(errors::ConcatBytesArray { span: expr.span, bytestr: false });
} }
*has_errors = true; *has_errors = true;
None None
@ -89,7 +91,7 @@ fn handle_array_element(
Ok(ast::LitKind::Byte(val)) => Some(val), Ok(ast::LitKind::Byte(val)) => Some(val),
Ok(ast::LitKind::ByteStr(..)) => { Ok(ast::LitKind::ByteStr(..)) => {
if !*has_errors { if !*has_errors {
cx.emit_err(errors::ConcatBytesArray { span: expr.span, bytestr: true }); dcx.emit_err(errors::ConcatBytesArray { span: expr.span, bytestr: true });
} }
*has_errors = true; *has_errors = true;
None None
@ -104,7 +106,7 @@ fn handle_array_element(
}, },
ast::ExprKind::IncludedBytes(..) => { ast::ExprKind::IncludedBytes(..) => {
if !*has_errors { if !*has_errors {
cx.emit_err(errors::ConcatBytesArray { span: expr.span, bytestr: false }); dcx.emit_err(errors::ConcatBytesArray { span: expr.span, bytestr: false });
} }
*has_errors = true; *has_errors = true;
None None
@ -151,7 +153,7 @@ pub fn expand_concat_bytes(
} }
} }
} else { } else {
cx.emit_err(errors::ConcatBytesBadRepeat { span: count.value.span }); cx.dcx().emit_err(errors::ConcatBytesBadRepeat { span: count.value.span });
} }
} }
&ast::ExprKind::Lit(token_lit) => match ast::LitKind::from_token_lit(token_lit) { &ast::ExprKind::Lit(token_lit) => match ast::LitKind::from_token_lit(token_lit) {
@ -180,7 +182,7 @@ pub fn expand_concat_bytes(
} }
} }
if !missing_literals.is_empty() { if !missing_literals.is_empty() {
cx.emit_err(errors::ConcatBytesMissingLiteral { spans: missing_literals }); cx.dcx().emit_err(errors::ConcatBytesMissingLiteral { spans: missing_literals });
return base::MacEager::expr(DummyResult::raw_expr(sp, true)); return base::MacEager::expr(DummyResult::raw_expr(sp, true));
} else if has_errors { } else if has_errors {
return base::MacEager::expr(DummyResult::raw_expr(sp, true)); return base::MacEager::expr(DummyResult::raw_expr(sp, true));

View file

@ -14,7 +14,7 @@ pub fn expand_concat_idents<'cx>(
tts: TokenStream, tts: TokenStream,
) -> Box<dyn base::MacResult + 'cx> { ) -> Box<dyn base::MacResult + 'cx> {
if tts.is_empty() { if tts.is_empty() {
cx.emit_err(errors::ConcatIdentsMissingArgs { span: sp }); cx.dcx().emit_err(errors::ConcatIdentsMissingArgs { span: sp });
return DummyResult::any(sp); return DummyResult::any(sp);
} }
@ -24,7 +24,7 @@ pub fn expand_concat_idents<'cx>(
match e { match e {
TokenTree::Token(Token { kind: token::Comma, .. }, _) => {} TokenTree::Token(Token { kind: token::Comma, .. }, _) => {}
_ => { _ => {
cx.emit_err(errors::ConcatIdentsMissingComma { span: sp }); cx.dcx().emit_err(errors::ConcatIdentsMissingComma { span: sp });
return DummyResult::any(sp); return DummyResult::any(sp);
} }
} }
@ -36,7 +36,7 @@ pub fn expand_concat_idents<'cx>(
} }
} }
cx.emit_err(errors::ConcatIdentsIdentArgs { span: sp }); cx.dcx().emit_err(errors::ConcatIdentsIdentArgs { span: sp });
return DummyResult::any(sp); return DummyResult::any(sp);
} }
} }

View file

@ -120,7 +120,7 @@ fn report_bad_target(
let bad_target = let bad_target =
!matches!(item_kind, Some(ItemKind::Struct(..) | ItemKind::Enum(..) | ItemKind::Union(..))); !matches!(item_kind, Some(ItemKind::Struct(..) | ItemKind::Enum(..) | ItemKind::Union(..)));
if bad_target { if bad_target {
return Err(sess.emit_err(errors::BadDeriveTarget { span, item: item.span() })); return Err(sess.dcx().emit_err(errors::BadDeriveTarget { span, item: item.span() }));
} }
Ok(()) Ok(())
} }
@ -134,7 +134,7 @@ fn report_unexpected_meta_item_lit(sess: &Session, lit: &ast::MetaItemLit) {
} }
_ => errors::BadDeriveLitHelp::Other, _ => errors::BadDeriveLitHelp::Other,
}; };
sess.emit_err(errors::BadDeriveLit { span: lit.span, help }); sess.dcx().emit_err(errors::BadDeriveLit { span: lit.span, help });
} }
fn report_path_args(sess: &Session, meta: &ast::MetaItem) { fn report_path_args(sess: &Session, meta: &ast::MetaItem) {
@ -143,10 +143,10 @@ fn report_path_args(sess: &Session, meta: &ast::MetaItem) {
match meta.kind { match meta.kind {
MetaItemKind::Word => {} MetaItemKind::Word => {}
MetaItemKind::List(..) => { MetaItemKind::List(..) => {
sess.emit_err(errors::DerivePathArgsList { span }); sess.dcx().emit_err(errors::DerivePathArgsList { span });
} }
MetaItemKind::NameValue(..) => { MetaItemKind::NameValue(..) => {
sess.emit_err(errors::DerivePathArgsValue { span }); sess.dcx().emit_err(errors::DerivePathArgsValue { span });
} }
} }
} }

View file

@ -62,10 +62,10 @@ pub fn expand_deriving_clone(
cs_clone_simple("Clone", c, s, sub, true) cs_clone_simple("Clone", c, s, sub, true)
})); }));
} }
_ => cx.span_bug(span, "`#[derive(Clone)]` on wrong item kind"), _ => cx.dcx().span_bug(span, "`#[derive(Clone)]` on wrong item kind"),
}, },
_ => cx.span_bug(span, "`#[derive(Clone)]` on trait item or impl item"), _ => cx.dcx().span_bug(span, "`#[derive(Clone)]` on trait item or impl item"),
} }
let trait_def = TraitDef { let trait_def = TraitDef {
@ -144,7 +144,7 @@ fn cs_clone_simple(
process_variant(&variant.data); process_variant(&variant.data);
} }
} }
_ => cx.span_bug( _ => cx.dcx().span_bug(
trait_span, trait_span,
format!("unexpected substructure in simple `derive({name})`"), format!("unexpected substructure in simple `derive({name})`"),
), ),
@ -180,10 +180,10 @@ fn cs_clone(
vdata = &variant.data; vdata = &variant.data;
} }
EnumTag(..) | AllFieldlessEnum(..) => { EnumTag(..) | AllFieldlessEnum(..) => {
cx.span_bug(trait_span, format!("enum tags in `derive({name})`",)) cx.dcx().span_bug(trait_span, format!("enum tags in `derive({name})`",))
} }
StaticEnum(..) | StaticStruct(..) => { StaticEnum(..) | StaticStruct(..) => {
cx.span_bug(trait_span, format!("associated function in `derive({name})`")) cx.dcx().span_bug(trait_span, format!("associated function in `derive({name})`"))
} }
} }
@ -193,7 +193,7 @@ fn cs_clone(
.iter() .iter()
.map(|field| { .map(|field| {
let Some(ident) = field.name else { let Some(ident) = field.name else {
cx.span_bug( cx.dcx().span_bug(
trait_span, trait_span,
format!("unnamed field in normal struct in `derive({name})`",), format!("unnamed field in normal struct in `derive({name})`",),
); );

View file

@ -99,7 +99,7 @@ fn cs_total_eq_assert(
process_variant(&variant.data); process_variant(&variant.data);
} }
} }
_ => cx.span_bug(trait_span, "unexpected substructure in `derive(Eq)`"), _ => cx.dcx().span_bug(trait_span, "unexpected substructure in `derive(Eq)`"),
} }
BlockOrExpr::new_stmts(stmts) BlockOrExpr::new_stmts(stmts)
} }

View file

@ -61,7 +61,7 @@ pub fn cs_cmp(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> Bl
|cx, fold| match fold { |cx, fold| match fold {
CsFold::Single(field) => { CsFold::Single(field) => {
let [other_expr] = &field.other_selflike_exprs[..] else { let [other_expr] = &field.other_selflike_exprs[..] else {
cx.span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`"); cx.dcx().span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`");
}; };
let args = thin_vec![field.self_expr.clone(), other_expr.clone()]; let args = thin_vec![field.self_expr.clone(), other_expr.clone()];
cx.expr_call_global(field.span, cmp_path.clone(), args) cx.expr_call_global(field.span, cmp_path.clone(), args)

View file

@ -26,7 +26,8 @@ pub fn expand_deriving_partial_eq(
|cx, fold| match fold { |cx, fold| match fold {
CsFold::Single(field) => { CsFold::Single(field) => {
let [other_expr] = &field.other_selflike_exprs[..] else { let [other_expr] = &field.other_selflike_exprs[..] else {
cx.span_bug(field.span, "not exactly 2 arguments in `derive(PartialEq)`"); cx.dcx()
.span_bug(field.span, "not exactly 2 arguments in `derive(PartialEq)`");
}; };
// We received arguments of type `&T`. Convert them to type `T` by stripping // We received arguments of type `&T`. Convert them to type `T` by stripping

View file

@ -95,7 +95,7 @@ fn cs_partial_cmp(
|cx, fold| match fold { |cx, fold| match fold {
CsFold::Single(field) => { CsFold::Single(field) => {
let [other_expr] = &field.other_selflike_exprs[..] else { let [other_expr] = &field.other_selflike_exprs[..] else {
cx.span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`"); cx.dcx().span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`");
}; };
let args = thin_vec![field.self_expr.clone(), other_expr.clone()]; let args = thin_vec![field.self_expr.clone(), other_expr.clone()];
cx.expr_call_global(field.span, partial_cmp_path.clone(), args) cx.expr_call_global(field.span, partial_cmp_path.clone(), args)

View file

@ -55,7 +55,7 @@ fn show_substructure(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>
EnumMatching(_, _, v, fields) => (v.ident, &v.data, fields), EnumMatching(_, _, v, fields) => (v.ident, &v.data, fields),
AllFieldlessEnum(enum_def) => return show_fieldless_enum(cx, span, enum_def, substr), AllFieldlessEnum(enum_def) => return show_fieldless_enum(cx, span, enum_def, substr),
EnumTag(..) | StaticStruct(..) | StaticEnum(..) => { EnumTag(..) | StaticStruct(..) | StaticEnum(..) => {
cx.span_bug(span, "nonsensical .fields in `#[derive(Debug)]`") cx.dcx().span_bug(span, "nonsensical .fields in `#[derive(Debug)]`")
} }
}; };

View file

@ -177,7 +177,7 @@ fn decodable_substructure(
], ],
) )
} }
_ => cx.bug("expected StaticEnum or StaticStruct in derive(Decodable)"), _ => cx.dcx().bug("expected StaticEnum or StaticStruct in derive(Decodable)"),
}; };
BlockOrExpr::new_expr(expr) BlockOrExpr::new_expr(expr)
} }

View file

@ -41,7 +41,7 @@ pub fn expand_deriving_default(
default_struct_substructure(cx, trait_span, substr, fields) default_struct_substructure(cx, trait_span, substr, fields)
} }
StaticEnum(enum_def, _) => default_enum_substructure(cx, trait_span, enum_def), StaticEnum(enum_def, _) => default_enum_substructure(cx, trait_span, enum_def),
_ => cx.span_bug(trait_span, "method in `derive(Default)`"), _ => cx.dcx().span_bug(trait_span, "method in `derive(Default)`"),
} }
})), })),
}], }],
@ -120,7 +120,7 @@ fn extract_default_variant<'a>(
let suggs = possible_defaults let suggs = possible_defaults
.map(|v| errors::NoDefaultVariantSugg { span: v.span, ident: v.ident }) .map(|v| errors::NoDefaultVariantSugg { span: v.span, ident: v.ident })
.collect(); .collect();
cx.emit_err(errors::NoDefaultVariant { span: trait_span, suggs }); cx.dcx().emit_err(errors::NoDefaultVariant { span: trait_span, suggs });
return Err(()); return Err(());
} }
@ -140,7 +140,7 @@ fn extract_default_variant<'a>(
.then_some(errors::MultipleDefaultsSugg { spans, ident: variant.ident }) .then_some(errors::MultipleDefaultsSugg { spans, ident: variant.ident })
}) })
.collect(); .collect();
cx.emit_err(errors::MultipleDefaults { cx.dcx().emit_err(errors::MultipleDefaults {
span: trait_span, span: trait_span,
first: first.span, first: first.span,
additional: rest.iter().map(|v| v.span).collect(), additional: rest.iter().map(|v| v.span).collect(),
@ -151,12 +151,12 @@ fn extract_default_variant<'a>(
}; };
if !matches!(variant.data, VariantData::Unit(..)) { if !matches!(variant.data, VariantData::Unit(..)) {
cx.emit_err(errors::NonUnitDefault { span: variant.ident.span }); cx.dcx().emit_err(errors::NonUnitDefault { span: variant.ident.span });
return Err(()); return Err(());
} }
if let Some(non_exhaustive_attr) = attr::find_by_name(&variant.attrs, sym::non_exhaustive) { if let Some(non_exhaustive_attr) = attr::find_by_name(&variant.attrs, sym::non_exhaustive) {
cx.emit_err(errors::NonExhaustiveDefault { cx.dcx().emit_err(errors::NonExhaustiveDefault {
span: variant.ident.span, span: variant.ident.span,
non_exhaustive: non_exhaustive_attr.span, non_exhaustive: non_exhaustive_attr.span,
}); });
@ -176,14 +176,14 @@ fn validate_default_attribute(
let attr = match attrs.as_slice() { let attr = match attrs.as_slice() {
[attr] => attr, [attr] => attr,
[] => cx.bug( [] => cx.dcx().bug(
"this method must only be called with a variant that has a `#[default]` attribute", "this method must only be called with a variant that has a `#[default]` attribute",
), ),
[first, rest @ ..] => { [first, rest @ ..] => {
let sugg = errors::MultipleDefaultAttrsSugg { let sugg = errors::MultipleDefaultAttrsSugg {
spans: rest.iter().map(|attr| attr.span).collect(), spans: rest.iter().map(|attr| attr.span).collect(),
}; };
cx.emit_err(errors::MultipleDefaultAttrs { cx.dcx().emit_err(errors::MultipleDefaultAttrs {
span: default_variant.ident.span, span: default_variant.ident.span,
first: first.span, first: first.span,
first_rest: rest[0].span, first_rest: rest[0].span,
@ -196,7 +196,7 @@ fn validate_default_attribute(
} }
}; };
if !attr.is_word() { if !attr.is_word() {
cx.emit_err(errors::DefaultHasArg { span: attr.span }); cx.dcx().emit_err(errors::DefaultHasArg { span: attr.span });
return Err(()); return Err(());
} }
@ -210,7 +210,7 @@ struct DetectNonVariantDefaultAttr<'a, 'b> {
impl<'a, 'b> rustc_ast::visit::Visitor<'a> for DetectNonVariantDefaultAttr<'a, 'b> { impl<'a, 'b> rustc_ast::visit::Visitor<'a> for DetectNonVariantDefaultAttr<'a, 'b> {
fn visit_attribute(&mut self, attr: &'a rustc_ast::Attribute) { fn visit_attribute(&mut self, attr: &'a rustc_ast::Attribute) {
if attr.has_name(kw::Default) { if attr.has_name(kw::Default) {
self.cx.emit_err(errors::NonUnitDefault { span: attr.span }); self.cx.dcx().emit_err(errors::NonUnitDefault { span: attr.span });
} }
rustc_ast::visit::walk_attribute(self, attr); rustc_ast::visit::walk_attribute(self, attr);

View file

@ -296,6 +296,6 @@ fn encodable_substructure(
BlockOrExpr::new_mixed(thin_vec![me], Some(expr)) BlockOrExpr::new_mixed(thin_vec![me], Some(expr))
} }
_ => cx.bug("expected Struct or EnumMatching in derive(Encodable)"), _ => cx.dcx().bug("expected Struct or EnumMatching in derive(Encodable)"),
} }
} }

View file

@ -430,7 +430,7 @@ fn find_type_parameters(
} }
fn visit_mac_call(&mut self, mac: &ast::MacCall) { fn visit_mac_call(&mut self, mac: &ast::MacCall) {
self.cx.emit_err(errors::DeriveMacroCall { span: mac.span() }); self.cx.dcx().emit_err(errors::DeriveMacroCall { span: mac.span() });
} }
} }
@ -503,7 +503,7 @@ impl<'a> TraitDef<'a> {
is_packed, is_packed,
) )
} else { } else {
cx.emit_err(errors::DeriveUnion { span: mitem.span }); cx.dcx().emit_err(errors::DeriveUnion { span: mitem.span });
return; return;
} }
} }
@ -974,7 +974,7 @@ impl<'a> MethodDef<'a> {
match ty { match ty {
// Selflike (`&Self`) arguments only occur in non-static methods. // Selflike (`&Self`) arguments only occur in non-static methods.
Ref(box Self_, _) if !self.is_static() => selflike_args.push(arg_expr), Ref(box Self_, _) if !self.is_static() => selflike_args.push(arg_expr),
Self_ => cx.span_bug(span, "`Self` in non-return position"), Self_ => cx.dcx().span_bug(span, "`Self` in non-return position"),
_ => nonselflike_args.push(arg_expr), _ => nonselflike_args.push(arg_expr),
} }
} }
@ -1441,9 +1441,9 @@ impl<'a> TraitDef<'a> {
let is_tuple = matches!(struct_def, ast::VariantData::Tuple(..)); let is_tuple = matches!(struct_def, ast::VariantData::Tuple(..));
match (just_spans.is_empty(), named_idents.is_empty()) { match (just_spans.is_empty(), named_idents.is_empty()) {
(false, false) => { (false, false) => cx
cx.span_bug(self.span, "a struct with named and unnamed fields in generic `derive`") .dcx()
} .span_bug(self.span, "a struct with named and unnamed fields in generic `derive`"),
// named fields // named fields
(_, false) => Named(named_idents), (_, false) => Named(named_idents),
// unnamed fields // unnamed fields
@ -1489,7 +1489,7 @@ impl<'a> TraitDef<'a> {
let field_pats = pieces_iter let field_pats = pieces_iter
.map(|(sp, ident, pat)| { .map(|(sp, ident, pat)| {
if ident.is_none() { if ident.is_none() {
cx.span_bug( cx.dcx().span_bug(
sp, sp,
"a braced struct with unnamed fields in `derive`", "a braced struct with unnamed fields in `derive`",
); );
@ -1707,7 +1707,9 @@ where
tag_check_expr tag_check_expr
} }
} }
StaticEnum(..) | StaticStruct(..) => cx.span_bug(trait_span, "static function in `derive`"), StaticEnum(..) | StaticStruct(..) => {
AllFieldlessEnum(..) => cx.span_bug(trait_span, "fieldless enum in `derive`"), cx.dcx().span_bug(trait_span, "static function in `derive`")
}
AllFieldlessEnum(..) => cx.dcx().span_bug(trait_span, "fieldless enum in `derive`"),
} }
} }

View file

@ -138,8 +138,8 @@ impl Ty {
cx.path_all(span, false, vec![self_ty], params) cx.path_all(span, false, vec![self_ty], params)
} }
Path(p) => p.to_path(cx, span, self_ty, generics), Path(p) => p.to_path(cx, span, self_ty, generics),
Ref(..) => cx.span_bug(span, "ref in a path in generic `derive`"), Ref(..) => cx.dcx().span_bug(span, "ref in a path in generic `derive`"),
Unit => cx.span_bug(span, "unit in a path in generic `derive`"), Unit => cx.dcx().span_bug(span, "unit in a path in generic `derive`"),
} }
} }
} }

View file

@ -52,7 +52,7 @@ fn hash_substructure(
substr: &Substructure<'_>, substr: &Substructure<'_>,
) -> BlockOrExpr { ) -> BlockOrExpr {
let [state_expr] = substr.nonselflike_args else { let [state_expr] = substr.nonselflike_args else {
cx.span_bug(trait_span, "incorrect number of arguments in `derive(Hash)`"); cx.dcx().span_bug(trait_span, "incorrect number of arguments in `derive(Hash)`");
}; };
let call_hash = |span, expr| { let call_hash = |span, expr| {
let hash_path = { let hash_path = {
@ -75,7 +75,7 @@ fn hash_substructure(
let stmts = thin_vec![call_hash(tag_field.span, tag_field.self_expr.clone())]; let stmts = thin_vec![call_hash(tag_field.span, tag_field.self_expr.clone())];
(stmts, match_expr.clone()) (stmts, match_expr.clone())
} }
_ => cx.span_bug(trait_span, "impossible substructure in `derive(Hash)`"), _ => cx.dcx().span_bug(trait_span, "impossible substructure in `derive(Hash)`"),
}; };
BlockOrExpr::new_mixed(stmts, match_expr) BlockOrExpr::new_mixed(stmts, match_expr)

View file

@ -66,7 +66,7 @@ pub fn expand_env<'cx>(
) -> Box<dyn base::MacResult + 'cx> { ) -> Box<dyn base::MacResult + 'cx> {
let mut exprs = match get_exprs_from_tts(cx, tts) { let mut exprs = match get_exprs_from_tts(cx, tts) {
Some(exprs) if exprs.is_empty() || exprs.len() > 2 => { Some(exprs) if exprs.is_empty() || exprs.len() > 2 => {
cx.emit_err(errors::EnvTakesArgs { span: sp }); cx.dcx().emit_err(errors::EnvTakesArgs { span: sp });
return DummyResult::any(sp); return DummyResult::any(sp);
} }
None => return DummyResult::any(sp), None => return DummyResult::any(sp),
@ -101,15 +101,15 @@ pub fn expand_env<'cx>(
}; };
if let Some(msg_from_user) = custom_msg { if let Some(msg_from_user) = custom_msg {
cx.emit_err(errors::EnvNotDefinedWithUserMessage { span, msg_from_user }); cx.dcx().emit_err(errors::EnvNotDefinedWithUserMessage { span, msg_from_user });
} else if is_cargo_env_var(var.as_str()) { } else if is_cargo_env_var(var.as_str()) {
cx.emit_err(errors::EnvNotDefined::CargoEnvVar { cx.dcx().emit_err(errors::EnvNotDefined::CargoEnvVar {
span, span,
var: *symbol, var: *symbol,
var_expr: var_expr.ast_deref(), var_expr: var_expr.ast_deref(),
}); });
} else { } else {
cx.emit_err(errors::EnvNotDefined::CustomEnvVar { cx.dcx().emit_err(errors::EnvNotDefined::CustomEnvVar {
span, span,
var: *symbol, var: *symbol,
var_expr: var_expr.ast_deref(), var_expr: var_expr.ast_deref(),

View file

@ -69,7 +69,7 @@ fn parse_args<'a>(ecx: &mut ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<
let mut p = ecx.new_parser_from_tts(tts); let mut p = ecx.new_parser_from_tts(tts);
if p.token == token::Eof { if p.token == token::Eof {
return Err(ecx.create_err(errors::FormatRequiresString { span: sp })); return Err(ecx.dcx().create_err(errors::FormatRequiresString { span: sp }));
} }
let first_token = &p.token; let first_token = &p.token;
@ -126,7 +126,7 @@ fn parse_args<'a>(ecx: &mut ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<
p.expect(&token::Eq)?; p.expect(&token::Eq)?;
let expr = p.parse_expr()?; let expr = p.parse_expr()?;
if let Some((_, prev)) = args.by_name(ident.name) { if let Some((_, prev)) = args.by_name(ident.name) {
ecx.emit_err(errors::FormatDuplicateArg { ecx.dcx().emit_err(errors::FormatDuplicateArg {
span: ident.span, span: ident.span,
prev: prev.kind.ident().unwrap().span, prev: prev.kind.ident().unwrap().span,
duplicate: ident.span, duplicate: ident.span,
@ -139,7 +139,7 @@ fn parse_args<'a>(ecx: &mut ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<
_ => { _ => {
let expr = p.parse_expr()?; let expr = p.parse_expr()?;
if !args.named_args().is_empty() { if !args.named_args().is_empty() {
ecx.emit_err(errors::PositionalAfterNamed { ecx.dcx().emit_err(errors::PositionalAfterNamed {
span: expr.span, span: expr.span,
args: args args: args
.named_args() .named_args()
@ -293,7 +293,7 @@ fn make_format_args(
} }
} }
} }
ecx.emit_err(e); ecx.dcx().emit_err(e);
return Err(()); return Err(());
} }
@ -351,7 +351,7 @@ fn make_format_args(
} else { } else {
// For the moment capturing variables from format strings expanded from macros is // For the moment capturing variables from format strings expanded from macros is
// disabled (see RFC #2795) // disabled (see RFC #2795)
ecx.emit_err(errors::FormatNoArgNamed { span, name }); ecx.dcx().emit_err(errors::FormatNoArgNamed { span, name });
DummyResult::raw_expr(span, true) DummyResult::raw_expr(span, true)
}; };
Ok(args.add(FormatArgument { kind: FormatArgumentKind::Captured(ident), expr })) Ok(args.add(FormatArgument { kind: FormatArgumentKind::Captured(ident), expr }))
@ -529,7 +529,7 @@ fn make_format_args(
// Only check for unused named argument names if there are no other errors to avoid causing // Only check for unused named argument names if there are no other errors to avoid causing
// too much noise in output errors, such as when a named argument is entirely unused. // too much noise in output errors, such as when a named argument is entirely unused.
if invalid_refs.is_empty() && ecx.sess.err_count() == 0 { if invalid_refs.is_empty() && ecx.dcx().err_count() == 0 {
for &(index, span, used_as) in &numeric_refences_to_named_arg { for &(index, span, used_as) in &numeric_refences_to_named_arg {
let (position_sp_to_replace, position_sp_for_msg) = match used_as { let (position_sp_to_replace, position_sp_for_msg) = match used_as {
Placeholder(pspan) => (span, pspan), Placeholder(pspan) => (span, pspan),
@ -585,7 +585,7 @@ fn invalid_placeholder_type_error(
} else { } else {
vec![] vec![]
}; };
ecx.emit_err(errors::FormatUnknownTrait { span: sp.unwrap_or(fmt_span), ty, suggs }); ecx.dcx().emit_err(errors::FormatUnknownTrait { span: sp.unwrap_or(fmt_span), ty, suggs });
} }
fn report_missing_placeholders( fn report_missing_placeholders(
@ -600,12 +600,12 @@ fn report_missing_placeholders(
fmt_span: Span, fmt_span: Span,
) { ) {
let mut diag = if let &[(span, named)] = &unused[..] { let mut diag = if let &[(span, named)] = &unused[..] {
ecx.create_err(errors::FormatUnusedArg { span, named }) ecx.dcx().create_err(errors::FormatUnusedArg { span, named })
} else { } else {
let unused_labels = let unused_labels =
unused.iter().map(|&(span, named)| errors::FormatUnusedArg { span, named }).collect(); unused.iter().map(|&(span, named)| errors::FormatUnusedArg { span, named }).collect();
let unused_spans = unused.iter().map(|&(span, _)| span).collect(); let unused_spans = unused.iter().map(|&(span, _)| span).collect();
ecx.create_err(errors::FormatUnusedArgs { ecx.dcx().create_err(errors::FormatUnusedArgs {
fmt: fmt_span, fmt: fmt_span,
unused: unused_spans, unused: unused_spans,
unused_labels, unused_labels,
@ -776,7 +776,7 @@ fn report_redundant_format_arguments<'a>(
None None
}; };
return Some(ecx.create_err(errors::FormatRedundantArgs { return Some(ecx.dcx().create_err(errors::FormatRedundantArgs {
n: args_spans.len(), n: args_spans.len(),
span: MultiSpan::from(args_spans), span: MultiSpan::from(args_spans),
note: multispan, note: multispan,
@ -876,7 +876,7 @@ fn report_invalid_references(
} else { } else {
MultiSpan::from_spans(spans) MultiSpan::from_spans(spans)
}; };
e = ecx.create_err(errors::FormatPositionalMismatch { e = ecx.dcx().create_err(errors::FormatPositionalMismatch {
span, span,
n: num_placeholders, n: num_placeholders,
desc: num_args_desc, desc: num_args_desc,
@ -942,7 +942,7 @@ fn report_invalid_references(
head = indexes.into_iter().map(|i| i.to_string()).collect::<Vec<_>>().join(", ") head = indexes.into_iter().map(|i| i.to_string()).collect::<Vec<_>>().join(", ")
) )
}; };
e = ecx.struct_span_err( e = ecx.dcx().struct_span_err(
span, span,
format!("invalid reference to positional {arg_list} ({num_args_desc})"), format!("invalid reference to positional {arg_list} ({num_args_desc})"),
); );

View file

@ -34,7 +34,7 @@ pub fn expand(
{ {
(item, true, ecx.with_def_site_ctxt(ty.span)) (item, true, ecx.with_def_site_ctxt(ty.span))
} else { } else {
ecx.sess.dcx().emit_err(errors::AllocMustStatics { span: item.span() }); ecx.dcx().emit_err(errors::AllocMustStatics { span: item.span() });
return vec![orig_item]; return vec![orig_item];
}; };

View file

@ -155,7 +155,7 @@ pub fn expand_include<'cx>(
if self.p.token != token::Eof { if self.p.token != token::Eof {
let token = pprust::token_to_string(&self.p.token); let token = pprust::token_to_string(&self.p.token);
let msg = format!("expected item, found `{token}`"); let msg = format!("expected item, found `{token}`");
self.p.struct_span_err(self.p.token.span, msg).emit(); self.p.dcx().struct_span_err(self.p.token.span, msg).emit();
} }
break; break;
@ -193,12 +193,12 @@ pub fn expand_include_str(
base::MacEager::expr(cx.expr_str(sp, interned_src)) base::MacEager::expr(cx.expr_str(sp, interned_src))
} }
Err(_) => { Err(_) => {
cx.span_err(sp, format!("{} wasn't a utf-8 file", file.display())); cx.dcx().span_err(sp, format!("{} wasn't a utf-8 file", file.display()));
DummyResult::any(sp) DummyResult::any(sp)
} }
}, },
Err(e) => { Err(e) => {
cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e)); cx.dcx().span_err(sp, format!("couldn't read {}: {}", file.display(), e));
DummyResult::any(sp) DummyResult::any(sp)
} }
} }
@ -226,7 +226,7 @@ pub fn expand_include_bytes(
base::MacEager::expr(expr) base::MacEager::expr(expr)
} }
Err(e) => { Err(e) => {
cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e)); cx.dcx().span_err(sp, format!("couldn't read {}: {}", file.display(), e));
DummyResult::any(sp) DummyResult::any(sp)
} }
} }

View file

@ -43,7 +43,7 @@ pub fn expand_test_case(
} }
} }
_ => { _ => {
ecx.emit_err(errors::TestCaseNonItem { span: anno_item.span() }); ecx.dcx().emit_err(errors::TestCaseNonItem { span: anno_item.span() });
return vec![]; return vec![];
} }
}; };
@ -389,7 +389,7 @@ pub fn expand_test_or_bench(
} }
fn not_testable_error(cx: &ExtCtxt<'_>, attr_sp: Span, item: Option<&ast::Item>) { fn not_testable_error(cx: &ExtCtxt<'_>, attr_sp: Span, item: Option<&ast::Item>) {
let dcx = cx.sess.dcx(); let dcx = cx.dcx();
let msg = "the `#[test]` attribute may only be used on a non-associated function"; let msg = "the `#[test]` attribute may only be used on a non-associated function";
let level = match item.map(|i| &i.kind) { let level = match item.map(|i| &i.kind) {
// These were a warning before #92959 and need to continue being that to avoid breaking // These were a warning before #92959 and need to continue being that to avoid breaking
@ -465,8 +465,6 @@ fn should_ignore_message(i: &ast::Item) -> Option<Symbol> {
fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic { fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic {
match attr::find_by_name(&i.attrs, sym::should_panic) { match attr::find_by_name(&i.attrs, sym::should_panic) {
Some(attr) => { Some(attr) => {
let dcx = cx.sess.dcx();
match attr.meta_item_list() { match attr.meta_item_list() {
// Handle #[should_panic(expected = "foo")] // Handle #[should_panic(expected = "foo")]
Some(list) => { Some(list) => {
@ -476,17 +474,18 @@ fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic {
.and_then(|mi| mi.meta_item()) .and_then(|mi| mi.meta_item())
.and_then(|mi| mi.value_str()); .and_then(|mi| mi.value_str());
if list.len() != 1 || msg.is_none() { if list.len() != 1 || msg.is_none() {
dcx.struct_span_warn( cx.dcx()
attr.span, .struct_span_warn(
"argument must be of the form: \ attr.span,
"argument must be of the form: \
`expected = \"error message\"`", `expected = \"error message\"`",
) )
.note( .note(
"errors in this attribute were erroneously \ "errors in this attribute were erroneously \
allowed and will become a hard error in a \ allowed and will become a hard error in a \
future release", future release",
) )
.emit(); .emit();
ShouldPanic::Yes(None) ShouldPanic::Yes(None)
} else { } else {
ShouldPanic::Yes(msg) ShouldPanic::Yes(msg)
@ -534,7 +533,7 @@ fn check_test_signature(
f: &ast::Fn, f: &ast::Fn,
) -> Result<(), ErrorGuaranteed> { ) -> Result<(), ErrorGuaranteed> {
let has_should_panic_attr = attr::contains_name(&i.attrs, sym::should_panic); let has_should_panic_attr = attr::contains_name(&i.attrs, sym::should_panic);
let dcx = cx.sess.dcx(); let dcx = cx.dcx();
if let ast::Unsafe::Yes(span) = f.sig.header.unsafety { if let ast::Unsafe::Yes(span) = f.sig.header.unsafety {
return Err(dcx.emit_err(errors::TestBadFn { span: i.span, cause: span, kind: "unsafe" })); return Err(dcx.emit_err(errors::TestBadFn { span: i.span, cause: span, kind: "unsafe" }));
@ -600,7 +599,7 @@ fn check_bench_signature(
// N.B., inadequate check, but we're running // N.B., inadequate check, but we're running
// well before resolve, can't get too deep. // well before resolve, can't get too deep.
if f.sig.decl.inputs.len() != 1 { if f.sig.decl.inputs.len() != 1 {
return Err(cx.sess.dcx().emit_err(errors::BenchSig { span: i.span })); return Err(cx.dcx().emit_err(errors::BenchSig { span: i.span }));
} }
Ok(()) Ok(())
} }

View file

@ -21,7 +21,7 @@ pub fn expand_trace_macros(
}; };
err |= cursor.next().is_some(); err |= cursor.next().is_some();
if err { if err {
cx.emit_err(errors::TraceMacros { span: sp }); cx.dcx().emit_err(errors::TraceMacros { span: sp });
} else { } else {
cx.set_trace_macros(value); cx.set_trace_macros(value);
} }

View file

@ -47,12 +47,12 @@ pub(crate) fn conv_to_call_conv(sess: &Session, c: Conv, default_call_conv: Call
} }
Conv::X86Intr | Conv::RiscvInterrupt { .. } => { Conv::X86Intr | Conv::RiscvInterrupt { .. } => {
sess.fatal(format!("interrupt call conv {c:?} not yet implemented")) sess.dcx().fatal(format!("interrupt call conv {c:?} not yet implemented"))
} }
Conv::ArmAapcs => sess.fatal("aapcs call conv not yet implemented"), Conv::ArmAapcs => sess.dcx().fatal("aapcs call conv not yet implemented"),
Conv::CCmseNonSecureCall => { Conv::CCmseNonSecureCall => {
sess.fatal("C-cmse-nonsecure-call call conv is not yet implemented"); sess.dcx().fatal("C-cmse-nonsecure-call call conv is not yet implemented");
} }
Conv::Msp430Intr Conv::Msp430Intr
@ -88,10 +88,10 @@ pub(crate) fn import_function<'tcx>(
let sig = get_function_sig(tcx, module.target_config().default_call_conv, inst); let sig = get_function_sig(tcx, module.target_config().default_call_conv, inst);
match module.declare_function(name, Linkage::Import, &sig) { match module.declare_function(name, Linkage::Import, &sig) {
Ok(func_id) => func_id, Ok(func_id) => func_id,
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(format!( Err(ModuleError::IncompatibleDeclaration(_)) => tcx.dcx().fatal(format!(
"attempt to declare `{name}` as function, but it was already declared as static" "attempt to declare `{name}` as function, but it was already declared as static"
)), )),
Err(ModuleError::IncompatibleSignature(_, prev_sig, new_sig)) => tcx.sess.fatal(format!( Err(ModuleError::IncompatibleSignature(_, prev_sig, new_sig)) => tcx.dcx().fatal(format!(
"attempt to declare `{name}` with signature {new_sig:?}, \ "attempt to declare `{name}` with signature {new_sig:?}, \
but it was already declared with signature {prev_sig:?}" but it was already declared with signature {prev_sig:?}"
)), )),
@ -181,7 +181,7 @@ fn make_local_place<'tcx>(
is_ssa: bool, is_ssa: bool,
) -> CPlace<'tcx> { ) -> CPlace<'tcx> {
if layout.is_unsized() { if layout.is_unsized() {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
fx.mir.local_decls[local].source_info.span, fx.mir.local_decls[local].source_info.span,
"unsized locals are not yet supported", "unsized locals are not yet supported",
); );
@ -226,7 +226,7 @@ pub(crate) fn codegen_fn_prelude<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, start_
// FIXME implement variadics in cranelift // FIXME implement variadics in cranelift
if fn_abi.c_variadic { if fn_abi.c_variadic {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
fx.mir.span, fx.mir.span,
"Defining variadic functions is not yet supported by Cranelift", "Defining variadic functions is not yet supported by Cranelift",
); );
@ -543,7 +543,7 @@ pub(crate) fn codegen_terminator_call<'tcx>(
// FIXME find a cleaner way to support varargs // FIXME find a cleaner way to support varargs
if fn_sig.c_variadic() { if fn_sig.c_variadic() {
if !matches!(fn_sig.abi(), Abi::C { .. }) { if !matches!(fn_sig.abi(), Abi::C { .. }) {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
source_info.span, source_info.span,
format!("Variadic call for non-C abi {:?}", fn_sig.abi()), format!("Variadic call for non-C abi {:?}", fn_sig.abi()),
); );
@ -555,7 +555,7 @@ pub(crate) fn codegen_terminator_call<'tcx>(
let ty = fx.bcx.func.dfg.value_type(arg); let ty = fx.bcx.func.dfg.value_type(arg);
if !ty.is_int() { if !ty.is_int() {
// FIXME set %al to upperbound on float args once floats are supported // FIXME set %al to upperbound on float args once floats are supported
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
source_info.span, source_info.span,
format!("Non int ty {:?} for variadic call", ty), format!("Non int ty {:?} for variadic call", ty),
); );

View file

@ -236,13 +236,13 @@ pub(crate) fn verify_func(
match cranelift_codegen::verify_function(&func, &flags) { match cranelift_codegen::verify_function(&func, &flags) {
Ok(_) => {} Ok(_) => {}
Err(err) => { Err(err) => {
tcx.sess.err(format!("{:?}", err)); tcx.dcx().err(format!("{:?}", err));
let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error( let pretty_error = cranelift_codegen::print_errors::pretty_verifier_error(
&func, &func,
Some(Box::new(writer)), Some(Box::new(writer)),
err, err,
); );
tcx.sess.fatal(format!("cranelift verify error:\n{}", pretty_error)); tcx.dcx().fatal(format!("cranelift verify error:\n{}", pretty_error));
} }
} }
}); });
@ -450,7 +450,7 @@ fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) {
unwind: _, unwind: _,
} => { } => {
if options.contains(InlineAsmOptions::MAY_UNWIND) { if options.contains(InlineAsmOptions::MAY_UNWIND) {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
source_info.span, source_info.span,
"cranelift doesn't support unwinding from inline assembly.", "cranelift doesn't support unwinding from inline assembly.",
); );
@ -812,7 +812,7 @@ fn codegen_stmt<'tcx>(
| StatementKind::PlaceMention(..) | StatementKind::PlaceMention(..)
| StatementKind::AscribeUserType(..) => {} | StatementKind::AscribeUserType(..) => {}
StatementKind::Coverage { .. } => fx.tcx.sess.fatal("-Zcoverage is unimplemented"), StatementKind::Coverage { .. } => fx.tcx.dcx().fatal("-Zcoverage is unimplemented"),
StatementKind::Intrinsic(ref intrinsic) => match &**intrinsic { StatementKind::Intrinsic(ref intrinsic) => match &**intrinsic {
// We ignore `assume` intrinsics, they are only useful for optimizations // We ignore `assume` intrinsics, they are only useful for optimizations
NonDivergingIntrinsic::Assume(_) => {} NonDivergingIntrinsic::Assume(_) => {}

View file

@ -465,9 +465,12 @@ impl<'tcx> LayoutOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
#[inline] #[inline]
fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! { fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
if let LayoutError::SizeOverflow(_) | LayoutError::ReferencesError(_) = err { if let LayoutError::SizeOverflow(_) | LayoutError::ReferencesError(_) = err {
self.0.sess.span_fatal(span, err.to_string()) self.0.sess.dcx().span_fatal(span, err.to_string())
} else { } else {
self.0.sess.span_fatal(span, format!("failed to get layout for `{}`: {}", ty, err)) self.0
.sess
.dcx()
.span_fatal(span, format!("failed to get layout for `{}`: {}", ty, err))
} }
} }
} }
@ -483,7 +486,7 @@ impl<'tcx> FnAbiOfHelpers<'tcx> for RevealAllLayoutCx<'tcx> {
fn_abi_request: FnAbiRequest<'tcx>, fn_abi_request: FnAbiRequest<'tcx>,
) -> ! { ) -> ! {
if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err { if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err {
self.0.sess.emit_fatal(Spanned { span, node: err }) self.0.sess.dcx().emit_fatal(Spanned { span, node: err })
} else { } else {
match fn_abi_request { match fn_abi_request {
FnAbiRequest::OfFnPtr { sig, extra_args } => { FnAbiRequest::OfFnPtr { sig, extra_args } => {

View file

@ -263,7 +263,7 @@ fn data_id_for_static(
attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL), attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
) { ) {
Ok(data_id) => data_id, Ok(data_id) => data_id,
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(format!( Err(ModuleError::IncompatibleDeclaration(_)) => tcx.dcx().fatal(format!(
"attempt to declare `{symbol_name}` as static, but it was already declared as function" "attempt to declare `{symbol_name}` as static, but it was already declared as function"
)), )),
Err(err) => Err::<_, _>(err).unwrap(), Err(err) => Err::<_, _>(err).unwrap(),
@ -311,7 +311,7 @@ fn data_id_for_static(
attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL), attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
) { ) {
Ok(data_id) => data_id, Ok(data_id) => data_id,
Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(format!( Err(ModuleError::IncompatibleDeclaration(_)) => tcx.dcx().fatal(format!(
"attempt to declare `{symbol_name}` as static, but it was already declared as function" "attempt to declare `{symbol_name}` as static, but it was already declared as function"
)), )),
Err(err) => Err::<_, _>(err).unwrap(), Err(err) => Err::<_, _>(err).unwrap(),
@ -360,7 +360,7 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut Constant
if let Some(names) = section_name.split_once(',') { if let Some(names) = section_name.split_once(',') {
names names
} else { } else {
tcx.sess.fatal(format!( tcx.dcx().fatal(format!(
"#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma", "#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
section_name section_name
)); ));
@ -406,7 +406,7 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut Constant
GlobalAlloc::Static(def_id) => { GlobalAlloc::Static(def_id) => {
if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
{ {
tcx.sess.fatal(format!( tcx.dcx().fatal(format!(
"Allocation {:?} contains reference to TLS value {:?}", "Allocation {:?} contains reference to TLS value {:?}",
alloc_id, def_id alloc_id, def_id
)); ));

View file

@ -69,7 +69,7 @@ impl OngoingCodegen {
let module_codegen_result = match module_codegen_result { let module_codegen_result = match module_codegen_result {
Ok(module_codegen_result) => module_codegen_result, Ok(module_codegen_result) => module_codegen_result,
Err(err) => sess.fatal(err), Err(err) => sess.dcx().fatal(err),
}; };
let ModuleCodegenResult { module_regular, module_global_asm, existing_work_product } = let ModuleCodegenResult { module_regular, module_global_asm, existing_work_product } =
module_codegen_result; module_codegen_result;
@ -108,7 +108,7 @@ impl OngoingCodegen {
self.concurrency_limiter.finished(); self.concurrency_limiter.finished();
sess.abort_if_errors(); sess.dcx().abort_if_errors();
( (
CodegenResults { CodegenResults {
@ -422,7 +422,7 @@ pub(crate) fn run_aot(
backend_config.clone(), backend_config.clone(),
global_asm_config.clone(), global_asm_config.clone(),
cgu.name(), cgu.name(),
concurrency_limiter.acquire(tcx.sess.dcx()), concurrency_limiter.acquire(tcx.dcx()),
), ),
module_codegen, module_codegen,
Some(rustc_middle::dep_graph::hash_result), Some(rustc_middle::dep_graph::hash_result),
@ -455,7 +455,7 @@ pub(crate) fn run_aot(
"allocator_shim".to_owned(), "allocator_shim".to_owned(),
) { ) {
Ok(allocator_module) => Some(allocator_module), Ok(allocator_module) => Some(allocator_module),
Err(err) => tcx.sess.fatal(err), Err(err) => tcx.dcx().fatal(err),
} }
} else { } else {
None None
@ -478,7 +478,7 @@ pub(crate) fn run_aot(
let obj = create_compressed_metadata_file(tcx.sess, &metadata, &symbol_name); let obj = create_compressed_metadata_file(tcx.sess, &metadata, &symbol_name);
if let Err(err) = std::fs::write(&tmp_file, obj) { if let Err(err) = std::fs::write(&tmp_file, obj) {
tcx.sess.fatal(format!("error writing metadata object file: {}", err)); tcx.dcx().fatal(format!("error writing metadata object file: {}", err));
} }
(metadata_cgu_name, tmp_file) (metadata_cgu_name, tmp_file)

View file

@ -94,11 +94,11 @@ fn create_jit_module(
pub(crate) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! { pub(crate) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! {
if !tcx.sess.opts.output_types.should_codegen() { if !tcx.sess.opts.output_types.should_codegen() {
tcx.sess.fatal("JIT mode doesn't work with `cargo check`"); tcx.dcx().fatal("JIT mode doesn't work with `cargo check`");
} }
if !tcx.crate_types().contains(&rustc_session::config::CrateType::Executable) { if !tcx.crate_types().contains(&rustc_session::config::CrateType::Executable) {
tcx.sess.fatal("can't jit non-executable crate"); tcx.dcx().fatal("can't jit non-executable crate");
} }
let (mut jit_module, mut cx) = create_jit_module( let (mut jit_module, mut cx) = create_jit_module(
@ -141,17 +141,17 @@ pub(crate) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! {
} }
MonoItem::GlobalAsm(item_id) => { MonoItem::GlobalAsm(item_id) => {
let item = tcx.hir().item(item_id); let item = tcx.hir().item(item_id);
tcx.sess.span_fatal(item.span, "Global asm is not supported in JIT mode"); tcx.dcx().span_fatal(item.span, "Global asm is not supported in JIT mode");
} }
} }
} }
}); });
if !cx.global_asm.is_empty() { if !cx.global_asm.is_empty() {
tcx.sess.fatal("Inline asm is not supported in JIT mode"); tcx.dcx().fatal("Inline asm is not supported in JIT mode");
} }
tcx.sess.abort_if_errors(); tcx.dcx().abort_if_errors();
jit_module.finalize_definitions().unwrap(); jit_module.finalize_definitions().unwrap();
unsafe { cx.unwind_context.register_jit(&jit_module) }; unsafe { cx.unwind_context.register_jit(&jit_module) };
@ -338,7 +338,7 @@ fn dep_symbol_lookup_fn(
.collect::<Box<[_]>>(), .collect::<Box<[_]>>(),
); );
sess.abort_if_errors(); sess.dcx().abort_if_errors();
Box::new(move |sym_name| { Box::new(move |sym_name| {
for dylib in &*imported_dylibs { for dylib in &*imported_dylibs {

View file

@ -47,7 +47,7 @@ pub(crate) fn codegen_global_asm_item(tcx: TyCtxt<'_>, global_asm: &mut String,
} }
InlineAsmOperand::SymFn { anon_const } => { InlineAsmOperand::SymFn { anon_const } => {
if cfg!(not(feature = "inline_asm_sym")) { if cfg!(not(feature = "inline_asm_sym")) {
tcx.sess.span_err( tcx.dcx().span_err(
item.span, item.span,
"asm! and global_asm! sym operands are not yet supported", "asm! and global_asm! sym operands are not yet supported",
); );
@ -65,7 +65,7 @@ pub(crate) fn codegen_global_asm_item(tcx: TyCtxt<'_>, global_asm: &mut String,
} }
InlineAsmOperand::SymStatic { path: _, def_id } => { InlineAsmOperand::SymStatic { path: _, def_id } => {
if cfg!(not(feature = "inline_asm_sym")) { if cfg!(not(feature = "inline_asm_sym")) {
tcx.sess.span_err( tcx.dcx().span_err(
item.span, item.span,
"asm! and global_asm! sym operands are not yet supported", "asm! and global_asm! sym operands are not yet supported",
); );

View file

@ -84,7 +84,7 @@ pub(crate) fn codegen_inline_asm_terminator<'tcx>(
InlineAsmOperand::SymFn { ref value } => { InlineAsmOperand::SymFn { ref value } => {
if cfg!(not(feature = "inline_asm_sym")) { if cfg!(not(feature = "inline_asm_sym")) {
fx.tcx fx.tcx
.sess .dcx()
.span_err(span, "asm! and global_asm! sym operands are not yet supported"); .span_err(span, "asm! and global_asm! sym operands are not yet supported");
} }
@ -455,7 +455,7 @@ impl<'tcx> InlineAssemblyGenerator<'_, 'tcx> {
} }
_ => self _ => self
.tcx .tcx
.sess .dcx()
.fatal(format!("Unsupported binary format for inline asm: {binary_format:?}")), .fatal(format!("Unsupported binary format for inline asm: {binary_format:?}")),
} }
@ -563,7 +563,7 @@ impl<'tcx> InlineAssemblyGenerator<'_, 'tcx> {
BinaryFormat::Macho | BinaryFormat::Coff => {} BinaryFormat::Macho | BinaryFormat::Coff => {}
_ => self _ => self
.tcx .tcx
.sess .dcx()
.fatal(format!("Unsupported binary format for inline asm: {binary_format:?}")), .fatal(format!("Unsupported binary format for inline asm: {binary_format:?}")),
} }

View file

@ -68,7 +68,7 @@ pub(crate) fn codegen_llvm_intrinsic_call<'tcx>(
_ => { _ => {
fx.tcx fx.tcx
.sess .dcx()
.warn(format!("unsupported llvm intrinsic {}; replacing with trap", intrinsic)); .warn(format!("unsupported llvm intrinsic {}; replacing with trap", intrinsic));
crate::trap::trap_unimplemented(fx, intrinsic); crate::trap::trap_unimplemented(fx, intrinsic);
return; return;

View file

@ -309,7 +309,7 @@ pub(crate) fn codegen_aarch64_llvm_intrinsic_call<'tcx>(
} }
*/ */
_ => { _ => {
fx.tcx.sess.warn(format!( fx.tcx.dcx().warn(format!(
"unsupported AArch64 llvm intrinsic {}; replacing with trap", "unsupported AArch64 llvm intrinsic {}; replacing with trap",
intrinsic intrinsic
)); ));

View file

@ -960,7 +960,9 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>(
{ {
imm8 imm8
} else { } else {
fx.tcx.sess.span_fatal(span, "Index argument for `_mm_cmpestri` is not a constant"); fx.tcx
.dcx()
.span_fatal(span, "Index argument for `_mm_cmpestri` is not a constant");
}; };
let imm8 = imm8.try_to_u8().unwrap_or_else(|_| panic!("kind not scalar: {:?}", imm8)); let imm8 = imm8.try_to_u8().unwrap_or_else(|_| panic!("kind not scalar: {:?}", imm8));
@ -1011,7 +1013,9 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>(
{ {
imm8 imm8
} else { } else {
fx.tcx.sess.span_fatal(span, "Index argument for `_mm_cmpestrm` is not a constant"); fx.tcx
.dcx()
.span_fatal(span, "Index argument for `_mm_cmpestrm` is not a constant");
}; };
let imm8 = imm8.try_to_u8().unwrap_or_else(|_| panic!("kind not scalar: {:?}", imm8)); let imm8 = imm8.try_to_u8().unwrap_or_else(|_| panic!("kind not scalar: {:?}", imm8));
@ -1056,7 +1060,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>(
{ {
imm8 imm8
} else { } else {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
span, span,
"Index argument for `_mm_clmulepi64_si128` is not a constant", "Index argument for `_mm_clmulepi64_si128` is not a constant",
); );
@ -1093,7 +1097,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>(
{ {
imm8 imm8
} else { } else {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
span, span,
"Index argument for `_mm_aeskeygenassist_si128` is not a constant", "Index argument for `_mm_aeskeygenassist_si128` is not a constant",
); );
@ -1361,7 +1365,7 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>(
_ => { _ => {
fx.tcx fx.tcx
.sess .dcx()
.warn(format!("unsupported x86 llvm intrinsic {}; replacing with trap", intrinsic)); .warn(format!("unsupported x86 llvm intrinsic {}; replacing with trap", intrinsic));
crate::trap::trap_unimplemented(fx, intrinsic); crate::trap::trap_unimplemented(fx, intrinsic);
return; return;

View file

@ -37,7 +37,7 @@ fn report_atomic_type_validation_error<'tcx>(
span: Span, span: Span,
ty: Ty<'tcx>, ty: Ty<'tcx>,
) { ) {
fx.tcx.sess.span_err( fx.tcx.dcx().span_err(
span, span,
format!( format!(
"`{}` intrinsic: expected basic integer or raw pointer type, found `{:?}`", "`{}` intrinsic: expected basic integer or raw pointer type, found `{:?}`",
@ -785,7 +785,7 @@ fn codegen_regular_intrinsic_call<'tcx>(
return; return;
} else { } else {
fx.tcx fx.tcx
.sess .dcx()
.span_fatal(source_info.span, "128bit atomics not yet supported"); .span_fatal(source_info.span, "128bit atomics not yet supported");
} }
} }
@ -816,7 +816,7 @@ fn codegen_regular_intrinsic_call<'tcx>(
return; return;
} else { } else {
fx.tcx fx.tcx
.sess .dcx()
.span_fatal(source_info.span, "128bit atomics not yet supported"); .span_fatal(source_info.span, "128bit atomics not yet supported");
} }
} }
@ -1245,7 +1245,7 @@ fn codegen_regular_intrinsic_call<'tcx>(
// FIXME implement variadics in cranelift // FIXME implement variadics in cranelift
sym::va_copy | sym::va_arg | sym::va_end => { sym::va_copy | sym::va_arg | sym::va_end => {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
source_info.span, source_info.span,
"Defining variadic functions is not yet supported by Cranelift", "Defining variadic functions is not yet supported by Cranelift",
); );
@ -1253,7 +1253,7 @@ fn codegen_regular_intrinsic_call<'tcx>(
_ => { _ => {
fx.tcx fx.tcx
.sess .dcx()
.span_fatal(source_info.span, format!("unsupported intrinsic {}", intrinsic)); .span_fatal(source_info.span, format!("unsupported intrinsic {}", intrinsic));
} }
} }

View file

@ -12,7 +12,7 @@ fn report_simd_type_validation_error(
span: Span, span: Span,
ty: Ty<'_>, ty: Ty<'_>,
) { ) {
fx.tcx.sess.span_err(span, format!("invalid monomorphization of `{}` intrinsic: expected SIMD input type, found non-SIMD `{}`", intrinsic, ty)); fx.tcx.dcx().span_err(span, format!("invalid monomorphization of `{}` intrinsic: expected SIMD input type, found non-SIMD `{}`", intrinsic, ty));
// Prevent verifier error // Prevent verifier error
fx.bcx.ins().trap(TrapCode::UnreachableCodeReached); fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
} }
@ -192,7 +192,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
.try_into() .try_into()
.unwrap(), .unwrap(),
_ => { _ => {
fx.tcx.sess.span_err( fx.tcx.dcx().span_err(
span, span,
format!("simd_shuffle index must be an array of `u32`, got `{}`", idx_ty), format!("simd_shuffle index must be an array of `u32`, got `{}`", idx_ty),
); );
@ -278,7 +278,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
{ {
idx_const idx_const
} else { } else {
fx.tcx.sess.span_fatal(span, "Index argument for `simd_insert` is not a constant"); fx.tcx.dcx().span_fatal(span, "Index argument for `simd_insert` is not a constant");
}; };
let idx: u32 = idx_const let idx: u32 = idx_const
@ -286,7 +286,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
.unwrap_or_else(|_| panic!("kind not scalar: {:?}", idx_const)); .unwrap_or_else(|_| panic!("kind not scalar: {:?}", idx_const));
let (lane_count, _lane_ty) = base.layout().ty.simd_size_and_type(fx.tcx); let (lane_count, _lane_ty) = base.layout().ty.simd_size_and_type(fx.tcx);
if u64::from(idx) >= lane_count { if u64::from(idx) >= lane_count {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
fx.mir.span, fx.mir.span,
format!("[simd_insert] idx {} >= lane_count {}", idx, lane_count), format!("[simd_insert] idx {} >= lane_count {}", idx, lane_count),
); );
@ -316,7 +316,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
{ {
idx_const idx_const
} else { } else {
fx.tcx.sess.span_warn(span, "Index argument for `simd_extract` is not a constant"); fx.tcx.dcx().span_warn(span, "Index argument for `simd_extract` is not a constant");
let trap_block = fx.bcx.create_block(); let trap_block = fx.bcx.create_block();
let true_ = fx.bcx.ins().iconst(types::I8, 1); let true_ = fx.bcx.ins().iconst(types::I8, 1);
let ret_block = fx.get_block(target); let ret_block = fx.get_block(target);
@ -334,7 +334,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
.unwrap_or_else(|_| panic!("kind not scalar: {:?}", idx_const)); .unwrap_or_else(|_| panic!("kind not scalar: {:?}", idx_const));
let (lane_count, _lane_ty) = v.layout().ty.simd_size_and_type(fx.tcx); let (lane_count, _lane_ty) = v.layout().ty.simd_size_and_type(fx.tcx);
if u64::from(idx) >= lane_count { if u64::from(idx) >= lane_count {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
fx.mir.span, fx.mir.span,
format!("[simd_extract] idx {} >= lane_count {}", idx, lane_count), format!("[simd_extract] idx {} >= lane_count {}", idx, lane_count),
); );
@ -859,7 +859,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
match lane_ty.kind() { match lane_ty.kind() {
ty::Int(_) | ty::Uint(_) => {} ty::Int(_) | ty::Uint(_) => {}
_ => { _ => {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
span, span,
format!( format!(
"invalid monomorphization of `simd_bitmask` intrinsic: \ "invalid monomorphization of `simd_bitmask` intrinsic: \
@ -899,7 +899,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
&& len.try_eval_target_usize(fx.tcx, ty::ParamEnv::reveal_all()) && len.try_eval_target_usize(fx.tcx, ty::ParamEnv::reveal_all())
== Some(expected_bytes) => {} == Some(expected_bytes) => {}
_ => { _ => {
fx.tcx.sess.span_fatal( fx.tcx.dcx().span_fatal(
span, span,
format!( format!(
"invalid monomorphization of `simd_bitmask` intrinsic: \ "invalid monomorphization of `simd_bitmask` intrinsic: \
@ -1117,7 +1117,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
} }
_ => { _ => {
fx.tcx.sess.span_err(span, format!("Unknown SIMD intrinsic {}", intrinsic)); fx.tcx.dcx().span_err(span, format!("Unknown SIMD intrinsic {}", intrinsic));
// Prevent verifier error // Prevent verifier error
fx.bcx.ins().trap(TrapCode::UnreachableCodeReached); fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
return; return;

View file

@ -177,13 +177,15 @@ impl CodegenBackend for CraneliftCodegenBackend {
use rustc_session::config::Lto; use rustc_session::config::Lto;
match sess.lto() { match sess.lto() {
Lto::No | Lto::ThinLocal => {} Lto::No | Lto::ThinLocal => {}
Lto::Thin | Lto::Fat => sess.warn("LTO is not supported. You may get a linker error."), Lto::Thin | Lto::Fat => {
sess.dcx().warn("LTO is not supported. You may get a linker error.")
}
} }
let mut config = self.config.borrow_mut(); let mut config = self.config.borrow_mut();
if config.is_none() { if config.is_none() {
let new_config = BackendConfig::from_opts(&sess.opts.cg.llvm_args) let new_config = BackendConfig::from_opts(&sess.opts.cg.llvm_args)
.unwrap_or_else(|err| sess.fatal(err)); .unwrap_or_else(|err| sess.dcx().fatal(err));
*config = Some(new_config); *config = Some(new_config);
} }
} }
@ -202,7 +204,7 @@ impl CodegenBackend for CraneliftCodegenBackend {
metadata: EncodedMetadata, metadata: EncodedMetadata,
need_metadata_module: bool, need_metadata_module: bool,
) -> Box<dyn Any> { ) -> Box<dyn Any> {
tcx.sess.abort_if_errors(); tcx.dcx().abort_if_errors();
let config = self.config.borrow().clone().unwrap(); let config = self.config.borrow().clone().unwrap();
match config.codegen_mode { match config.codegen_mode {
CodegenMode::Aot => driver::aot::run_aot(tcx, config, metadata, need_metadata_module), CodegenMode::Aot => driver::aot::run_aot(tcx, config, metadata, need_metadata_module),
@ -211,7 +213,7 @@ impl CodegenBackend for CraneliftCodegenBackend {
driver::jit::run_jit(tcx, config); driver::jit::run_jit(tcx, config);
#[cfg(not(feature = "jit"))] #[cfg(not(feature = "jit"))]
tcx.sess.fatal("jit support was disabled when compiling rustc_codegen_cranelift"); tcx.dcx().fatal("jit support was disabled when compiling rustc_codegen_cranelift");
} }
} }
} }
@ -243,7 +245,7 @@ impl CodegenBackend for CraneliftCodegenBackend {
fn target_triple(sess: &Session) -> target_lexicon::Triple { fn target_triple(sess: &Session) -> target_lexicon::Triple {
match sess.target.llvm_target.parse() { match sess.target.llvm_target.parse() {
Ok(triple) => triple, Ok(triple) => triple,
Err(err) => sess.fatal(format!("target not recognized: {}", err)), Err(err) => sess.dcx().fatal(format!("target not recognized: {}", err)),
} }
} }
@ -310,17 +312,18 @@ fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Arc<dyn isa::Tar
Some(value) => { Some(value) => {
let mut builder = let mut builder =
cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| { cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
sess.fatal(format!("can't compile for {}: {}", target_triple, err)); sess.dcx().fatal(format!("can't compile for {}: {}", target_triple, err));
}); });
if let Err(_) = builder.enable(value) { if let Err(_) = builder.enable(value) {
sess.fatal("the specified target cpu isn't currently supported by Cranelift."); sess.dcx()
.fatal("the specified target cpu isn't currently supported by Cranelift.");
} }
builder builder
} }
None => { None => {
let mut builder = let mut builder =
cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| { cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
sess.fatal(format!("can't compile for {}: {}", target_triple, err)); sess.dcx().fatal(format!("can't compile for {}: {}", target_triple, err));
}); });
if target_triple.architecture == target_lexicon::Architecture::X86_64 { if target_triple.architecture == target_lexicon::Architecture::X86_64 {
// Don't use "haswell" as the default, as it implies `has_lzcnt`. // Don't use "haswell" as the default, as it implies `has_lzcnt`.
@ -333,7 +336,7 @@ fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Arc<dyn isa::Tar
match isa_builder.finish(flags) { match isa_builder.finish(flags) {
Ok(target_isa) => target_isa, Ok(target_isa) => target_isa,
Err(err) => sess.fatal(format!("failed to build TargetIsa: {}", err)), Err(err) => sess.dcx().fatal(format!("failed to build TargetIsa: {}", err)),
} }
} }

View file

@ -74,7 +74,7 @@ pub(crate) fn maybe_create_entry_wrapper(
let cmain_func_id = match m.declare_function(entry_name, Linkage::Export, &cmain_sig) { let cmain_func_id = match m.declare_function(entry_name, Linkage::Export, &cmain_sig) {
Ok(func_id) => func_id, Ok(func_id) => func_id,
Err(err) => { Err(err) => {
tcx.sess tcx.dcx()
.fatal(format!("entry symbol `{entry_name}` declared multiple times: {err}")); .fatal(format!("entry symbol `{entry_name}` declared multiple times: {err}"));
} }
}; };
@ -171,7 +171,7 @@ pub(crate) fn maybe_create_entry_wrapper(
} }
if let Err(err) = m.define_function(cmain_func_id, &mut ctx) { if let Err(err) = m.define_function(cmain_func_id, &mut ctx) {
tcx.sess.fatal(format!("entry symbol `{entry_name}` defined multiple times: {err}")); tcx.dcx().fatal(format!("entry symbol `{entry_name}` defined multiple times: {err}"));
} }
unwind_context.add_function(cmain_func_id, &ctx, m.isa()); unwind_context.add_function(cmain_func_id, &ctx, m.isa());

View file

@ -397,7 +397,7 @@ impl<'tcx> CPlace<'tcx> {
if layout.size.bytes() >= u64::from(u32::MAX - 16) { if layout.size.bytes() >= u64::from(u32::MAX - 16) {
fx.tcx fx.tcx
.sess .dcx()
.fatal(format!("values of type {} are too big to store on the stack", layout.ty)); .fatal(format!("values of type {} are too big to store on the stack", layout.ty));
} }

View file

@ -109,7 +109,7 @@ enum ConstraintOrRegister {
impl<'a, 'gcc, 'tcx> AsmBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tcx> { impl<'a, 'gcc, 'tcx> AsmBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tcx> {
fn codegen_inline_asm(&mut self, template: &[InlineAsmTemplatePiece], rust_operands: &[InlineAsmOperandRef<'tcx, Self>], options: InlineAsmOptions, span: &[Span], instance: Instance<'_>, _dest_catch_funclet: Option<(Self::BasicBlock, Self::BasicBlock, Option<&Self::Funclet>)>) { fn codegen_inline_asm(&mut self, template: &[InlineAsmTemplatePiece], rust_operands: &[InlineAsmOperandRef<'tcx, Self>], options: InlineAsmOptions, span: &[Span], instance: Instance<'_>, _dest_catch_funclet: Option<(Self::BasicBlock, Self::BasicBlock, Option<&Self::Funclet>)>) {
if options.contains(InlineAsmOptions::MAY_UNWIND) { if options.contains(InlineAsmOptions::MAY_UNWIND) {
self.sess() self.sess().dcx()
.create_err(UnwindingInlineAsm { span: span[0] }) .create_err(UnwindingInlineAsm { span: span[0] })
.emit(); .emit();
return; return;

View file

@ -80,7 +80,7 @@ pub fn from_fn_attrs<'gcc, 'tcx>(
let span = cx.tcx let span = cx.tcx
.get_attr(instance.def_id(), sym::target_feature) .get_attr(instance.def_id(), sym::target_feature)
.map_or_else(|| cx.tcx.def_span(instance.def_id()), |a| a.span); .map_or_else(|| cx.tcx.def_span(instance.def_id()), |a| a.span);
cx.tcx.sess.create_err(TiedTargetFeatures { cx.tcx.dcx().create_err(TiedTargetFeatures {
features: features.join(", "), features: features.join(", "),
span, span,
}) })

View file

@ -24,7 +24,7 @@ fn set_global_alignment<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, gv: LValue<'gcc>
match Align::from_bits(min) { match Align::from_bits(min) {
Ok(min) => align = align.max(min), Ok(min) => align = align.max(min),
Err(err) => { Err(err) => {
cx.sess().emit_err(InvalidMinimumAlignment { err: err.to_string() }); cx.sess().dcx().emit_err(InvalidMinimumAlignment { err: err.to_string() });
} }
} }
} }

View file

@ -500,9 +500,9 @@ impl<'gcc, 'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'gcc, 'tcx> {
#[inline] #[inline]
fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! { fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
if let LayoutError::SizeOverflow(_) | LayoutError::ReferencesError(_) = err { if let LayoutError::SizeOverflow(_) | LayoutError::ReferencesError(_) = err {
self.sess().emit_fatal(respan(span, err.into_diagnostic())) self.tcx.dcx().emit_fatal(respan(span, err.into_diagnostic()))
} else { } else {
self.tcx.sess.emit_fatal(ssa_errors::FailedToGetLayout { span, ty, err }) self.tcx.dcx().emit_fatal(ssa_errors::FailedToGetLayout { span, ty, err })
} }
} }
} }
@ -518,7 +518,7 @@ impl<'gcc, 'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'gcc, 'tcx> {
fn_abi_request: FnAbiRequest<'tcx>, fn_abi_request: FnAbiRequest<'tcx>,
) -> ! { ) -> ! {
if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err { if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err {
self.sess().emit_fatal(respan(span, err)) self.tcx.dcx().emit_fatal(respan(span, err))
} else { } else {
match fn_abi_request { match fn_abi_request {
FnAbiRequest::OfFnPtr { sig, extra_args } => { FnAbiRequest::OfFnPtr { sig, extra_args } => {

View file

@ -52,7 +52,7 @@ pub(crate) fn global_gcc_features(sess: &Session, diagnostics: bool) -> Vec<Stri
Some(c @ ('+' | '-')) => c, Some(c @ ('+' | '-')) => c,
Some(_) => { Some(_) => {
if diagnostics { if diagnostics {
sess.emit_warning(UnknownCTargetFeaturePrefix { feature: s }); sess.dcx().emit_warning(UnknownCTargetFeaturePrefix { feature: s });
} }
return None; return None;
} }
@ -79,7 +79,7 @@ pub(crate) fn global_gcc_features(sess: &Session, diagnostics: bool) -> Vec<Stri
else { else {
UnknownCTargetFeature { feature, rust_feature: PossibleFeature::None } UnknownCTargetFeature { feature, rust_feature: PossibleFeature::None }
}; };
sess.emit_warning(unknown_feature); sess.dcx().emit_warning(unknown_feature);
} }
if diagnostics { if diagnostics {
@ -114,7 +114,7 @@ pub(crate) fn global_gcc_features(sess: &Session, diagnostics: bool) -> Vec<Stri
if diagnostics { if diagnostics {
if let Some(f) = check_tied_features(sess, &featsmap) { if let Some(f) = check_tied_features(sess, &featsmap) {
sess.emit_err(TargetFeatureDisableOrEnable { sess.dcx().emit_err(TargetFeatureDisableOrEnable {
features: f, features: f,
span: None, span: None,
missing_features: None, missing_features: None,

View file

@ -262,7 +262,7 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'a, 'gcc, 'tcx> {
_ => bug!(), _ => bug!(),
}, },
None => { None => {
tcx.sess.emit_err(InvalidMonomorphization::BasicIntegerType { span, name, ty }); tcx.dcx().emit_err(InvalidMonomorphization::BasicIntegerType { span, name, ty });
return; return;
} }
} }

View file

@ -34,7 +34,7 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>(
// macros for error handling: // macros for error handling:
macro_rules! return_error { macro_rules! return_error {
($err:expr) => {{ ($err:expr) => {{
bx.sess().emit_err($err); bx.tcx.dcx().emit_err($err);
return Err(()); return Err(());
}}; }};
} }
@ -390,7 +390,7 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>(
) -> Result<RValue<'gcc>, ()> { ) -> Result<RValue<'gcc>, ()> {
macro_rules! return_error { macro_rules! return_error {
($err:expr) => {{ ($err:expr) => {{
bx.sess().emit_err($err); bx.tcx.dcx().emit_err($err);
return Err(()); return Err(());
}}; }};
} }

View file

@ -191,7 +191,7 @@ impl CodegenBackend for GccCodegenBackend {
#[cfg(feature="master")] #[cfg(feature="master")]
gccjit::set_global_personality_function_name(b"rust_eh_personality\0"); gccjit::set_global_personality_function_name(b"rust_eh_personality\0");
if sess.lto() == Lto::Thin { if sess.lto() == Lto::Thin {
sess.emit_warning(LTONotSupported {}); sess.dcx().emit_warning(LTONotSupported {});
} }
#[cfg(not(feature="master"))] #[cfg(not(feature="master"))]

View file

@ -82,7 +82,7 @@ pub fn sanitize_attrs<'ll>(
let mte_feature = let mte_feature =
features.iter().map(|s| &s[..]).rfind(|n| ["+mte", "-mte"].contains(&&n[..])); features.iter().map(|s| &s[..]).rfind(|n| ["+mte", "-mte"].contains(&&n[..]));
if let None | Some("-mte") = mte_feature { if let None | Some("-mte") = mte_feature {
cx.tcx.sess.emit_err(SanitizerMemtagRequiresMte); cx.tcx.dcx().emit_err(SanitizerMemtagRequiresMte);
} }
attrs.push(llvm::AttributeKind::SanitizeMemTag.create_attr(cx.llcx)); attrs.push(llvm::AttributeKind::SanitizeMemTag.create_attr(cx.llcx));
@ -444,7 +444,7 @@ pub fn from_fn_attrs<'ll, 'tcx>(
.next() .next()
.map_or_else(|| cx.tcx.def_span(instance.def_id()), |a| a.span); .map_or_else(|| cx.tcx.def_span(instance.def_id()), |a| a.span);
cx.tcx cx.tcx
.sess .dcx()
.create_err(TargetFeatureDisableOrEnable { .create_err(TargetFeatureDisableOrEnable {
features: f, features: f,
span: Some(span), span: Some(span),

View file

@ -99,7 +99,7 @@ impl<'a> ArchiveBuilder<'a> for LlvmArchiveBuilder<'a> {
fn build(mut self: Box<Self>, output: &Path) -> bool { fn build(mut self: Box<Self>, output: &Path) -> bool {
match self.build_with_llvm(output) { match self.build_with_llvm(output) {
Ok(any_members) => any_members, Ok(any_members) => any_members,
Err(e) => self.sess.emit_fatal(ArchiveBuildFailure { error: e }), Err(e) => self.sess.dcx().emit_fatal(ArchiveBuildFailure { error: e }),
} }
} }
} }
@ -175,7 +175,7 @@ impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder {
match std::fs::write(&def_file_path, def_file_content) { match std::fs::write(&def_file_path, def_file_content) {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
sess.emit_fatal(ErrorWritingDEFFile { error: e }); sess.dcx().emit_fatal(ErrorWritingDEFFile { error: e });
} }
}; };
@ -217,14 +217,14 @@ impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder {
match dlltool_cmd.output() { match dlltool_cmd.output() {
Err(e) => { Err(e) => {
sess.emit_fatal(ErrorCallingDllTool { sess.dcx().emit_fatal(ErrorCallingDllTool {
dlltool_path: dlltool.to_string_lossy(), dlltool_path: dlltool.to_string_lossy(),
error: e, error: e,
}); });
} }
// dlltool returns '0' on failure, so check for error output instead. // dlltool returns '0' on failure, so check for error output instead.
Ok(output) if !output.stderr.is_empty() => { Ok(output) if !output.stderr.is_empty() => {
sess.emit_fatal(DlltoolFailImportLibrary { sess.dcx().emit_fatal(DlltoolFailImportLibrary {
dlltool_path: dlltool.to_string_lossy(), dlltool_path: dlltool.to_string_lossy(),
dlltool_args: dlltool_cmd dlltool_args: dlltool_cmd
.get_args() .get_args()
@ -282,7 +282,7 @@ impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder {
}; };
if result == crate::llvm::LLVMRustResult::Failure { if result == crate::llvm::LLVMRustResult::Failure {
sess.emit_fatal(ErrorCreatingImportLibrary { sess.dcx().emit_fatal(ErrorCreatingImportLibrary {
lib_name, lib_name,
error: llvm::last_error().unwrap_or("unknown LLVM error".to_string()), error: llvm::last_error().unwrap_or("unknown LLVM error".to_string()),
}); });
@ -354,7 +354,7 @@ impl<'a> LlvmArchiveBuilder<'a> {
let kind = kind let kind = kind
.parse::<ArchiveKind>() .parse::<ArchiveKind>()
.map_err(|_| kind) .map_err(|_| kind)
.unwrap_or_else(|kind| self.sess.emit_fatal(UnknownArchiveKind { kind })); .unwrap_or_else(|kind| self.sess.dcx().emit_fatal(UnknownArchiveKind { kind }));
let mut additions = mem::take(&mut self.additions); let mut additions = mem::take(&mut self.additions);
let mut strings = Vec::new(); let mut strings = Vec::new();

View file

@ -126,7 +126,7 @@ pub fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> OwnedTargetMach
tcx.backend_optimization_level(()), tcx.backend_optimization_level(()),
tcx.global_backend_features(()), tcx.global_backend_features(()),
)(config) )(config)
.unwrap_or_else(|err| llvm_err(tcx.sess.dcx(), err).raise()) .unwrap_or_else(|err| llvm_err(tcx.dcx(), err).raise())
} }
pub fn to_llvm_opt_settings( pub fn to_llvm_opt_settings(
@ -245,12 +245,12 @@ pub fn target_machine_factory(
match sess.opts.debuginfo_compression { match sess.opts.debuginfo_compression {
rustc_session::config::DebugInfoCompression::Zlib => { rustc_session::config::DebugInfoCompression::Zlib => {
if !unsafe { LLVMRustLLVMHasZlibCompressionForDebugSymbols() } { if !unsafe { LLVMRustLLVMHasZlibCompressionForDebugSymbols() } {
sess.emit_warning(UnknownCompression { algorithm: "zlib" }); sess.dcx().emit_warning(UnknownCompression { algorithm: "zlib" });
} }
} }
rustc_session::config::DebugInfoCompression::Zstd => { rustc_session::config::DebugInfoCompression::Zstd => {
if !unsafe { LLVMRustLLVMHasZstdCompressionForDebugSymbols() } { if !unsafe { LLVMRustLLVMHasZstdCompressionForDebugSymbols() } {
sess.emit_warning(UnknownCompression { algorithm: "zstd" }); sess.dcx().emit_warning(UnknownCompression { algorithm: "zstd" });
} }
} }
rustc_session::config::DebugInfoCompression::None => {} rustc_session::config::DebugInfoCompression::None => {}

View file

@ -131,10 +131,10 @@ fn set_global_alignment<'ll>(cx: &CodegenCx<'ll, '_>, gv: &'ll Value, mut align:
Ok(min) => align = align.max(min), Ok(min) => align = align.max(min),
Err(err) => match err { Err(err) => match err {
AlignFromBytesError::NotPowerOfTwo(align) => { AlignFromBytesError::NotPowerOfTwo(align) => {
cx.sess().emit_err(InvalidMinimumAlignmentNotPowerOfTwo { align }); cx.sess().dcx().emit_err(InvalidMinimumAlignmentNotPowerOfTwo { align });
} }
AlignFromBytesError::TooLarge(align) => { AlignFromBytesError::TooLarge(align) => {
cx.sess().emit_err(InvalidMinimumAlignmentTooLarge { align }); cx.sess().dcx().emit_err(InvalidMinimumAlignmentTooLarge { align });
} }
}, },
} }
@ -169,7 +169,7 @@ fn check_and_apply_linkage<'ll, 'tcx>(
let mut real_name = "_rust_extern_with_linkage_".to_string(); let mut real_name = "_rust_extern_with_linkage_".to_string();
real_name.push_str(sym); real_name.push_str(sym);
let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| { let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| {
cx.sess().emit_fatal(SymbolAlreadyDefined { cx.sess().dcx().emit_fatal(SymbolAlreadyDefined {
span: cx.tcx.def_span(def_id), span: cx.tcx.def_span(def_id),
symbol_name: sym, symbol_name: sym,
}) })

View file

@ -1014,9 +1014,9 @@ impl<'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
#[inline] #[inline]
fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! { fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
if let LayoutError::SizeOverflow(_) | LayoutError::ReferencesError(_) = err { if let LayoutError::SizeOverflow(_) | LayoutError::ReferencesError(_) = err {
self.sess().emit_fatal(Spanned { span, node: err.into_diagnostic() }) self.tcx.dcx().emit_fatal(Spanned { span, node: err.into_diagnostic() })
} else { } else {
self.tcx.sess.emit_fatal(ssa_errors::FailedToGetLayout { span, ty, err }) self.tcx.dcx().emit_fatal(ssa_errors::FailedToGetLayout { span, ty, err })
} }
} }
} }
@ -1032,7 +1032,7 @@ impl<'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
fn_abi_request: FnAbiRequest<'tcx>, fn_abi_request: FnAbiRequest<'tcx>,
) -> ! { ) -> ! {
if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err { if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err {
self.sess().emit_fatal(Spanned { span, node: err }) self.tcx.dcx().emit_fatal(Spanned { span, node: err })
} else { } else {
match fn_abi_request { match fn_abi_request {
FnAbiRequest::OfFnPtr { sig, extra_args } => { FnAbiRequest::OfFnPtr { sig, extra_args } => {

View file

@ -285,7 +285,7 @@ impl<'ll, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'_, 'll, 'tcx> {
_ => bug!(), _ => bug!(),
}, },
None => { None => {
tcx.sess.emit_err(InvalidMonomorphization::BasicIntegerType { tcx.dcx().emit_err(InvalidMonomorphization::BasicIntegerType {
span, span,
name, name,
ty, ty,
@ -921,7 +921,7 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
) -> Result<&'ll Value, ()> { ) -> Result<&'ll Value, ()> {
macro_rules! return_error { macro_rules! return_error {
($diag: expr) => {{ ($diag: expr) => {{
bx.sess().emit_err($diag); bx.sess().dcx().emit_err($diag);
return Err(()); return Err(());
}}; }};
} }
@ -1059,7 +1059,7 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
.map(|(arg_idx, val)| { .map(|(arg_idx, val)| {
let idx = val.unwrap_leaf().try_to_i32().unwrap(); let idx = val.unwrap_leaf().try_to_i32().unwrap();
if idx >= i32::try_from(total_len).unwrap() { if idx >= i32::try_from(total_len).unwrap() {
bx.sess().emit_err(InvalidMonomorphization::ShuffleIndexOutOfBounds { bx.sess().dcx().emit_err(InvalidMonomorphization::ShuffleIndexOutOfBounds {
span, span,
name, name,
arg_idx: arg_idx as u64, arg_idx: arg_idx as u64,
@ -1118,20 +1118,24 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
let val = bx.const_get_elt(vector, i as u64); let val = bx.const_get_elt(vector, i as u64);
match bx.const_to_opt_u128(val, true) { match bx.const_to_opt_u128(val, true) {
None => { None => {
bx.sess().emit_err(InvalidMonomorphization::ShuffleIndexNotConstant { bx.sess().dcx().emit_err(
span, InvalidMonomorphization::ShuffleIndexNotConstant {
name, span,
arg_idx, name,
}); arg_idx,
},
);
None None
} }
Some(idx) if idx >= total_len => { Some(idx) if idx >= total_len => {
bx.sess().emit_err(InvalidMonomorphization::ShuffleIndexOutOfBounds { bx.sess().dcx().emit_err(
span, InvalidMonomorphization::ShuffleIndexOutOfBounds {
name, span,
arg_idx, name,
total_len, arg_idx,
}); total_len,
},
);
None None
} }
Some(idx) => Some(bx.const_i32(idx as i32)), Some(idx) => Some(bx.const_i32(idx as i32)),
@ -1276,7 +1280,7 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
) -> Result<&'ll Value, ()> { ) -> Result<&'ll Value, ()> {
macro_rules! return_error { macro_rules! return_error {
($diag: expr) => {{ ($diag: expr) => {{
bx.sess().emit_err($diag); bx.sess().dcx().emit_err($diag);
return Err(()); return Err(());
}}; }};
} }

View file

@ -529,7 +529,7 @@ pub(crate) fn global_llvm_features(sess: &Session, diagnostics: bool) -> Vec<Str
Some(c @ ('+' | '-')) => c, Some(c @ ('+' | '-')) => c,
Some(_) => { Some(_) => {
if diagnostics { if diagnostics {
sess.emit_warning(UnknownCTargetFeaturePrefix { feature: s }); sess.dcx().emit_warning(UnknownCTargetFeaturePrefix { feature: s });
} }
return None; return None;
} }
@ -557,12 +557,12 @@ pub(crate) fn global_llvm_features(sess: &Session, diagnostics: bool) -> Vec<Str
} else { } else {
UnknownCTargetFeature { feature, rust_feature: PossibleFeature::None } UnknownCTargetFeature { feature, rust_feature: PossibleFeature::None }
}; };
sess.emit_warning(unknown_feature); sess.dcx().emit_warning(unknown_feature);
} else if feature_state } else if feature_state
.is_some_and(|(_name, feature_gate)| !feature_gate.is_stable()) .is_some_and(|(_name, feature_gate)| !feature_gate.is_stable())
{ {
// An unstable feature. Warn about using it. // An unstable feature. Warn about using it.
sess.emit_warning(UnstableCTargetFeature { feature }); sess.dcx().emit_warning(UnstableCTargetFeature { feature });
} }
} }
@ -598,7 +598,7 @@ pub(crate) fn global_llvm_features(sess: &Session, diagnostics: bool) -> Vec<Str
features.extend(feats); features.extend(feats);
if diagnostics && let Some(f) = check_tied_features(sess, &featsmap) { if diagnostics && let Some(f) = check_tied_features(sess, &featsmap) {
sess.emit_err(TargetFeatureDisableOrEnable { sess.dcx().emit_err(TargetFeatureDisableOrEnable {
features: f, features: f,
span: None, span: None,
missing_features: None, missing_features: None,

View file

@ -26,6 +26,7 @@ impl<'tcx> PreDefineMethods<'tcx> for CodegenCx<'_, 'tcx> {
let g = self.define_global(symbol_name, llty).unwrap_or_else(|| { let g = self.define_global(symbol_name, llty).unwrap_or_else(|| {
self.sess() self.sess()
.dcx()
.emit_fatal(SymbolAlreadyDefined { span: self.tcx.def_span(def_id), symbol_name }) .emit_fatal(SymbolAlreadyDefined { span: self.tcx.def_span(def_id), symbol_name })
}); });

View file

@ -88,7 +88,7 @@ impl<'tcx> AssertModuleSource<'tcx> {
sym::any => (CguReuse::PreLto, ComparisonKind::AtLeast), sym::any => (CguReuse::PreLto, ComparisonKind::AtLeast),
other => { other => {
self.tcx self.tcx
.sess .dcx()
.emit_fatal(errors::UnknownReuseKind { span: attr.span, kind: other }); .emit_fatal(errors::UnknownReuseKind { span: attr.span, kind: other });
} }
} }
@ -97,7 +97,7 @@ impl<'tcx> AssertModuleSource<'tcx> {
}; };
if !self.tcx.sess.opts.unstable_opts.query_dep_graph { if !self.tcx.sess.opts.unstable_opts.query_dep_graph {
self.tcx.sess.emit_fatal(errors::MissingQueryDepGraph { span: attr.span }); self.tcx.dcx().emit_fatal(errors::MissingQueryDepGraph { span: attr.span });
} }
if !self.check_config(attr) { if !self.check_config(attr) {
@ -109,7 +109,7 @@ impl<'tcx> AssertModuleSource<'tcx> {
let crate_name = self.tcx.crate_name(LOCAL_CRATE).to_string(); let crate_name = self.tcx.crate_name(LOCAL_CRATE).to_string();
if !user_path.starts_with(&crate_name) { if !user_path.starts_with(&crate_name) {
self.tcx.sess.emit_fatal(errors::MalformedCguName { self.tcx.dcx().emit_fatal(errors::MalformedCguName {
span: attr.span, span: attr.span,
user_path, user_path,
crate_name, crate_name,
@ -139,7 +139,7 @@ impl<'tcx> AssertModuleSource<'tcx> {
if !self.available_cgus.contains(&cgu_name) { if !self.available_cgus.contains(&cgu_name) {
let cgu_names: Vec<&str> = let cgu_names: Vec<&str> =
self.available_cgus.items().map(|cgu| cgu.as_str()).into_sorted_stable_ord(); self.available_cgus.items().map(|cgu| cgu.as_str()).into_sorted_stable_ord();
self.tcx.sess.emit_err(errors::NoModuleNamed { self.tcx.dcx().emit_err(errors::NoModuleNamed {
span: attr.span, span: attr.span,
user_path, user_path,
cgu_name, cgu_name,
@ -162,7 +162,7 @@ impl<'tcx> AssertModuleSource<'tcx> {
if let Some(value) = item.value_str() { if let Some(value) = item.value_str() {
return value; return value;
} else { } else {
self.tcx.sess.emit_fatal(errors::FieldAssociatedValueExpected { self.tcx.dcx().emit_fatal(errors::FieldAssociatedValueExpected {
span: item.span(), span: item.span(),
name, name,
}); });
@ -170,7 +170,7 @@ impl<'tcx> AssertModuleSource<'tcx> {
} }
} }
self.tcx.sess.emit_fatal(errors::NoField { span: attr.span, name }); self.tcx.dcx().emit_fatal(errors::NoField { span: attr.span, name });
} }
/// Scan for a `cfg="foo"` attribute and check whether we have a /// Scan for a `cfg="foo"` attribute and check whether we have a
@ -278,7 +278,7 @@ impl CguReuseTracker {
if error { if error {
let at_least = if at_least { 1 } else { 0 }; let at_least = if at_least { 1 } else { 0 };
sess.emit_err(errors::IncorrectCguReuseType { sess.dcx().emit_err(errors::IncorrectCguReuseType {
span: *error_span, span: *error_span,
cgu_user_name, cgu_user_name,
actual_reuse, actual_reuse,
@ -287,7 +287,7 @@ impl CguReuseTracker {
}); });
} }
} else { } else {
sess.emit_fatal(errors::CguNotRecorded { cgu_user_name, cgu_name }); sess.dcx().emit_fatal(errors::CguNotRecorded { cgu_user_name, cgu_name });
} }
} }
} }

View file

@ -220,7 +220,7 @@ impl<'a> ArchiveBuilder<'a> for ArArchiveBuilder<'a> {
let sess = self.sess; let sess = self.sess;
match self.build_inner(output) { match self.build_inner(output) {
Ok(any_members) => any_members, Ok(any_members) => any_members,
Err(e) => sess.emit_fatal(ArchiveBuildFailure { error: e }), Err(e) => sess.dcx().emit_fatal(ArchiveBuildFailure { error: e }),
} }
} }
} }
@ -234,7 +234,7 @@ impl<'a> ArArchiveBuilder<'a> {
"coff" => ArchiveKind::Coff, "coff" => ArchiveKind::Coff,
"aix_big" => ArchiveKind::AixBig, "aix_big" => ArchiveKind::AixBig,
kind => { kind => {
self.sess.emit_fatal(UnknownArchiveKind { kind }); self.sess.dcx().emit_fatal(UnknownArchiveKind { kind });
} }
}; };

View file

@ -98,7 +98,7 @@ pub fn link_binary<'a>(
let tmpdir = TempFileBuilder::new() let tmpdir = TempFileBuilder::new()
.prefix("rustc") .prefix("rustc")
.tempdir() .tempdir()
.unwrap_or_else(|error| sess.emit_fatal(errors::CreateTempDir { error })); .unwrap_or_else(|error| sess.dcx().emit_fatal(errors::CreateTempDir { error }));
let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps); let path = MaybeTempDir::new(tmpdir, sess.opts.cg.save_temps);
let output = out_filename( let output = out_filename(
sess, sess,
@ -161,11 +161,11 @@ pub fn link_binary<'a>(
if output.is_stdout() { if output.is_stdout() {
if output.is_tty() { if output.is_tty() {
sess.emit_err(errors::BinaryOutputToTty { sess.dcx().emit_err(errors::BinaryOutputToTty {
shorthand: OutputType::Exe.shorthand(), shorthand: OutputType::Exe.shorthand(),
}); });
} else if let Err(e) = copy_to_stdout(&out_filename) { } else if let Err(e) = copy_to_stdout(&out_filename) {
sess.emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e)); sess.dcx().emit_err(errors::CopyPath::new(&out_filename, output.as_path(), e));
} }
tempfiles_for_stdout_output.push(out_filename); tempfiles_for_stdout_output.push(out_filename);
} }
@ -380,8 +380,8 @@ fn link_rlib<'a>(
&& let Some(filename) = lib.filename && let Some(filename) = lib.filename
{ {
let path = find_native_static_library(filename.as_str(), true, &lib_search_paths, sess); let path = find_native_static_library(filename.as_str(), true, &lib_search_paths, sess);
let src = let src = read(path)
read(path).map_err(|e| sess.emit_fatal(errors::ReadFileError { message: e }))?; .map_err(|e| sess.dcx().emit_fatal(errors::ReadFileError { message: e }))?;
let (data, _) = create_wrapper_file(sess, b".bundled_lib".to_vec(), &src); let (data, _) = create_wrapper_file(sess, b".bundled_lib".to_vec(), &src);
let wrapper_file = emit_wrapper_file(sess, &data, tmpdir, filename.as_str()); let wrapper_file = emit_wrapper_file(sess, &data, tmpdir, filename.as_str());
packed_bundled_libs.push(wrapper_file); packed_bundled_libs.push(wrapper_file);
@ -393,7 +393,7 @@ fn link_rlib<'a>(
sess, sess,
); );
ab.add_archive(&path, Box::new(|_| false)).unwrap_or_else(|error| { ab.add_archive(&path, Box::new(|_| false)).unwrap_or_else(|error| {
sess.emit_fatal(errors::AddNativeLibrary { library_path: path, error }) sess.dcx().emit_fatal(errors::AddNativeLibrary { library_path: path, error })
}); });
} }
} }
@ -410,7 +410,7 @@ fn link_rlib<'a>(
); );
ab.add_archive(&output_path, Box::new(|_| false)).unwrap_or_else(|error| { ab.add_archive(&output_path, Box::new(|_| false)).unwrap_or_else(|error| {
sess.emit_fatal(errors::AddNativeLibrary { library_path: output_path, error }); sess.dcx().emit_fatal(errors::AddNativeLibrary { library_path: output_path, error });
}); });
} }
@ -475,7 +475,7 @@ fn collate_raw_dylibs<'a, 'b>(
// FIXME: when we add support for ordinals, figure out if we need to do anything // FIXME: when we add support for ordinals, figure out if we need to do anything
// if we have two DllImport values with the same name but different ordinals. // if we have two DllImport values with the same name but different ordinals.
if import.calling_convention != old_import.calling_convention { if import.calling_convention != old_import.calling_convention {
sess.emit_err(errors::MultipleExternalFuncDecl { sess.dcx().emit_err(errors::MultipleExternalFuncDecl {
span: import.span, span: import.span,
function: import.name, function: import.name,
library_name: &name, library_name: &name,
@ -558,7 +558,7 @@ fn link_staticlib<'a>(
archive_builder_builder archive_builder_builder
.extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs) .extract_bundled_libs(path, tempdir.as_ref(), &relevant_libs)
.unwrap_or_else(|e| sess.emit_fatal(e)); .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
for filename in relevant_libs { for filename in relevant_libs {
let joined = tempdir.as_ref().join(filename.as_str()); let joined = tempdir.as_ref().join(filename.as_str());
let path = joined.as_path(); let path = joined.as_path();
@ -570,7 +570,7 @@ fn link_staticlib<'a>(
}, },
); );
if let Err(e) = res { if let Err(e) = res {
sess.emit_fatal(e); sess.dcx().emit_fatal(e);
} }
ab.build(out_filename); ab.build(out_filename);
@ -596,9 +596,9 @@ fn link_staticlib<'a>(
all_rust_dylibs.push(&**path); all_rust_dylibs.push(&**path);
} else { } else {
if used_crate_source.rmeta.is_some() { if used_crate_source.rmeta.is_some() {
sess.emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name }); sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
} else { } else {
sess.emit_fatal(errors::LinkRlibError::NotFound { crate_name }); sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
} }
} }
} }
@ -715,8 +715,8 @@ fn link_dwarf_object<'a>(
}) { }) {
Ok(()) => {} Ok(()) => {}
Err(e) => { Err(e) => {
sess.emit_err(errors::ThorinErrorWrapper(e)); sess.dcx().emit_err(errors::ThorinErrorWrapper(e));
sess.abort_if_errors(); sess.dcx().abort_if_errors();
} }
} }
} }
@ -765,7 +765,7 @@ fn link_natively<'a>(
} }
// May have not found libraries in the right formats. // May have not found libraries in the right formats.
sess.abort_if_errors(); sess.dcx().abort_if_errors();
// Invoke the system linker // Invoke the system linker
info!("{:?}", &cmd); info!("{:?}", &cmd);
@ -955,22 +955,22 @@ fn link_natively<'a>(
) )
.is_some(); .is_some();
sess.emit_note(errors::LinkExeUnexpectedError); sess.dcx().emit_note(errors::LinkExeUnexpectedError);
if is_vs_installed && has_linker { if is_vs_installed && has_linker {
// the linker is broken // the linker is broken
sess.emit_note(errors::RepairVSBuildTools); sess.dcx().emit_note(errors::RepairVSBuildTools);
sess.emit_note(errors::MissingCppBuildToolComponent); sess.dcx().emit_note(errors::MissingCppBuildToolComponent);
} else if is_vs_installed { } else if is_vs_installed {
// the linker is not installed // the linker is not installed
sess.emit_note(errors::SelectCppBuildToolWorkload); sess.dcx().emit_note(errors::SelectCppBuildToolWorkload);
} else { } else {
// visual studio is not installed // visual studio is not installed
sess.emit_note(errors::VisualStudioNotInstalled); sess.dcx().emit_note(errors::VisualStudioNotInstalled);
} }
} }
} }
sess.abort_if_errors(); sess.dcx().abort_if_errors();
} }
info!("linker stderr:\n{}", escape_string(&prog.stderr)); info!("linker stderr:\n{}", escape_string(&prog.stderr));
info!("linker stdout:\n{}", escape_string(&prog.stdout)); info!("linker stdout:\n{}", escape_string(&prog.stdout));
@ -979,9 +979,9 @@ fn link_natively<'a>(
let linker_not_found = e.kind() == io::ErrorKind::NotFound; let linker_not_found = e.kind() == io::ErrorKind::NotFound;
if linker_not_found { if linker_not_found {
sess.emit_err(errors::LinkerNotFound { linker_path, error: e }); sess.dcx().emit_err(errors::LinkerNotFound { linker_path, error: e });
} else { } else {
sess.emit_err(errors::UnableToExeLinker { sess.dcx().emit_err(errors::UnableToExeLinker {
linker_path, linker_path,
error: e, error: e,
command_formatted: format!("{:?}", &cmd), command_formatted: format!("{:?}", &cmd),
@ -989,11 +989,11 @@ fn link_natively<'a>(
} }
if sess.target.is_like_msvc && linker_not_found { if sess.target.is_like_msvc && linker_not_found {
sess.emit_note(errors::MsvcMissingLinker); sess.dcx().emit_note(errors::MsvcMissingLinker);
sess.emit_note(errors::CheckInstalledVisualStudio); sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
sess.emit_note(errors::InsufficientVSCodeProduct); sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
} }
sess.abort_if_errors(); sess.dcx().abort_if_errors();
} }
} }
@ -1016,13 +1016,13 @@ fn link_natively<'a>(
if !prog.status.success() { if !prog.status.success() {
let mut output = prog.stderr.clone(); let mut output = prog.stderr.clone();
output.extend_from_slice(&prog.stdout); output.extend_from_slice(&prog.stdout);
sess.emit_warning(errors::ProcessingDymutilFailed { sess.dcx().emit_warning(errors::ProcessingDymutilFailed {
status: prog.status, status: prog.status,
output: escape_string(&output), output: escape_string(&output),
}); });
} }
} }
Err(error) => sess.emit_fatal(errors::UnableToRunDsymutil { error }), Err(error) => sess.dcx().emit_fatal(errors::UnableToRunDsymutil { error }),
} }
} }
@ -1091,14 +1091,14 @@ fn strip_symbols_with_external_utility<'a>(
if !prog.status.success() { if !prog.status.success() {
let mut output = prog.stderr.clone(); let mut output = prog.stderr.clone();
output.extend_from_slice(&prog.stdout); output.extend_from_slice(&prog.stdout);
sess.emit_warning(errors::StrippingDebugInfoFailed { sess.dcx().emit_warning(errors::StrippingDebugInfoFailed {
util, util,
status: prog.status, status: prog.status,
output: escape_string(&output), output: escape_string(&output),
}); });
} }
} }
Err(error) => sess.emit_fatal(errors::UnableToRun { util, error }), Err(error) => sess.dcx().emit_fatal(errors::UnableToRun { util, error }),
} }
} }
@ -1311,7 +1311,7 @@ pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
)), )),
(Some(linker), None) => { (Some(linker), None) => {
let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| { let stem = linker.file_stem().and_then(|stem| stem.to_str()).unwrap_or_else(|| {
sess.emit_fatal(errors::LinkerFileStem); sess.dcx().emit_fatal(errors::LinkerFileStem);
}); });
let flavor = sess.target.linker_flavor.with_linker_hints(stem); let flavor = sess.target.linker_flavor.with_linker_hints(stem);
Some((linker, flavor)) Some((linker, flavor))
@ -1456,15 +1456,15 @@ fn print_native_static_libs(
OutFileName::Real(path) => { OutFileName::Real(path) => {
out.overwrite(&lib_args.join(" "), sess); out.overwrite(&lib_args.join(" "), sess);
if !lib_args.is_empty() { if !lib_args.is_empty() {
sess.emit_note(errors::StaticLibraryNativeArtifactsToFile { path }); sess.dcx().emit_note(errors::StaticLibraryNativeArtifactsToFile { path });
} }
} }
OutFileName::Stdout => { OutFileName::Stdout => {
if !lib_args.is_empty() { if !lib_args.is_empty() {
sess.emit_note(errors::StaticLibraryNativeArtifacts); sess.dcx().emit_note(errors::StaticLibraryNativeArtifacts);
// Prefix for greppability // Prefix for greppability
// Note: This must not be translated as tools are allowed to depend on this exact string. // Note: This must not be translated as tools are allowed to depend on this exact string.
sess.note(format!("native-static-libs: {}", &lib_args.join(" "))); sess.dcx().note(format!("native-static-libs: {}", &lib_args.join(" ")));
} }
} }
} }
@ -1703,7 +1703,7 @@ fn self_contained_components(sess: &Session, crate_type: CrateType) -> LinkSelfC
// Emit an error if the user requested self-contained mode on the CLI but the target // Emit an error if the user requested self-contained mode on the CLI but the target
// explicitly refuses it. // explicitly refuses it.
if sess.target.link_self_contained.is_disabled() { if sess.target.link_self_contained.is_disabled() {
sess.emit_err(errors::UnsupportedLinkSelfContained); sess.dcx().emit_err(errors::UnsupportedLinkSelfContained);
} }
self_contained self_contained
} else { } else {
@ -1790,14 +1790,14 @@ fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_ty
match (crate_type, &sess.target.link_script) { match (crate_type, &sess.target.link_script) {
(CrateType::Cdylib | CrateType::Executable, Some(script)) => { (CrateType::Cdylib | CrateType::Executable, Some(script)) => {
if !sess.target.linker_flavor.is_gnu() { if !sess.target.linker_flavor.is_gnu() {
sess.emit_fatal(errors::LinkScriptUnavailable); sess.dcx().emit_fatal(errors::LinkScriptUnavailable);
} }
let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-"); let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");
let path = tmpdir.join(file_name); let path = tmpdir.join(file_name);
if let Err(error) = fs::write(&path, script.as_ref()) { if let Err(error) = fs::write(&path, script.as_ref()) {
sess.emit_fatal(errors::LinkScriptWriteFailure { path, error }); sess.dcx().emit_fatal(errors::LinkScriptWriteFailure { path, error });
} }
cmd.arg("--script"); cmd.arg("--script");
@ -1921,7 +1921,7 @@ fn add_linked_symbol_object(
let path = tmpdir.join("symbols.o"); let path = tmpdir.join("symbols.o");
let result = std::fs::write(&path, file.write().unwrap()); let result = std::fs::write(&path, file.write().unwrap());
if let Err(error) = result { if let Err(error) = result {
sess.emit_fatal(errors::FailedToWrite { path, error }); sess.dcx().emit_fatal(errors::FailedToWrite { path, error });
} }
cmd.add_object(&path); cmd.add_object(&path);
} }
@ -2390,7 +2390,7 @@ fn collect_natvis_visualizers(
visualizer_paths.push(visualizer_out_file); visualizer_paths.push(visualizer_out_file);
} }
Err(error) => { Err(error) => {
sess.emit_warning(errors::UnableToWriteDebuggerVisualizer { sess.dcx().emit_warning(errors::UnableToWriteDebuggerVisualizer {
path: visualizer_out_file, path: visualizer_out_file,
error, error,
}); });
@ -2425,7 +2425,7 @@ fn add_native_libs_from_crate(
let rlib = &codegen_results.crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap().0; let rlib = &codegen_results.crate_info.used_crate_source[&cnum].rlib.as_ref().unwrap().0;
archive_builder_builder archive_builder_builder
.extract_bundled_libs(rlib, tmpdir, bundled_libs) .extract_bundled_libs(rlib, tmpdir, bundled_libs)
.unwrap_or_else(|e| sess.emit_fatal(e)); .unwrap_or_else(|e| sess.dcx().emit_fatal(e));
} }
let native_libs = match cnum { let native_libs = match cnum {
@ -2798,7 +2798,7 @@ fn add_static_crate<'a>(
false false
}), }),
) { ) {
sess.emit_fatal(errors::RlibArchiveBuildFailure { error }); sess.dcx().emit_fatal(errors::RlibArchiveBuildFailure { error });
} }
if archive.build(&dst) { if archive.build(&dst) {
link_upstream(&dst); link_upstream(&dst);
@ -2872,14 +2872,14 @@ fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
("arm", "watchos") => "watchos", ("arm", "watchos") => "watchos",
(_, "macos") => "macosx", (_, "macos") => "macosx",
_ => { _ => {
sess.emit_err(errors::UnsupportedArch { arch, os }); sess.dcx().emit_err(errors::UnsupportedArch { arch, os });
return; return;
} }
}; };
let sdk_root = match get_apple_sdk_root(sdk_name) { let sdk_root = match get_apple_sdk_root(sdk_name) {
Ok(s) => s, Ok(s) => s,
Err(e) => { Err(e) => {
sess.emit_err(e); sess.dcx().emit_err(e);
return; return;
} }
}; };

View file

@ -446,11 +446,11 @@ impl<'a> Linker for GccLinker<'a> {
// FIXME(81490): ld64 doesn't support these flags but macOS 11 // FIXME(81490): ld64 doesn't support these flags but macOS 11
// has -needed-l{} / -needed_library {} // has -needed-l{} / -needed_library {}
// but we have no way to detect that here. // but we have no way to detect that here.
self.sess.emit_warning(errors::Ld64UnimplementedModifier); self.sess.dcx().emit_warning(errors::Ld64UnimplementedModifier);
} else if self.is_gnu && !self.sess.target.is_like_windows { } else if self.is_gnu && !self.sess.target.is_like_windows {
self.linker_arg("--no-as-needed"); self.linker_arg("--no-as-needed");
} else { } else {
self.sess.emit_warning(errors::LinkerUnsupportedModifier); self.sess.dcx().emit_warning(errors::LinkerUnsupportedModifier);
} }
} }
self.hint_dynamic(); self.hint_dynamic();
@ -504,7 +504,7 @@ impl<'a> Linker for GccLinker<'a> {
// FIXME(81490): ld64 as of macOS 11 supports the -needed_framework // FIXME(81490): ld64 as of macOS 11 supports the -needed_framework
// flag but we have no way to detect that here. // flag but we have no way to detect that here.
// self.cmd.arg("-needed_framework").arg(framework); // self.cmd.arg("-needed_framework").arg(framework);
self.sess.emit_warning(errors::Ld64UnimplementedModifier); self.sess.dcx().emit_warning(errors::Ld64UnimplementedModifier);
} }
self.cmd.arg("-framework").arg(framework); self.cmd.arg("-framework").arg(framework);
} }
@ -693,7 +693,7 @@ impl<'a> Linker for GccLinker<'a> {
} }
}; };
if let Err(error) = res { if let Err(error) = res {
self.sess.emit_fatal(errors::LibDefWriteFailure { error }); self.sess.dcx().emit_fatal(errors::LibDefWriteFailure { error });
} }
} else if is_windows { } else if is_windows {
let res: io::Result<()> = try { let res: io::Result<()> = try {
@ -708,7 +708,7 @@ impl<'a> Linker for GccLinker<'a> {
} }
}; };
if let Err(error) = res { if let Err(error) = res {
self.sess.emit_fatal(errors::LibDefWriteFailure { error }); self.sess.dcx().emit_fatal(errors::LibDefWriteFailure { error });
} }
} else { } else {
// Write an LD version script // Write an LD version script
@ -725,7 +725,7 @@ impl<'a> Linker for GccLinker<'a> {
writeln!(f, "\n local:\n *;\n}};")?; writeln!(f, "\n local:\n *;\n}};")?;
}; };
if let Err(error) = res { if let Err(error) = res {
self.sess.emit_fatal(errors::VersionScriptWriteFailure { error }); self.sess.dcx().emit_fatal(errors::VersionScriptWriteFailure { error });
} }
} }
@ -950,7 +950,7 @@ impl<'a> Linker for MsvcLinker<'a> {
} }
} }
Err(error) => { Err(error) => {
self.sess.emit_warning(errors::NoNatvisDirectory { error }); self.sess.dcx().emit_warning(errors::NoNatvisDirectory { error });
} }
} }
} }
@ -1005,7 +1005,7 @@ impl<'a> Linker for MsvcLinker<'a> {
} }
}; };
if let Err(error) = res { if let Err(error) = res {
self.sess.emit_fatal(errors::LibDefWriteFailure { error }); self.sess.dcx().emit_fatal(errors::LibDefWriteFailure { error });
} }
let mut arg = OsString::from("/DEF:"); let mut arg = OsString::from("/DEF:");
arg.push(path); arg.push(path);
@ -1501,7 +1501,7 @@ impl<'a> Linker for L4Bender<'a> {
fn export_symbols(&mut self, _: &Path, _: CrateType, _: &[String]) { fn export_symbols(&mut self, _: &Path, _: CrateType, _: &[String]) {
// ToDo, not implemented, copy from GCC // ToDo, not implemented, copy from GCC
self.sess.emit_warning(errors::L4BenderExportingSymbolsUnimplemented); self.sess.dcx().emit_warning(errors::L4BenderExportingSymbolsUnimplemented);
return; return;
} }
@ -1688,7 +1688,7 @@ impl<'a> Linker for AixLinker<'a> {
} }
}; };
if let Err(e) = res { if let Err(e) = res {
self.sess.fatal(format!("failed to write export file: {e}")); self.sess.dcx().fatal(format!("failed to write export file: {e}"));
} }
self.cmd.arg(format!("-bE:{}", path.to_str().unwrap())); self.cmd.arg(format!("-bE:{}", path.to_str().unwrap()));
} }
@ -1995,7 +1995,7 @@ impl<'a> Linker for BpfLinker<'a> {
} }
}; };
if let Err(error) = res { if let Err(error) = res {
self.sess.emit_fatal(errors::SymbolFileWriteFailure { error }); self.sess.dcx().emit_fatal(errors::SymbolFileWriteFailure { error });
} else { } else {
self.cmd.arg("--export-symbols").arg(&path); self.cmd.arg("--export-symbols").arg(&path);
} }

View file

@ -534,12 +534,12 @@ fn produce_final_output_artifacts(
let copy_gracefully = |from: &Path, to: &OutFileName| match to { let copy_gracefully = |from: &Path, to: &OutFileName| match to {
OutFileName::Stdout => { OutFileName::Stdout => {
if let Err(e) = copy_to_stdout(from) { if let Err(e) = copy_to_stdout(from) {
sess.emit_err(errors::CopyPath::new(from, to.as_path(), e)); sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
} }
} }
OutFileName::Real(path) => { OutFileName::Real(path) => {
if let Err(e) = fs::copy(from, path) { if let Err(e) = fs::copy(from, path) {
sess.emit_err(errors::CopyPath::new(from, path, e)); sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
} }
} }
}; };
@ -552,7 +552,8 @@ fn produce_final_output_artifacts(
let path = crate_output.temp_path(output_type, module_name); let path = crate_output.temp_path(output_type, module_name);
let output = crate_output.path(output_type); let output = crate_output.path(output_type);
if !output_type.is_text_output() && output.is_tty() { if !output_type.is_text_output() && output.is_tty() {
sess.emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() }); sess.dcx()
.emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
} else { } else {
copy_gracefully(&path, &output); copy_gracefully(&path, &output);
} }
@ -572,11 +573,11 @@ fn produce_final_output_artifacts(
if crate_output.outputs.contains_key(&output_type) { if crate_output.outputs.contains_key(&output_type) {
// 2) Multiple codegen units, with `--emit foo=some_name`. We have // 2) Multiple codegen units, with `--emit foo=some_name`. We have
// no good solution for this case, so warn the user. // no good solution for this case, so warn the user.
sess.emit_warning(errors::IgnoringEmitPath { extension }); sess.dcx().emit_warning(errors::IgnoringEmitPath { extension });
} else if crate_output.single_output_file.is_some() { } else if crate_output.single_output_file.is_some() {
// 3) Multiple codegen units, with `-o some_name`. We have // 3) Multiple codegen units, with `-o some_name`. We have
// no good solution for this case, so warn the user. // no good solution for this case, so warn the user.
sess.emit_warning(errors::IgnoringOutput { extension }); sess.dcx().emit_warning(errors::IgnoringOutput { extension });
} else { } else {
// 4) Multiple codegen units, but no explicit name. We // 4) Multiple codegen units, but no explicit name. We
// just leave the `foo.0.x` files in place. // just leave the `foo.0.x` files in place.
@ -1079,7 +1080,7 @@ fn start_executing_work<B: ExtraBackendMethods>(
let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize()); let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
match result { match result {
Ok(dir) => Some(dir), Ok(dir) => Some(dir),
Err(error) => sess.emit_fatal(ErrorCreatingRemarkDir { error }), Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
} }
} else { } else {
None None
@ -1882,10 +1883,10 @@ impl SharedEmitterMain {
err.emit(); err.emit();
} }
Ok(SharedEmitterMessage::AbortIfErrors) => { Ok(SharedEmitterMessage::AbortIfErrors) => {
sess.abort_if_errors(); sess.dcx().abort_if_errors();
} }
Ok(SharedEmitterMessage::Fatal(msg)) => { Ok(SharedEmitterMessage::Fatal(msg)) => {
sess.fatal(msg); sess.dcx().fatal(msg);
} }
Err(_) => { Err(_) => {
break; break;
@ -1938,7 +1939,7 @@ impl<B: ExtraBackendMethods> OngoingCodegen<B> {
let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() { let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
Ok(Ok(compiled_modules)) => compiled_modules, Ok(Ok(compiled_modules)) => compiled_modules,
Ok(Err(())) => { Ok(Err(())) => {
sess.abort_if_errors(); sess.dcx().abort_if_errors();
panic!("expected abort due to worker thread errors") panic!("expected abort due to worker thread errors")
} }
Err(_) => { Err(_) => {
@ -1946,7 +1947,7 @@ impl<B: ExtraBackendMethods> OngoingCodegen<B> {
} }
}); });
sess.abort_if_errors(); sess.dcx().abort_if_errors();
let work_products = let work_products =
copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules); copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);

View file

@ -448,8 +448,9 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
let Some(llfn) = cx.declare_c_main(llfty) else { let Some(llfn) = cx.declare_c_main(llfty) else {
// FIXME: We should be smart and show a better diagnostic here. // FIXME: We should be smart and show a better diagnostic here.
let span = cx.tcx().def_span(rust_main_def_id); let span = cx.tcx().def_span(rust_main_def_id);
cx.sess().emit_err(errors::MultipleMainFunctions { span }); let dcx = cx.tcx().dcx();
cx.sess().abort_if_errors(); dcx.emit_err(errors::MultipleMainFunctions { span });
dcx.abort_if_errors();
bug!(); bug!();
}; };
@ -620,7 +621,7 @@ pub fn codegen_crate<B: ExtraBackendMethods>(
&exported_symbols::metadata_symbol_name(tcx), &exported_symbols::metadata_symbol_name(tcx),
); );
if let Err(error) = std::fs::write(&file_name, data) { if let Err(error) = std::fs::write(&file_name, data) {
tcx.sess.emit_fatal(errors::MetadataObjectFileWrite { error }); tcx.dcx().emit_fatal(errors::MetadataObjectFileWrite { error });
} }
CompiledModule { CompiledModule {
name: metadata_cgu_name, name: metadata_cgu_name,
@ -752,7 +753,7 @@ pub fn codegen_crate<B: ExtraBackendMethods>(
// This will unwind if there are errors, which triggers our `AbortCodegenOnDrop` // This will unwind if there are errors, which triggers our `AbortCodegenOnDrop`
// guard. Unfortunately, just skipping the `submit_codegened_module_to_llvm` makes // guard. Unfortunately, just skipping the `submit_codegened_module_to_llvm` makes
// compilation hang on post-monomorphization errors. // compilation hang on post-monomorphization errors.
tcx.sess.abort_if_errors(); tcx.dcx().abort_if_errors();
submit_codegened_module_to_llvm( submit_codegened_module_to_llvm(
&backend, &backend,
@ -819,7 +820,7 @@ impl CrateInfo {
let subsystem = attr::first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem); let subsystem = attr::first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
let windows_subsystem = subsystem.map(|subsystem| { let windows_subsystem = subsystem.map(|subsystem| {
if subsystem != sym::windows && subsystem != sym::console { if subsystem != sym::windows && subsystem != sym::console {
tcx.sess.emit_fatal(errors::InvalidWindowsSubsystem { subsystem }); tcx.dcx().emit_fatal(errors::InvalidWindowsSubsystem { subsystem });
} }
subsystem.to_string() subsystem.to_string()
}); });

View file

@ -44,7 +44,7 @@ fn linkage_by_name(tcx: TyCtxt<'_>, def_id: LocalDefId, name: &str) -> Linkage {
"private" => Private, "private" => Private,
"weak" => WeakAny, "weak" => WeakAny,
"weak_odr" => WeakODR, "weak_odr" => WeakODR,
_ => tcx.sess.span_fatal(tcx.def_span(def_id), "invalid linkage specified"), _ => tcx.dcx().span_fatal(tcx.def_span(def_id), "invalid linkage specified"),
} }
} }
@ -90,7 +90,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
if let Fn | AssocFn | Variant | Ctor(..) = def_kind { if let Fn | AssocFn | Variant | Ctor(..) = def_kind {
Some(tcx.fn_sig(did)) Some(tcx.fn_sig(did))
} else { } else {
tcx.sess tcx.dcx()
.span_delayed_bug(attr.span, "this attribute can only be applied to functions"); .span_delayed_bug(attr.span, "this attribute can only be applied to functions");
None None
} }
@ -119,7 +119,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
if tcx.opt_item_name(did.to_def_id()).is_some() { if tcx.opt_item_name(did.to_def_id()).is_some() {
codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE
} else { } else {
tcx.sess tcx.dcx()
.struct_span_err( .struct_span_err(
attr.span, attr.span,
format!( format!(
@ -142,7 +142,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
// coverage on a smaller scope within an excluded larger scope. // coverage on a smaller scope within an excluded larger scope.
} }
Some(_) | None => { Some(_) | None => {
tcx.sess.emit_err(ExpectedCoverageSymbol { span: attr.span }); tcx.dcx().emit_err(ExpectedCoverageSymbol { span: attr.span });
} }
} }
} }
@ -177,7 +177,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED; codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED;
} }
Some(_) => { Some(_) => {
tcx.sess.emit_err(ExpectedUsedSymbol { span: attr.span }); tcx.dcx().emit_err(ExpectedUsedSymbol { span: attr.span });
} }
None => { None => {
// Unfortunately, unconditionally using `llvm.used` causes // Unfortunately, unconditionally using `llvm.used` causes
@ -217,7 +217,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
&& !matches!(fn_sig.skip_binder().abi(), abi::Abi::C { .. }) && !matches!(fn_sig.skip_binder().abi(), abi::Abi::C { .. })
{ {
struct_span_err!( struct_span_err!(
tcx.sess, tcx.dcx(),
attr.span, attr.span,
E0776, E0776,
"`#[cmse_nonsecure_entry]` requires C ABI" "`#[cmse_nonsecure_entry]` requires C ABI"
@ -225,7 +225,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
.emit(); .emit();
} }
if !tcx.sess.target.llvm_target.contains("thumbv8m") { if !tcx.sess.target.llvm_target.contains("thumbv8m") {
struct_span_err!(tcx.sess, attr.span, E0775, "`#[cmse_nonsecure_entry]` is only valid for targets with the TrustZone-M extension") struct_span_err!(tcx.dcx(), attr.span, E0775, "`#[cmse_nonsecure_entry]` is only valid for targets with the TrustZone-M extension")
.emit(); .emit();
} }
codegen_fn_attrs.flags |= CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY codegen_fn_attrs.flags |= CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY
@ -239,7 +239,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
&& fn_sig.skip_binder().abi() != abi::Abi::Rust && fn_sig.skip_binder().abi() != abi::Abi::Rust
{ {
struct_span_err!( struct_span_err!(
tcx.sess, tcx.dcx(),
attr.span, attr.span,
E0737, E0737,
"`#[track_caller]` requires Rust ABI" "`#[track_caller]` requires Rust ABI"
@ -266,7 +266,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
// `#[export_name = ...]` will be converted to a null-terminated string, // `#[export_name = ...]` will be converted to a null-terminated string,
// so it may not contain any null characters. // so it may not contain any null characters.
struct_span_err!( struct_span_err!(
tcx.sess, tcx.dcx(),
attr.span, attr.span,
E0648, E0648,
"`export_name` may not contain null characters" "`export_name` may not contain null characters"
@ -336,7 +336,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
if let Some(val) = attr.value_str() { if let Some(val) = attr.value_str() {
if val.as_str().bytes().any(|b| b == 0) { if val.as_str().bytes().any(|b| b == 0) {
let msg = format!("illegal null byte in link_section value: `{}`", &val); let msg = format!("illegal null byte in link_section value: `{}`", &val);
tcx.sess.span_err(attr.span, msg); tcx.dcx().span_err(attr.span, msg);
} else { } else {
codegen_fn_attrs.link_section = Some(val); codegen_fn_attrs.link_section = Some(val);
} }
@ -370,7 +370,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
codegen_fn_attrs.no_sanitize |= SanitizerSet::HWADDRESS codegen_fn_attrs.no_sanitize |= SanitizerSet::HWADDRESS
} }
_ => { _ => {
tcx.sess.emit_err(errors::InvalidNoSanitize { span: item.span() }); tcx.dcx().emit_err(errors::InvalidNoSanitize { span: item.span() });
} }
} }
} }
@ -386,7 +386,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
[sym::arm, sym::a32] | [sym::arm, sym::t32] => { [sym::arm, sym::a32] | [sym::arm, sym::t32] => {
if !tcx.sess.target.has_thumb_interworking { if !tcx.sess.target.has_thumb_interworking {
struct_span_err!( struct_span_err!(
tcx.sess.dcx(), tcx.dcx(),
attr.span, attr.span,
E0779, E0779,
"target does not support `#[instruction_set]`" "target does not support `#[instruction_set]`"
@ -403,7 +403,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
} }
_ => { _ => {
struct_span_err!( struct_span_err!(
tcx.sess.dcx(), tcx.dcx(),
attr.span, attr.span,
E0779, E0779,
"invalid instruction set specified", "invalid instruction set specified",
@ -415,7 +415,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
} }
[] => { [] => {
struct_span_err!( struct_span_err!(
tcx.sess.dcx(), tcx.dcx(),
attr.span, attr.span,
E0778, E0778,
"`#[instruction_set]` requires an argument" "`#[instruction_set]` requires an argument"
@ -425,7 +425,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
} }
_ => { _ => {
struct_span_err!( struct_span_err!(
tcx.sess.dcx(), tcx.dcx(),
attr.span, attr.span,
E0779, E0779,
"cannot specify more than one instruction set" "cannot specify more than one instruction set"
@ -443,7 +443,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
rustc_attr::parse_alignment(&literal.kind) rustc_attr::parse_alignment(&literal.kind)
.map_err(|msg| { .map_err(|msg| {
struct_span_err!( struct_span_err!(
tcx.sess.dcx(), tcx.dcx(),
attr.span, attr.span,
E0589, E0589,
"invalid `repr(align)` attribute: {}", "invalid `repr(align)` attribute: {}",
@ -469,15 +469,14 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
Some(MetaItemKind::List(ref items)) => { Some(MetaItemKind::List(ref items)) => {
inline_span = Some(attr.span); inline_span = Some(attr.span);
if items.len() != 1 { if items.len() != 1 {
struct_span_err!(tcx.sess.dcx(), attr.span, E0534, "expected one argument") struct_span_err!(tcx.dcx(), attr.span, E0534, "expected one argument").emit();
.emit();
InlineAttr::None InlineAttr::None
} else if list_contains_name(items, sym::always) { } else if list_contains_name(items, sym::always) {
InlineAttr::Always InlineAttr::Always
} else if list_contains_name(items, sym::never) { } else if list_contains_name(items, sym::never) {
InlineAttr::Never InlineAttr::Never
} else { } else {
struct_span_err!(tcx.sess.dcx(), items[0].span(), E0535, "invalid argument") struct_span_err!(tcx.dcx(), items[0].span(), E0535, "invalid argument")
.help("valid inline arguments are `always` and `never`") .help("valid inline arguments are `always` and `never`")
.emit(); .emit();
@ -493,7 +492,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
if !attr.has_name(sym::optimize) { if !attr.has_name(sym::optimize) {
return ia; return ia;
} }
let err = |sp, s| struct_span_err!(tcx.sess.dcx(), sp, E0722, "{}", s).emit(); let err = |sp, s| struct_span_err!(tcx.dcx(), sp, E0722, "{}", s).emit();
match attr.meta_kind() { match attr.meta_kind() {
Some(MetaItemKind::Word) => { Some(MetaItemKind::Word) => {
err(attr.span, "expected one argument"); err(attr.span, "expected one argument");
@ -550,7 +549,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
if !codegen_fn_attrs.target_features.is_empty() { if !codegen_fn_attrs.target_features.is_empty() {
if codegen_fn_attrs.inline == InlineAttr::Always { if codegen_fn_attrs.inline == InlineAttr::Always {
if let Some(span) = inline_span { if let Some(span) = inline_span {
tcx.sess.span_err( tcx.dcx().span_err(
span, span,
"cannot use `#[inline(always)]` with \ "cannot use `#[inline(always)]` with \
`#[target_feature]`", `#[target_feature]`",
@ -637,7 +636,7 @@ fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<u16> {
let sole_meta_list = match meta_item_list { let sole_meta_list = match meta_item_list {
Some([item]) => item.lit(), Some([item]) => item.lit(),
Some(_) => { Some(_) => {
tcx.sess.emit_err(errors::InvalidLinkOrdinalNargs { span: attr.span }); tcx.dcx().emit_err(errors::InvalidLinkOrdinalNargs { span: attr.span });
return None; return None;
} }
_ => None, _ => None,
@ -661,14 +660,14 @@ fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<u16> {
Some(*ordinal as u16) Some(*ordinal as u16)
} else { } else {
let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal); let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
tcx.sess tcx.dcx()
.struct_span_err(attr.span, msg) .struct_span_err(attr.span, msg)
.note("the value may not exceed `u16::MAX`") .note("the value may not exceed `u16::MAX`")
.emit(); .emit();
None None
} }
} else { } else {
tcx.sess.emit_err(errors::InvalidLinkOrdinalFormat { span: attr.span }); tcx.dcx().emit_err(errors::InvalidLinkOrdinalFormat { span: attr.span });
None None
} }
} }
@ -683,9 +682,9 @@ fn check_link_name_xor_ordinal(
} }
let msg = "cannot use `#[link_name]` with `#[link_ordinal]`"; let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
if let Some(span) = inline_span { if let Some(span) = inline_span {
tcx.sess.span_err(span, msg); tcx.dcx().span_err(span, msg);
} else { } else {
tcx.sess.err(msg); tcx.dcx().err(msg);
} }
} }

View file

@ -93,7 +93,7 @@ fn push_debuginfo_type_name<'tcx>(
Err(e) => { Err(e) => {
// Computing the layout can still fail here, e.g. if the target architecture // Computing the layout can still fail here, e.g. if the target architecture
// cannot represent the type. See https://github.com/rust-lang/rust/issues/94961. // cannot represent the type. See https://github.com/rust-lang/rust/issues/94961.
tcx.sess.emit_fatal(e.into_diagnostic()); tcx.dcx().emit_fatal(e.into_diagnostic());
} }
} }
} else { } else {

View file

@ -94,7 +94,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
bx.const_struct(&values, false) bx.const_struct(&values, false)
}) })
.unwrap_or_else(|| { .unwrap_or_else(|| {
bx.tcx().sess.emit_err(errors::ShuffleIndicesEvaluation { span: constant.span }); bx.tcx().dcx().emit_err(errors::ShuffleIndicesEvaluation { span: constant.span });
// We've errored, so we don't have to produce working code. // We've errored, so we don't have to produce working code.
let llty = bx.backend_type(bx.layout_of(ty)); let llty = bx.backend_type(bx.layout_of(ty));
bx.const_undef(llty) bx.const_undef(llty)

View file

@ -220,7 +220,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
} }
} }
None => { None => {
bx.tcx().sess.emit_err(InvalidMonomorphization::BasicIntegerType { bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicIntegerType {
span, span,
name, name,
ty, ty,
@ -240,7 +240,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
_ => bug!(), _ => bug!(),
}, },
None => { None => {
bx.tcx().sess.emit_err(InvalidMonomorphization::BasicFloatType { bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicFloatType {
span, span,
name, name,
ty: arg_tys[0], ty: arg_tys[0],
@ -252,14 +252,14 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
sym::float_to_int_unchecked => { sym::float_to_int_unchecked => {
if float_type_width(arg_tys[0]).is_none() { if float_type_width(arg_tys[0]).is_none() {
bx.tcx().sess.emit_err(InvalidMonomorphization::FloatToIntUnchecked { bx.tcx().dcx().emit_err(InvalidMonomorphization::FloatToIntUnchecked {
span, span,
ty: arg_tys[0], ty: arg_tys[0],
}); });
return; return;
} }
let Some((_width, signed)) = int_type_width_signed(ret_ty, bx.tcx()) else { let Some((_width, signed)) = int_type_width_signed(ret_ty, bx.tcx()) else {
bx.tcx().sess.emit_err(InvalidMonomorphization::FloatToIntUnchecked { bx.tcx().dcx().emit_err(InvalidMonomorphization::FloatToIntUnchecked {
span, span,
ty: ret_ty, ty: ret_ty,
}); });
@ -297,7 +297,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
use crate::common::{AtomicRmwBinOp, SynchronizationScope}; use crate::common::{AtomicRmwBinOp, SynchronizationScope};
let Some((instruction, ordering)) = atomic.split_once('_') else { let Some((instruction, ordering)) = atomic.split_once('_') else {
bx.sess().emit_fatal(errors::MissingMemoryOrdering); bx.sess().dcx().emit_fatal(errors::MissingMemoryOrdering);
}; };
let parse_ordering = |bx: &Bx, s| match s { let parse_ordering = |bx: &Bx, s| match s {
@ -307,11 +307,11 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
"release" => Release, "release" => Release,
"acqrel" => AcquireRelease, "acqrel" => AcquireRelease,
"seqcst" => SequentiallyConsistent, "seqcst" => SequentiallyConsistent,
_ => bx.sess().emit_fatal(errors::UnknownAtomicOrdering), _ => bx.sess().dcx().emit_fatal(errors::UnknownAtomicOrdering),
}; };
let invalid_monomorphization = |ty| { let invalid_monomorphization = |ty| {
bx.tcx().sess.emit_err(InvalidMonomorphization::BasicIntegerType { bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicIntegerType {
span, span,
name, name,
ty, ty,
@ -321,7 +321,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
match instruction { match instruction {
"cxchg" | "cxchgweak" => { "cxchg" | "cxchgweak" => {
let Some((success, failure)) = ordering.split_once('_') else { let Some((success, failure)) = ordering.split_once('_') else {
bx.sess().emit_fatal(errors::AtomicCompareExchange); bx.sess().dcx().emit_fatal(errors::AtomicCompareExchange);
}; };
let ty = fn_args.type_at(0); let ty = fn_args.type_at(0);
if int_type_width_signed(ty, bx.tcx()).is_some() || ty.is_unsafe_ptr() { if int_type_width_signed(ty, bx.tcx()).is_some() || ty.is_unsafe_ptr() {
@ -437,7 +437,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
"min" => AtomicRmwBinOp::AtomicMin, "min" => AtomicRmwBinOp::AtomicMin,
"umax" => AtomicRmwBinOp::AtomicUMax, "umax" => AtomicRmwBinOp::AtomicUMax,
"umin" => AtomicRmwBinOp::AtomicUMin, "umin" => AtomicRmwBinOp::AtomicUMin,
_ => bx.sess().emit_fatal(errors::UnknownAtomicOperation), _ => bx.sess().dcx().emit_fatal(errors::UnknownAtomicOperation),
}; };
let ty = fn_args.type_at(0); let ty = fn_args.type_at(0);

View file

@ -25,7 +25,7 @@ pub fn from_target_feature(
let bad_item = |span| { let bad_item = |span| {
let msg = "malformed `target_feature` attribute input"; let msg = "malformed `target_feature` attribute input";
let code = "enable = \"..\""; let code = "enable = \"..\"";
tcx.sess tcx.dcx()
.struct_span_err(span, msg) .struct_span_err(span, msg)
.span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders) .span_suggestion(span, "must be of the form", code, Applicability::HasPlaceholders)
.emit(); .emit();
@ -48,7 +48,7 @@ pub fn from_target_feature(
target_features.extend(value.as_str().split(',').filter_map(|feature| { target_features.extend(value.as_str().split(',').filter_map(|feature| {
let Some(feature_gate) = supported_target_features.get(feature) else { let Some(feature_gate) = supported_target_features.get(feature) else {
let msg = format!("the feature named `{feature}` is not valid for this target"); let msg = format!("the feature named `{feature}` is not valid for this target");
let mut err = tcx.sess.struct_span_err(item.span(), msg); let mut err = tcx.dcx().struct_span_err(item.span(), msg);
err.span_label(item.span(), format!("`{feature}` is not valid for this target")); err.span_label(item.span(), format!("`{feature}` is not valid for this target"));
if let Some(stripped) = feature.strip_prefix('+') { if let Some(stripped) = feature.strip_prefix('+') {
let valid = supported_target_features.contains_key(stripped); let valid = supported_target_features.contains_key(stripped);
@ -121,7 +121,7 @@ pub fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_s
if let DefKind::AssocFn = tcx.def_kind(id) { if let DefKind::AssocFn = tcx.def_kind(id) {
let parent_id = tcx.local_parent(id); let parent_id = tcx.local_parent(id);
if let DefKind::Trait | DefKind::Impl { of_trait: true } = tcx.def_kind(parent_id) { if let DefKind::Trait | DefKind::Impl { of_trait: true } = tcx.def_kind(parent_id) {
tcx.sess.emit_err(errors::TargetFeatureSafeTrait { tcx.dcx().emit_err(errors::TargetFeatureSafeTrait {
span: attr_span, span: attr_span,
def: tcx.def_span(id), def: tcx.def_span(id),
}); });

View file

@ -151,10 +151,10 @@ where
let (our_span, frames) = get_span_and_frames(); let (our_span, frames) = get_span_and_frames();
let span = span.unwrap_or(our_span); let span = span.unwrap_or(our_span);
let err = mk(span, frames); let err = mk(span, frames);
let mut err = tcx.sess.create_err(err); let mut err = tcx.dcx().create_err(err);
let msg = error.diagnostic_message(); let msg = error.diagnostic_message();
error.add_args(tcx.sess.dcx(), &mut err); error.add_args(tcx.dcx(), &mut err);
// Use *our* span to label the interp error // Use *our* span to label the interp error
err.span_label(our_span, msg); err.span_label(our_span, msg);

View file

@ -391,7 +391,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir,
if ecx.tcx.is_ctfe_mir_available(def) { if ecx.tcx.is_ctfe_mir_available(def) {
Ok(ecx.tcx.mir_for_ctfe(def)) Ok(ecx.tcx.mir_for_ctfe(def))
} else if ecx.tcx.def_kind(def) == DefKind::AssocConst { } else if ecx.tcx.def_kind(def) == DefKind::AssocConst {
let guar = ecx.tcx.sess.span_delayed_bug( let guar = ecx.tcx.dcx().span_delayed_bug(
rustc_span::DUMMY_SP, rustc_span::DUMMY_SP,
"This is likely a const item that is missing from its impl", "This is likely a const item that is missing from its impl",
); );
@ -621,7 +621,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir,
if is_error { if is_error {
let guard = ecx let guard = ecx
.tcx .tcx
.sess .dcx()
.span_delayed_bug(span, "The deny lint should have already errored"); .span_delayed_bug(span, "The deny lint should have already errored");
throw_inval!(AlreadyReported(guard.into())); throw_inval!(AlreadyReported(guard.into()));
} }
@ -630,7 +630,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir,
// current number of evaluated terminators is a power of 2. The latter gives us a cheap // current number of evaluated terminators is a power of 2. The latter gives us a cheap
// way to implement exponential backoff. // way to implement exponential backoff.
let span = ecx.cur_span(); let span = ecx.cur_span();
ecx.tcx.sess.emit_warning(LongRunningWarn { span, item_span: ecx.tcx.span }); ecx.tcx.dcx().emit_warning(LongRunningWarn { span, item_span: ecx.tcx.span });
} }
} }

View file

@ -61,7 +61,7 @@ pub(crate) fn eval_to_valtree<'tcx>(
match err { match err {
ValTreeCreationError::NodesOverflow => { ValTreeCreationError::NodesOverflow => {
let span = tcx.hir().span_if_local(did); let span = tcx.hir().span_if_local(did);
tcx.sess.emit_err(MaxNumNodesInConstErr { span, global_const_id }); tcx.dcx().emit_err(MaxNumNodesInConstErr { span, global_const_id });
Ok(None) Ok(None)
} }

View file

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

View file

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

View file

@ -96,7 +96,7 @@ fn intern_shallow<'rt, 'mir, 'tcx, M: CompileTimeMachine<'mir, 'tcx, const_eval:
// in the value the dangling reference lies. // in the value the dangling reference lies.
// The `span_delayed_bug` ensures that we don't forget such a check in validation. // The `span_delayed_bug` ensures that we don't forget such a check in validation.
if tcx.try_get_global_alloc(alloc_id).is_none() { if tcx.try_get_global_alloc(alloc_id).is_none() {
tcx.sess.span_delayed_bug(ecx.tcx.span, "tried to intern dangling pointer"); tcx.dcx().span_delayed_bug(ecx.tcx.span, "tried to intern dangling pointer");
} }
// treat dangling pointers like other statics // treat dangling pointers like other statics
// just to stop trying to recurse into them // just to stop trying to recurse into them
@ -185,7 +185,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx, const_eval::Memory
} else { } else {
// Validation will error (with a better message) on an invalid vtable pointer. // Validation will error (with a better message) on an invalid vtable pointer.
// Let validation show the error message, but make sure it *does* error. // Let validation show the error message, but make sure it *does* error.
tcx.sess tcx.dcx()
.span_delayed_bug(tcx.span, "vtables pointers cannot be integer pointers"); .span_delayed_bug(tcx.span, "vtables pointers cannot be integer pointers");
} }
} }
@ -375,7 +375,7 @@ pub fn intern_const_alloc_recursive<
match res { match res {
Ok(()) => {} Ok(()) => {}
Err(error) => { Err(error) => {
ecx.tcx.sess.span_delayed_bug( ecx.tcx.dcx().span_delayed_bug(
ecx.tcx.span, ecx.tcx.span,
format!( format!(
"error during interning should later cause validation failure: {}", "error during interning should later cause validation failure: {}",
@ -424,7 +424,7 @@ pub fn intern_const_alloc_recursive<
// something that cannot be promoted, which in constants means values that have // something that cannot be promoted, which in constants means values that have
// drop glue, such as the example above. // drop glue, such as the example above.
InternKind::Constant => { InternKind::Constant => {
ecx.tcx.sess.emit_err(UnsupportedUntypedPointer { span: ecx.tcx.span }); ecx.tcx.dcx().emit_err(UnsupportedUntypedPointer { span: ecx.tcx.span });
// For better errors later, mark the allocation as immutable. // For better errors later, mark the allocation as immutable.
alloc.mutability = Mutability::Not; alloc.mutability = Mutability::Not;
} }
@ -440,7 +440,7 @@ pub fn intern_const_alloc_recursive<
} else if ecx.memory.dead_alloc_map.contains_key(&alloc_id) { } else if ecx.memory.dead_alloc_map.contains_key(&alloc_id) {
// Codegen does not like dangling pointers, and generally `tcx` assumes that // Codegen does not like dangling pointers, and generally `tcx` assumes that
// all allocations referenced anywhere actually exist. So, make sure we error here. // all allocations referenced anywhere actually exist. So, make sure we error here.
let reported = ecx.tcx.sess.emit_err(DanglingPtrInFinal { span: ecx.tcx.span }); let reported = ecx.tcx.dcx().emit_err(DanglingPtrInFinal { span: ecx.tcx.span });
return Err(reported); return Err(reported);
} else if ecx.tcx.try_get_global_alloc(alloc_id).is_none() { } else if ecx.tcx.try_get_global_alloc(alloc_id).is_none() {
// We have hit an `AllocId` that is neither in local or global memory and isn't // We have hit an `AllocId` that is neither in local or global memory and isn't

View file

@ -244,7 +244,7 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> {
// `async` functions cannot be `const fn`. This is checked during AST lowering, so there's // `async` functions cannot be `const fn`. This is checked during AST lowering, so there's
// no need to emit duplicate errors here. // no need to emit duplicate errors here.
if self.ccx.is_async() || body.coroutine.is_some() { if self.ccx.is_async() || body.coroutine.is_some() {
tcx.sess.span_delayed_bug(body.span, "`async` functions cannot be `const fn`"); tcx.dcx().span_delayed_bug(body.span, "`async` functions cannot be `const fn`");
return; return;
} }
@ -276,10 +276,10 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> {
let secondary_errors = mem::take(&mut self.secondary_errors); let secondary_errors = mem::take(&mut self.secondary_errors);
if self.error_emitted.is_none() { if self.error_emitted.is_none() {
for error in secondary_errors { for error in secondary_errors {
self.tcx.sess.dcx().emit_diagnostic(error); self.tcx.dcx().emit_diagnostic(error);
} }
} else { } else {
assert!(self.tcx.sess.has_errors().is_some()); assert!(self.tcx.dcx().has_errors().is_some());
} }
} }
@ -354,7 +354,7 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> {
fn check_static(&mut self, def_id: DefId, span: Span) { fn check_static(&mut self, def_id: DefId, span: Span) {
if self.tcx.is_thread_local_static(def_id) { if self.tcx.is_thread_local_static(def_id) {
self.tcx self.tcx
.sess .dcx()
.span_delayed_bug(span, "tls access is checked in `Rvalue::ThreadLocalRef`"); .span_delayed_bug(span, "tls access is checked in `Rvalue::ThreadLocalRef`");
} }
self.check_op_spanned(ops::StaticAccess, span) self.check_op_spanned(ops::StaticAccess, span)
@ -994,5 +994,5 @@ fn is_int_bool_or_char(ty: Ty<'_>) -> bool {
fn emit_unstable_in_stable_error(ccx: &ConstCx<'_, '_>, span: Span, gate: Symbol) { fn emit_unstable_in_stable_error(ccx: &ConstCx<'_, '_>, span: Span, gate: Symbol) {
let attr_span = ccx.tcx.def_span(ccx.def_id()).shrink_to_lo(); let attr_span = ccx.tcx.def_span(ccx.def_id()).shrink_to_lo();
ccx.tcx.sess.emit_err(UnstableInStable { gate: gate.to_string(), span, attr_span }); ccx.dcx().emit_err(UnstableInStable { gate: gate.to_string(), span, attr_span });
} }

Some files were not shown because too many files have changed in this diff Show more