Skip to content

Commit

Permalink
Auto merge of #119146 - nnethercote:rm-DiagCtxt-api-duplication, r=co…
Browse files Browse the repository at this point in the history
…mpiler-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`
  • Loading branch information
bors committed Dec 26, 2023
2 parents e4c626d + 8a9db25 commit 2271c26
Show file tree
Hide file tree
Showing 347 changed files with 2,334 additions and 2,696 deletions.
28 changes: 16 additions & 12 deletions compiler/rustc_ast_lowering/src/asm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
let 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 {
self.tcx.sess.emit_err(InlineAsmUnsupportedTarget { span: sp });
self.dcx().emit_err(InlineAsmUnsupportedTarget { span: sp });
}
if let Some(asm_arch) = asm_arch {
// Inline assembly is currently only stable for these architectures.
Expand Down Expand Up @@ -60,7 +60,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
&& !matches!(asm_arch, Some(asm::InlineAsmArch::X86 | asm::InlineAsmArch::X86_64))
&& !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 {
feature_err(
Expand All @@ -87,7 +87,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
!= source_map.span_to_snippet(*abi_span))
.then_some(());

self.tcx.sess.emit_err(AbiSpecifiedMultipleTimes {
self.dcx().emit_err(AbiSpecifiedMultipleTimes {
abi_span: *abi_span,
prev_name: *prev_name,
prev_span: *prev_sp,
Expand All @@ -100,14 +100,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
}
}
Err(&[]) => {
self.tcx.sess.emit_err(ClobberAbiNotSupported { abi_span: *abi_span });
self.dcx().emit_err(ClobberAbiNotSupported { abi_span: *abi_span });
}
Err(supported_abis) => {
let mut abis = format!("`{}`", supported_abis[0]);
for m in &supported_abis[1..] {
let _ = write!(abis, ", `{m}`");
}
self.tcx.sess.emit_err(InvalidAbiClobberAbi {
self.dcx().emit_err(InvalidAbiClobberAbi {
abi_span: *abi_span,
supported_abis: abis,
});
Expand All @@ -128,7 +128,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
InlineAsmRegOrRegClass::Reg(reg) => {
asm::InlineAsmRegOrRegClass::Reg(if let Some(asm_arch) = asm_arch {
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
})
} else {
Expand All @@ -139,7 +143,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
asm::InlineAsmRegOrRegClass::RegClass(if let Some(asm_arch) = asm_arch {
asm::InlineAsmRegClass::parse(asm_arch, reg_class).unwrap_or_else(
|error| {
sess.emit_err(InvalidRegisterClass {
self.dcx().emit_err(InvalidRegisterClass {
op_span: *op_sp,
reg_class,
error,
Expand Down Expand Up @@ -276,22 +280,22 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
class_name: class.name(),
}
};
sess.emit_err(InvalidAsmTemplateModifierRegClass {
self.dcx().emit_err(InvalidAsmTemplateModifierRegClass {
placeholder_span,
op_span: op_sp,
sub,
});
}
}
hir::InlineAsmOperand::Const { .. } => {
sess.emit_err(InvalidAsmTemplateModifierConst {
self.dcx().emit_err(InvalidAsmTemplateModifierConst {
placeholder_span,
op_span: op_sp,
});
}
hir::InlineAsmOperand::SymFn { .. }
| hir::InlineAsmOperand::SymStatic { .. } => {
sess.emit_err(InvalidAsmTemplateModifierSym {
self.dcx().emit_err(InvalidAsmTemplateModifierSym {
placeholder_span,
op_span: op_sp,
});
Expand All @@ -315,7 +319,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
// require that the operand name an explicit register, not a
// register class.
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,
reg_class_name: reg_class.name(),
});
Expand Down Expand Up @@ -384,7 +388,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
}
};

sess.emit_err(RegisterConflict {
self.dcx().emit_err(RegisterConflict {
op_span1: op_sp,
op_span2: op_sp2,
reg1_name: reg_str(idx),
Expand Down
33 changes: 16 additions & 17 deletions compiler/rustc_ast_lowering/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), *lims)
}
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)
}
ExprKind::Path(qself, path) => {
Expand Down Expand Up @@ -294,8 +294,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let rest = match &se.rest {
StructRest::Base(e) => Some(self.lower_expr(e)),
StructRest::Rest(sp) => {
let guar =
self.tcx.sess.emit_err(BaseExpressionDoubleDot { span: *sp });
let guar = self.dcx().emit_err(BaseExpressionDoubleDot { span: *sp });
Some(&*self.arena.alloc(self.expr_err(*sp, guar)))
}
StructRest::None => None,
Expand Down Expand Up @@ -332,9 +331,9 @@ impl<'hir> LoweringContext<'_, 'hir> {
|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::Err => hir::ExprKind::Err(
self.tcx.sess.span_delayed_bug(e.span, "lowered ExprKind::Err"),
),
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::Paren(_) | ExprKind::ForLoop { .. } => {
Expand Down Expand Up @@ -584,13 +583,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
if self.tcx.features().never_patterns {
// If the feature is off we already emitted the error after parsing.
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 {
self.tcx.sess.emit_err(NeverPatternWithBody { span: body.span });
self.dcx().emit_err(NeverPatternWithBody { span: body.span });
guard = None;
} 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;
}

Expand Down Expand Up @@ -902,7 +901,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
Some(hir::CoroutineKind::Coroutine)
| Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _))
| None => {
return hir::ExprKind::Err(self.tcx.sess.emit_err(AwaitOnlyInAsyncFnAndBlocks {
return hir::ExprKind::Err(self.dcx().emit_err(AwaitOnlyInAsyncFnAndBlocks {
await_kw_span,
item_span: self.current_item,
}));
Expand Down Expand Up @@ -1129,7 +1128,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
match coroutine_kind {
Some(hir::CoroutineKind::Coroutine) => {
if decl.inputs.len() > 1 {
self.tcx.sess.emit_err(CoroutineTooManyParameters { fn_decl_span });
self.dcx().emit_err(CoroutineTooManyParameters { fn_decl_span });
}
Some(movability)
}
Expand All @@ -1142,7 +1141,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
}
None => {
if movability == Movability::Static {
self.tcx.sess.emit_err(ClosureCannotBeStatic { fn_decl_span });
self.dcx().emit_err(ClosureCannotBeStatic { fn_decl_span });
}
None
}
Expand Down Expand Up @@ -1181,7 +1180,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
};

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);
Expand All @@ -1192,7 +1191,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let body = self.with_new_scopes(fn_decl_span, |this| {
// FIXME(cramertj): allow `async` non-`move` closures with arguments.
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
Expand Down Expand Up @@ -1448,7 +1447,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
);
let fields_omitted = match &se.rest {
StructRest::Base(e) => {
self.tcx.sess.emit_err(FunctionalRecordUpdateDestructuringAssignment {
self.dcx().emit_err(FunctionalRecordUpdateDestructuringAssignment {
span: e.span,
});
true
Expand Down Expand Up @@ -1544,7 +1543,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
(None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
(Some(..), Some(..), Closed) => unreachable!(),
(start, None, Closed) => {
self.tcx.sess.emit_err(InclusiveRangeWithNoEnd { span });
self.dcx().emit_err(InclusiveRangeWithNoEnd { span });
match start {
Some(..) => hir::LangItem::RangeFrom,
None => hir::LangItem::RangeFull,
Expand Down Expand Up @@ -1653,7 +1652,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => true,
Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
return hir::ExprKind::Err(
self.tcx.sess.emit_err(AsyncCoroutinesNotSupported { span }),
self.dcx().emit_err(AsyncCoroutinesNotSupported { span }),
);
}
Some(hir::CoroutineKind::Coroutine) | None => {
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_ast_lowering/src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ fn make_count<'hir>(
ctx.expr(
sp,
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"),
),
)
}
Expand Down Expand Up @@ -306,7 +306,7 @@ fn make_format_spec<'hir>(
}
Err(_) => ctx.expr(
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 {
Expand Down
12 changes: 6 additions & 6 deletions compiler/rustc_ast_lowering/src/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
&ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
|this| match ty {
None => {
let guar = this.tcx.sess.span_delayed_bug(
let guar = this.dcx().span_delayed_bug(
span,
"expected to lower type alias type, but it was missing",
);
Expand Down Expand Up @@ -879,7 +879,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
&ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
|this| match ty {
None => {
let guar = this.tcx.sess.span_delayed_bug(
let guar = this.dcx().span_delayed_bug(
i.span,
"expected to lower associated type, but it was missing",
);
Expand Down Expand Up @@ -1012,7 +1012,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
match 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")),
}
}

Expand All @@ -1022,7 +1022,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
&[],
match 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")),
},
)
})
Expand Down Expand Up @@ -1296,7 +1296,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
.map(|s| Symbol::intern(s))
.collect::<Vec<_>>();
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,
span: abi.span,
explain: match err {
Expand Down Expand Up @@ -1383,7 +1383,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
}
let is_param = *is_param.get_or_insert_with(compute_is_param);
if !is_param {
self.tcx.sess.emit_err(MisplacedRelaxTraitBound { span: bound.span() });
self.dcx().emit_err(MisplacedRelaxTraitBound { span: bound.span() });
}
}
}
Expand Down
Loading

0 comments on commit 2271c26

Please sign in to comment.