Auto merge of #3310 - rust-lang:rustup-2024-02-22, r=oli-obk

Automatic Rustup
This commit is contained in:
bors 2024-02-22 05:06:27 +00:00
commit 3815fc0625
628 changed files with 12915 additions and 8290 deletions

View file

@ -52,7 +52,7 @@ Copyright: 2019 The Crossbeam Project Developers
The Rust Project Developers (see https://thanks.rust-lang.org)
License: MIT OR Apache-2.0
Files: library/std/src/sys/pal/unix/locks/fuchsia_mutex.rs
Files: library/std/src/sys/locks/mutex/fuchsia.rs
Copyright: 2016 The Fuchsia Authors
The Rust Project Developers (see https://thanks.rust-lang.org)
License: BSD-2-Clause AND (MIT OR Apache-2.0)

View file

@ -2627,6 +2627,7 @@ dependencies = [
"rustc-std-workspace-alloc",
"rustc-std-workspace-core",
"ruzstd",
"wasmparser",
]
[[package]]
@ -4047,7 +4048,6 @@ dependencies = [
name = "rustc_interface"
version = "0.0.0"
dependencies = [
"libloading",
"rustc-rayon",
"rustc-rayon-core",
"rustc_ast",
@ -6128,6 +6128,16 @@ version = "0.2.91"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f186bd2dcf04330886ce82d6f33dd75a7bfcf69ecf5763b89fcde53b6ac9838"
[[package]]
name = "wasmparser"
version = "0.118.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77f1154f1ab868e2a01d9834a805faca7bf8b50d041b4ca714d005d0dab1c50c"
dependencies = [
"indexmap",
"semver",
]
[[package]]
name = "web-sys"
version = "0.3.68"

View file

@ -95,7 +95,7 @@ impl<T> ArenaChunk<T> {
unsafe {
if mem::size_of::<T>() == 0 {
// A pointer as large as possible for zero-sized elements.
ptr::invalid_mut(!0)
ptr::without_provenance_mut(!0)
} else {
self.start().add(self.storage.len())
}

View file

@ -1,5 +1,6 @@
use rustc_errors::{
codes::*, AddToDiagnostic, Diagnostic, DiagnosticArgFromDisplay, SubdiagnosticMessageOp,
codes::*, AddToDiagnostic, DiagnosticArgFromDisplay, DiagnosticBuilder, EmissionGuarantee,
SubdiagnosticMessageOp,
};
use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_span::{symbol::Ident, Span, Symbol};
@ -41,7 +42,11 @@ pub struct InvalidAbi {
pub struct InvalidAbiReason(pub &'static str);
impl AddToDiagnostic for InvalidAbiReason {
fn add_to_diagnostic_with<F: SubdiagnosticMessageOp>(self, diag: &mut Diagnostic, _: F) {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self,
diag: &mut DiagnosticBuilder<'_, G>,
_: F,
) {
#[allow(rustc::untranslatable_diagnostic)]
diag.note(self.0);
}

View file

@ -1636,9 +1636,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
if let Some(old_def_id) = self.orig_opt_local_def_id(param) {
old_def_id
} else {
self.dcx()
.span_delayed_bug(lifetime.ident.span, "no def-id for fresh lifetime");
continue;
self.dcx().span_bug(lifetime.ident.span, "no def-id for fresh lifetime");
}
}

View file

@ -881,9 +881,10 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
&item.vis,
errors::VisibilityNotPermittedNote::TraitImpl,
);
// njn: use Dummy here
if let TyKind::Err(_) = self_ty.kind {
this.dcx().emit_err(errors::ObsoleteAuto { span: item.span });
if let TyKind::Dummy = self_ty.kind {
// Abort immediately otherwise the `TyKind::Dummy` will reach HIR lowering,
// which isn't allowed. Not a problem for this obscure, obsolete syntax.
this.dcx().emit_fatal(errors::ObsoleteAuto { span: item.span });
}
if let (&Unsafe::Yes(span), &ImplPolarity::Negative(sp)) = (unsafety, polarity)
{

View file

@ -1,7 +1,10 @@
//! Errors emitted by ast_passes.
use rustc_ast::ParamKindOrd;
use rustc_errors::{codes::*, AddToDiagnostic, Applicability, Diagnostic, SubdiagnosticMessageOp};
use rustc_errors::{
codes::*, AddToDiagnostic, Applicability, DiagnosticBuilder, EmissionGuarantee,
SubdiagnosticMessageOp,
};
use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_span::{symbol::Ident, Span, Symbol};
@ -372,7 +375,11 @@ pub struct EmptyLabelManySpans(pub Vec<Span>);
// The derive for `Vec<Span>` does multiple calls to `span_label`, adding commas between each
impl AddToDiagnostic for EmptyLabelManySpans {
fn add_to_diagnostic_with<F: SubdiagnosticMessageOp>(self, diag: &mut Diagnostic, _: F) {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self,
diag: &mut DiagnosticBuilder<'_, G>,
_: F,
) {
diag.span_labels(self.0, "");
}
}
@ -729,7 +736,11 @@ pub struct StableFeature {
}
impl AddToDiagnostic for StableFeature {
fn add_to_diagnostic_with<F: SubdiagnosticMessageOp>(self, diag: &mut Diagnostic, _: F) {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self,
diag: &mut DiagnosticBuilder<'_, G>,
_: F,
) {
diag.arg("name", self.name);
diag.arg("since", self.since);
diag.help(fluent::ast_passes_stable_since);

View file

@ -22,6 +22,9 @@ macro_rules! gate {
}};
($visitor:expr, $feature:ident, $span:expr, $explain:expr, $help:expr) => {{
if !$visitor.features.$feature && !$span.allows_unstable(sym::$feature) {
// FIXME: make this translatable
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)]
feature_err(&$visitor.sess, sym::$feature, $span, $explain).with_help($help).emit();
}
}};

View file

@ -6,9 +6,7 @@
use either::Either;
use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::FxIndexSet;
use rustc_errors::{
codes::*, struct_span_code_err, Applicability, Diagnostic, DiagnosticBuilder, MultiSpan,
};
use rustc_errors::{codes::*, struct_span_code_err, Applicability, DiagnosticBuilder, MultiSpan};
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::intravisit::{walk_block, walk_expr, Visitor};
@ -635,7 +633,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
fn suggest_assign_value(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
moved_place: PlaceRef<'tcx>,
sugg_span: Span,
) {
@ -674,7 +672,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
fn suggest_borrow_fn_like(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
ty: Ty<'tcx>,
move_sites: &[MoveSite],
value_name: &str,
@ -742,7 +740,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
fn suggest_cloning(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
ty: Ty<'tcx>,
expr: &hir::Expr<'_>,
span: Span,
@ -778,7 +776,12 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
}
}
fn suggest_adding_copy_bounds(&self, err: &mut Diagnostic, ty: Ty<'tcx>, span: Span) {
fn suggest_adding_copy_bounds(
&self,
err: &mut DiagnosticBuilder<'_>,
ty: Ty<'tcx>,
span: Span,
) {
let tcx = self.infcx.tcx;
let generics = tcx.generics_of(self.mir_def_id());
@ -1225,7 +1228,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
#[instrument(level = "debug", skip(self, err))]
fn suggest_using_local_if_applicable(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
location: Location,
issued_borrow: &BorrowData<'tcx>,
explanation: BorrowExplanation<'tcx>,
@ -1321,7 +1324,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
fn suggest_slice_method_if_applicable(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
place: Place<'tcx>,
borrowed_place: Place<'tcx>,
) {
@ -1430,7 +1433,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
/// ```
pub(crate) fn explain_iterator_advancement_in_for_loop_if_applicable(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
span: Span,
issued_spans: &UseSpans<'tcx>,
) {
@ -1617,7 +1620,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
/// ```
fn suggest_using_closure_argument_instead_of_capture(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
borrowed_place: Place<'tcx>,
issued_spans: &UseSpans<'tcx>,
) {
@ -1751,7 +1754,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
fn suggest_binding_for_closure_capture_self(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
issued_spans: &UseSpans<'tcx>,
) {
let UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
@ -2997,7 +3000,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
self.buffer_error(err);
}
fn explain_deref_coercion(&mut self, loan: &BorrowData<'tcx>, err: &mut Diagnostic) {
fn explain_deref_coercion(&mut self, loan: &BorrowData<'tcx>, err: &mut DiagnosticBuilder<'_>) {
let tcx = self.infcx.tcx;
if let (
Some(Terminator {
@ -3532,7 +3535,11 @@ enum AnnotatedBorrowFnSignature<'tcx> {
impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
/// Annotate the provided diagnostic with information about borrow from the fn signature that
/// helps explain.
pub(crate) fn emit(&self, cx: &mut MirBorrowckCtxt<'_, 'tcx>, diag: &mut Diagnostic) -> String {
pub(crate) fn emit(
&self,
cx: &mut MirBorrowckCtxt<'_, 'tcx>,
diag: &mut DiagnosticBuilder<'_>,
) -> String {
match self {
&AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => {
diag.span_label(

View file

@ -3,7 +3,7 @@
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]
use rustc_errors::{Applicability, Diagnostic};
use rustc_errors::{Applicability, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_hir::intravisit::Visitor;
use rustc_index::IndexSlice;
@ -65,7 +65,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
tcx: TyCtxt<'tcx>,
body: &Body<'tcx>,
local_names: &IndexSlice<Local, Option<Symbol>>,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
borrow_desc: &str,
borrow_span: Option<Span>,
multiple_borrow_span: Option<(Span, Span)>,
@ -306,7 +306,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
fn add_object_lifetime_default_note(
&self,
tcx: TyCtxt<'tcx>,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
unsize_ty: Ty<'tcx>,
) {
if let ty::Adt(def, args) = unsize_ty.kind() {
@ -359,7 +359,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
fn add_lifetime_bound_suggestion_to_diagnostic(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
category: &ConstraintCategory<'tcx>,
span: Span,
region_name: &RegionName,

View file

@ -5,7 +5,7 @@ use crate::session_diagnostics::{
CaptureVarKind, CaptureVarPathUseCause, OnClosureNote,
};
use itertools::Itertools;
use rustc_errors::{Applicability, Diagnostic};
use rustc_errors::{Applicability, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_hir::def::{CtorKind, Namespace};
use rustc_hir::CoroutineKind;
@ -80,7 +80,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
&self,
location: Location,
place: PlaceRef<'tcx>,
diag: &mut Diagnostic,
diag: &mut DiagnosticBuilder<'_>,
) -> bool {
debug!("add_moved_or_invoked_closure_note: location={:?} place={:?}", location, place);
let mut target = place.local_or_deref_local();
@ -588,7 +588,7 @@ impl UseSpans<'_> {
pub(super) fn args_subdiag(
self,
dcx: &rustc_errors::DiagCtxt,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
f: impl FnOnce(Span) -> CaptureArgLabel,
) {
if let UseSpans::ClosureUse { args_span, .. } = self {
@ -601,7 +601,7 @@ impl UseSpans<'_> {
pub(super) fn var_path_only_subdiag(
self,
dcx: &rustc_errors::DiagCtxt,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
action: crate::InitializationRequiringAction,
) {
use crate::InitializationRequiringAction::*;
@ -638,7 +638,7 @@ impl UseSpans<'_> {
pub(super) fn var_subdiag(
self,
dcx: &rustc_errors::DiagCtxt,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
kind: Option<rustc_middle::mir::BorrowKind>,
f: impl FnOnce(hir::ClosureKind, Span) -> CaptureVarCause,
) {
@ -1010,7 +1010,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
fn explain_captures(
&mut self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
span: Span,
move_span: Span,
move_spans: UseSpans<'tcx>,

View file

@ -1,7 +1,7 @@
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]
use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder};
use rustc_errors::{Applicability, DiagnosticBuilder};
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty};
use rustc_mir_dataflow::move_paths::{LookupResult, MovePathIndex};
@ -437,7 +437,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
err
}
fn add_move_hints(&self, error: GroupedMoveError<'tcx>, err: &mut Diagnostic, span: Span) {
fn add_move_hints(
&self,
error: GroupedMoveError<'tcx>,
err: &mut DiagnosticBuilder<'_>,
span: Span,
) {
match error {
GroupedMoveError::MovesFromPlace { mut binds_to, move_from, .. } => {
self.add_borrow_suggestions(err, span);
@ -500,7 +505,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
}
}
fn add_borrow_suggestions(&self, err: &mut Diagnostic, span: Span) {
fn add_borrow_suggestions(&self, err: &mut DiagnosticBuilder<'_>, span: Span) {
match self.infcx.tcx.sess.source_map().span_to_snippet(span) {
Ok(snippet) if snippet.starts_with('*') => {
err.span_suggestion_verbose(
@ -521,7 +526,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
}
}
fn add_move_error_suggestions(&self, err: &mut Diagnostic, binds_to: &[Local]) {
fn add_move_error_suggestions(&self, err: &mut DiagnosticBuilder<'_>, binds_to: &[Local]) {
let mut suggestions: Vec<(Span, String, String)> = Vec::new();
for local in binds_to {
let bind_to = &self.body.local_decls[*local];
@ -573,7 +578,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
}
}
fn add_move_error_details(&self, err: &mut Diagnostic, binds_to: &[Local]) {
fn add_move_error_details(&self, err: &mut DiagnosticBuilder<'_>, binds_to: &[Local]) {
for (j, local) in binds_to.iter().enumerate() {
let bind_to = &self.body.local_decls[*local];
let binding_span = bind_to.source_info.span;
@ -610,7 +615,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
/// expansion of a packed struct.
/// Such errors happen because derive macro expansions shy away from taking
/// references to the struct's fields since doing so would be undefined behaviour
fn add_note_for_packed_struct_derive(&self, err: &mut Diagnostic, local: Local) {
fn add_note_for_packed_struct_derive(&self, err: &mut DiagnosticBuilder<'_>, local: Local) {
let local_place: PlaceRef<'tcx> = local.into();
let local_ty = local_place.ty(self.body.local_decls(), self.infcx.tcx).ty.peel_refs();

View file

@ -2,7 +2,7 @@
#![allow(rustc::untranslatable_diagnostic)]
use hir::ExprKind;
use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder};
use rustc_errors::{Applicability, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_hir::intravisit::Visitor;
use rustc_hir::Node;
@ -540,7 +540,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
}
}
fn suggest_map_index_mut_alternatives(&self, ty: Ty<'tcx>, err: &mut Diagnostic, span: Span) {
fn suggest_map_index_mut_alternatives(
&self,
ty: Ty<'tcx>,
err: &mut DiagnosticBuilder<'tcx>,
span: Span,
) {
let Some(adt) = ty.ty_adt_def() else { return };
let did = adt.did();
if self.infcx.tcx.is_diagnostic_item(sym::HashMap, did)
@ -548,7 +553,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
{
struct V<'a, 'tcx> {
assign_span: Span,
err: &'a mut Diagnostic,
err: &'a mut DiagnosticBuilder<'tcx>,
ty: Ty<'tcx>,
suggested: bool,
}
@ -790,7 +795,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
tcx: TyCtxt<'_>,
closure_local_def_id: hir::def_id::LocalDefId,
the_place_err: PlaceRef<'tcx>,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
) {
let tables = tcx.typeck(closure_local_def_id);
if let Some((span, closure_kind_origin)) = tcx.closure_kind_origin(closure_local_def_id) {
@ -852,7 +857,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
// Attempt to search similar mutable associated items for suggestion.
// In the future, attempt in all path but initially for RHS of for_loop
fn suggest_similar_mut_method_for_for_loop(&self, err: &mut Diagnostic, span: Span) {
fn suggest_similar_mut_method_for_for_loop(&self, err: &mut DiagnosticBuilder<'_>, span: Span) {
use hir::{
BorrowKind, Expr,
ExprKind::{AddrOf, Block, Call, MethodCall},
@ -936,7 +941,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
}
/// Targeted error when encountering an `FnMut` closure where an `Fn` closure was expected.
fn expected_fn_found_fn_mut_call(&self, err: &mut Diagnostic, sp: Span, act: &str) {
fn expected_fn_found_fn_mut_call(&self, err: &mut DiagnosticBuilder<'_>, sp: Span, act: &str) {
err.span_label(sp, format!("cannot {act}"));
let hir = self.infcx.tcx.hir();

View file

@ -5,7 +5,7 @@
#![allow(rustc::untranslatable_diagnostic)]
use rustc_data_structures::fx::FxIndexSet;
use rustc_errors::Diagnostic;
use rustc_errors::DiagnosticBuilder;
use rustc_middle::ty::RegionVid;
use smallvec::SmallVec;
use std::collections::BTreeMap;
@ -158,13 +158,13 @@ impl OutlivesSuggestionBuilder {
self.constraints_to_add.entry(fr).or_default().push(outlived_fr);
}
/// Emit an intermediate note on the given `Diagnostic` if the involved regions are
/// Emit an intermediate note on the given `DiagnosticBuilder` if the involved regions are
/// suggestable.
pub(crate) fn intermediate_suggestion(
&mut self,
mbcx: &MirBorrowckCtxt<'_, '_>,
errci: &ErrorConstraintInfo<'_>,
diag: &mut Diagnostic,
diag: &mut DiagnosticBuilder<'_>,
) {
// Emit an intermediate note.
let fr_name = self.region_vid_to_name(mbcx, errci.fr);

View file

@ -1,7 +1,7 @@
//! Error reporting machinery for lifetime errors.
use rustc_data_structures::fx::FxIndexSet;
use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, MultiSpan};
use rustc_errors::{Applicability, DiagnosticBuilder, MultiSpan};
use rustc_hir as hir;
use rustc_hir::def::Res::Def;
use rustc_hir::def_id::DefId;
@ -251,6 +251,9 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
hrtb_bounds.iter().for_each(|bound| {
let Trait(PolyTraitRef { trait_ref, span: trait_span, .. }, _) = bound else { return; };
// FIXME: make this translatable
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)]
diag.span_note(
*trait_span,
"due to current limitations in the borrow checker, this implies a `'static` lifetime"
@ -421,6 +424,9 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
/// ```
///
/// Here we would be invoked with `fr = 'a` and `outlived_fr = 'b`.
// FIXME: make this translatable
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)]
pub(crate) fn report_region_error(
&mut self,
fr: RegionVid,
@ -685,12 +691,18 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx, *span, escapes_from);
if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
// FIXME: make this translatable
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)]
diag.span_label(
outlived_fr_span,
format!("`{outlived_fr_name}` declared here, outside of the {escapes_from} body",),
);
}
// FIXME: make this translatable
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)]
if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
diag.span_label(
fr_span,
@ -714,6 +726,9 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
let outlived_fr_region_name = self.give_region_a_name(errci.outlived_fr).unwrap();
outlived_fr_region_name.highlight_region_name(&mut diag);
// FIXME: make this translatable
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)]
diag.span_label(
*span,
format!(
@ -808,7 +823,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
/// ```
fn add_static_impl_trait_suggestion(
&self,
diag: &mut Diagnostic,
diag: &mut DiagnosticBuilder<'_>,
fr: RegionVid,
// We need to pass `fr_name` - computing it again will label it twice.
fr_name: RegionName,
@ -897,7 +912,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
fn maybe_suggest_constrain_dyn_trait_impl(
&self,
diag: &mut Diagnostic,
diag: &mut DiagnosticBuilder<'_>,
f: Region<'tcx>,
o: Region<'tcx>,
category: &ConstraintCategory<'tcx>,
@ -959,7 +974,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
#[instrument(skip(self, err), level = "debug")]
fn suggest_constrain_dyn_trait_in_impl(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
found_dids: &FxIndexSet<DefId>,
ident: Ident,
self_ty: &hir::Ty<'_>,
@ -994,7 +1009,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
fn suggest_adding_lifetime_params(
&self,
diag: &mut Diagnostic,
diag: &mut DiagnosticBuilder<'_>,
sub: RegionVid,
sup: RegionVid,
) {
@ -1023,7 +1038,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
suggest_adding_lifetime_params(self.infcx.tcx, sub, ty_sup, ty_sub, diag);
}
fn suggest_move_on_borrowing_closure(&self, diag: &mut Diagnostic) {
fn suggest_move_on_borrowing_closure(&self, diag: &mut DiagnosticBuilder<'_>) {
let map = self.infcx.tcx.hir();
let body_id = map.body_owned_by(self.mir_def_id());
let expr = &map.body(body_id).value.peel_blocks();

View file

@ -5,7 +5,7 @@ use std::fmt::{self, Display};
use std::iter;
use rustc_data_structures::fx::IndexEntry;
use rustc_errors::Diagnostic;
use rustc_errors::DiagnosticBuilder;
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
use rustc_middle::ty::print::RegionHighlightMode;
@ -106,7 +106,7 @@ impl RegionName {
}
}
pub(crate) fn highlight_region_name(&self, diag: &mut Diagnostic) {
pub(crate) fn highlight_region_name(&self, diag: &mut DiagnosticBuilder<'_>) {
match &self.source {
RegionNameSource::NamedLateParamRegion(span)
| RegionNameSource::NamedEarlyParamRegion(span) => {
@ -626,9 +626,9 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {
| GenericArgKind::Const(_),
_,
) => {
// HIR lowering sometimes doesn't catch this in erroneous
// programs, so we need to use span_delayed_bug here. See #82126.
self.dcx().span_delayed_bug(
// This was previously a `span_delayed_bug` and could be
// reached by the test for #82126, but no longer.
self.dcx().span_bug(
hir_arg.span(),
format!("unmatched arg and hir arg: found {kind:?} vs {hir_arg:?}"),
);

View file

@ -2497,6 +2497,8 @@ mod diags {
}
for (_, (mut diag, count)) in std::mem::take(&mut self.diags.buffered_mut_errors) {
if count > 10 {
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)]
diag.note(format!("...and {} other attempted mutable borrows", count - 10));
}
self.diags.buffered_diags.push(BufferedDiag::Error(diag));

View file

@ -5,7 +5,7 @@ use rustc_data_structures::binary_search_util;
use rustc_data_structures::frozen::Frozen;
use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
use rustc_data_structures::graph::scc::Sccs;
use rustc_errors::Diagnostic;
use rustc_errors::DiagnosticBuilder;
use rustc_hir::def_id::CRATE_DEF_ID;
use rustc_index::{IndexSlice, IndexVec};
use rustc_infer::infer::outlives::test_type_match;
@ -592,7 +592,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
}
/// Adds annotations for `#[rustc_regions]`; see `UniversalRegions::annotate`.
pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diagnostic) {
pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut DiagnosticBuilder<'_, ()>) {
self.universal_regions.annotate(tcx, err)
}

View file

@ -100,7 +100,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
locations: Locations,
) {
for (predicate, span) in instantiated_predicates {
debug!(?predicate);
debug!(?span, ?predicate);
let category = ConstraintCategory::Predicate(span);
let predicate = self.normalize_with_category(predicate, locations, category);
self.prove_predicate(predicate, locations, category);

View file

@ -8,7 +8,7 @@ use rustc_middle::mir::{ClosureOutlivesSubject, ClosureRegionRequirements, Const
use rustc_middle::traits::query::NoSolution;
use rustc_middle::traits::ObligationCause;
use rustc_middle::ty::{self, GenericArgKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt};
use rustc_span::{Span, DUMMY_SP};
use rustc_span::Span;
use rustc_trait_selection::solve::deeply_normalize;
use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
@ -183,7 +183,7 @@ impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> {
// we don't actually use this for anything, but
// the `TypeOutlives` code needs an origin.
let origin = infer::RelateParamBound(DUMMY_SP, t1, None);
let origin = infer::RelateParamBound(self.span, t1, None);
TypeOutlives::new(
&mut *self,

View file

@ -10,7 +10,7 @@ use rustc_middle::mir::ConstraintCategory;
use rustc_middle::traits::query::OutlivesBound;
use rustc_middle::traits::ObligationCause;
use rustc_middle::ty::{self, RegionVid, Ty, TypeVisitableExt};
use rustc_span::{ErrorGuaranteed, DUMMY_SP};
use rustc_span::{ErrorGuaranteed, Span};
use rustc_trait_selection::solve::deeply_normalize;
use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt;
use rustc_trait_selection::traits::query::type_op::{self, TypeOp};
@ -269,7 +269,7 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> {
debug!("build: input_or_output={:?}", ty);
// We add implied bounds from both the unnormalized and normalized ty.
// See issue #87748
let constraints_unnorm = self.add_implied_bounds(ty);
let constraints_unnorm = self.add_implied_bounds(ty, span);
if let Some(c) = constraints_unnorm {
constraints.push(c)
}
@ -299,7 +299,7 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> {
// ```
// Both &Self::Bar and &() are WF
if ty != norm_ty {
let constraints_norm = self.add_implied_bounds(norm_ty);
let constraints_norm = self.add_implied_bounds(norm_ty, span);
if let Some(c) = constraints_norm {
constraints.push(c)
}
@ -316,6 +316,9 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> {
.and(type_op::normalize::Normalize::new(ty))
.fully_perform(self.infcx, span)
else {
// Note: this path is currently not reached in any test, so
// any example that triggers this would be worth minimizing
// and converting into a test.
tcx.dcx().span_delayed_bug(span, format!("failed to normalize {ty:?}"));
continue;
};
@ -323,7 +326,7 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> {
// We currently add implied bounds from the normalized ty only.
// This is more conservative and matches wfcheck behavior.
let c = self.add_implied_bounds(norm_ty);
let c = self.add_implied_bounds(norm_ty, span);
constraints.extend(c);
}
}
@ -361,11 +364,15 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> {
/// the same time, compute and add any implied bounds that come
/// from this local.
#[instrument(level = "debug", skip(self))]
fn add_implied_bounds(&mut self, ty: Ty<'tcx>) -> Option<&'tcx QueryRegionConstraints<'tcx>> {
fn add_implied_bounds(
&mut self,
ty: Ty<'tcx>,
span: Span,
) -> Option<&'tcx QueryRegionConstraints<'tcx>> {
let TypeOpOutput { output: bounds, constraints, .. } = self
.param_env
.and(type_op::implied_outlives_bounds::ImpliedOutlivesBounds { ty })
.fully_perform(self.infcx, DUMMY_SP)
.fully_perform(self.infcx, span)
.map_err(|_: ErrorGuaranteed| debug!("failed to compute implied bounds {:?}", ty))
.ok()?;
debug!(?bounds, ?constraints);

View file

@ -154,8 +154,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
if argument_index + 1 >= body.local_decls.len() {
self.tcx()
.dcx()
.span_delayed_bug(body.span, "found more normalized_input_ty than local_decls");
break;
.span_bug(body.span, "found more normalized_input_ty than local_decls");
}
// In MIR, argument N is stored in local N+1.

View file

@ -37,7 +37,7 @@ use rustc_mir_dataflow::points::DenseLocationMap;
use rustc_span::def_id::CRATE_DEF_ID;
use rustc_span::source_map::Spanned;
use rustc_span::symbol::sym;
use rustc_span::{Span, DUMMY_SP};
use rustc_span::Span;
use rustc_target::abi::{FieldIdx, FIRST_VARIANT};
use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
@ -220,14 +220,13 @@ pub(crate) fn type_check<'mir, 'tcx>(
"opaque_type_map",
),
);
let mut hidden_type = infcx.resolve_vars_if_possible(decl.hidden_type);
let hidden_type = infcx.resolve_vars_if_possible(decl.hidden_type);
trace!("finalized opaque type {:?} to {:#?}", opaque_type_key, hidden_type.ty.kind());
if hidden_type.has_non_region_infer() {
let reported = infcx.dcx().span_delayed_bug(
infcx.dcx().span_bug(
decl.hidden_type.span,
format!("could not resolve {:#?}", hidden_type.ty.kind()),
);
hidden_type.ty = Ty::new_error(infcx.tcx, reported);
}
(opaque_type_key, hidden_type)
@ -1014,7 +1013,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
) -> Self {
let mut checker = Self {
infcx,
last_span: DUMMY_SP,
last_span: body.span,
body,
user_type_annotations: &body.user_type_annotations,
param_env,
@ -1089,10 +1088,9 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
);
if result.is_err() {
self.infcx.dcx().span_delayed_bug(
self.body.span,
"failed re-defining predefined opaques in mir typeck",
);
self.infcx
.dcx()
.span_bug(self.body.span, "failed re-defining predefined opaques in mir typeck");
}
}
@ -2766,7 +2764,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
self.param_env,
self.known_type_outlives_obligations,
locations,
DUMMY_SP, // irrelevant; will be overridden.
self.body.span, // irrelevant; will be overridden.
ConstraintCategory::Boring, // same as above.
self.borrowck_context.constraints,
)

View file

@ -1,11 +1,14 @@
use rustc_data_structures::fx::FxHashMap;
use rustc_errors::ErrorGuaranteed;
use rustc_infer::infer::nll_relate::{TypeRelating, TypeRelatingDelegate};
use rustc_infer::infer::NllRegionVariableOrigin;
use rustc_infer::traits::PredicateObligations;
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use rustc_infer::infer::{NllRegionVariableOrigin, ObligationEmittingRelation};
use rustc_infer::traits::{Obligation, PredicateObligations};
use rustc_middle::mir::ConstraintCategory;
use rustc_middle::traits::query::NoSolution;
use rustc_middle::ty::relate::TypeRelation;
use rustc_middle::ty::{self, Ty};
use rustc_middle::traits::ObligationCause;
use rustc_middle::ty::fold::FnMutDelegate;
use rustc_middle::ty::relate::{Relate, RelateResult, TypeRelation};
use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt};
use rustc_span::symbol::sym;
use rustc_span::{Span, Symbol};
@ -32,12 +35,8 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
locations: Locations,
category: ConstraintCategory<'tcx>,
) -> Result<(), NoSolution> {
TypeRelating::new(
self.infcx,
NllTypeRelatingDelegate::new(self, locations, category, UniverseInfo::relate(a, b)),
v,
)
.relate(a, b)?;
NllTypeRelating::new(self, locations, category, UniverseInfo::relate(a, b), v)
.relate(a, b)?;
Ok(())
}
@ -49,9 +48,11 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
locations: Locations,
category: ConstraintCategory<'tcx>,
) -> Result<(), NoSolution> {
TypeRelating::new(
self.infcx,
NllTypeRelatingDelegate::new(self, locations, category, UniverseInfo::other()),
NllTypeRelating::new(
self,
locations,
category,
UniverseInfo::other(),
ty::Variance::Invariant,
)
.relate(a, b)?;
@ -59,7 +60,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
}
}
struct NllTypeRelatingDelegate<'me, 'bccx, 'tcx> {
pub struct NllTypeRelating<'me, 'bccx, 'tcx> {
type_checker: &'me mut TypeChecker<'bccx, 'tcx>,
/// Where (and why) is this relation taking place?
@ -71,26 +72,177 @@ struct NllTypeRelatingDelegate<'me, 'bccx, 'tcx> {
/// Information so that error reporting knows what types we are relating
/// when reporting a bound region error.
universe_info: UniverseInfo<'tcx>,
/// How are we relating `a` and `b`?
///
/// - Covariant means `a <: b`.
/// - Contravariant means `b <: a`.
/// - Invariant means `a == b`.
/// - Bivariant means that it doesn't matter.
ambient_variance: ty::Variance,
ambient_variance_info: ty::VarianceDiagInfo<'tcx>,
}
impl<'me, 'bccx, 'tcx> NllTypeRelatingDelegate<'me, 'bccx, 'tcx> {
fn new(
impl<'me, 'bccx, 'tcx> NllTypeRelating<'me, 'bccx, 'tcx> {
pub fn new(
type_checker: &'me mut TypeChecker<'bccx, 'tcx>,
locations: Locations,
category: ConstraintCategory<'tcx>,
universe_info: UniverseInfo<'tcx>,
ambient_variance: ty::Variance,
) -> Self {
Self { type_checker, locations, category, universe_info }
}
}
impl<'tcx> TypeRelatingDelegate<'tcx> for NllTypeRelatingDelegate<'_, '_, 'tcx> {
fn span(&self) -> Span {
self.locations.span(self.type_checker.body)
Self {
type_checker,
locations,
category,
universe_info,
ambient_variance,
ambient_variance_info: ty::VarianceDiagInfo::default(),
}
}
fn param_env(&self) -> ty::ParamEnv<'tcx> {
self.type_checker.param_env
fn ambient_covariance(&self) -> bool {
match self.ambient_variance {
ty::Variance::Covariant | ty::Variance::Invariant => true,
ty::Variance::Contravariant | ty::Variance::Bivariant => false,
}
}
fn ambient_contravariance(&self) -> bool {
match self.ambient_variance {
ty::Variance::Contravariant | ty::Variance::Invariant => true,
ty::Variance::Covariant | ty::Variance::Bivariant => false,
}
}
fn relate_opaques(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, ()> {
let infcx = self.type_checker.infcx;
debug_assert!(!infcx.next_trait_solver());
let (a, b) = if self.a_is_expected() { (a, b) } else { (b, a) };
// `handle_opaque_type` cannot handle subtyping, so to support subtyping
// we instead eagerly generalize here. This is a bit of a mess but will go
// away once we're using the new solver.
let mut enable_subtyping = |ty, ty_is_expected| {
let ty_vid = infcx.next_ty_var_id_in_universe(
TypeVariableOrigin {
kind: TypeVariableOriginKind::MiscVariable,
span: self.span(),
},
ty::UniverseIndex::ROOT,
);
let variance = if ty_is_expected {
self.ambient_variance
} else {
self.ambient_variance.xform(ty::Contravariant)
};
self.type_checker.infcx.instantiate_ty_var(
self,
ty_is_expected,
ty_vid,
variance,
ty,
)?;
Ok(infcx.resolve_vars_if_possible(Ty::new_infer(infcx.tcx, ty::TyVar(ty_vid))))
};
let (a, b) = match (a.kind(), b.kind()) {
(&ty::Alias(ty::Opaque, ..), _) => (a, enable_subtyping(b, false)?),
(_, &ty::Alias(ty::Opaque, ..)) => (enable_subtyping(a, true)?, b),
_ => unreachable!(
"expected at least one opaque type in `relate_opaques`, got {a} and {b}."
),
};
let cause = ObligationCause::dummy_with_span(self.span());
let obligations =
infcx.handle_opaque_type(a, b, true, &cause, self.param_env())?.obligations;
self.register_obligations(obligations);
Ok(())
}
fn enter_forall<T, U>(
&mut self,
binder: ty::Binder<'tcx, T>,
f: impl FnOnce(&mut Self, T) -> U,
) -> U
where
T: ty::TypeFoldable<TyCtxt<'tcx>> + Copy,
{
let value = if let Some(inner) = binder.no_bound_vars() {
inner
} else {
let infcx = self.type_checker.infcx;
let mut lazy_universe = None;
let delegate = FnMutDelegate {
regions: &mut |br: ty::BoundRegion| {
// The first time this closure is called, create a
// new universe for the placeholders we will make
// from here out.
let universe = lazy_universe.unwrap_or_else(|| {
let universe = self.create_next_universe();
lazy_universe = Some(universe);
universe
});
let placeholder = ty::PlaceholderRegion { universe, bound: br };
debug!(?placeholder);
let placeholder_reg = self.next_placeholder_region(placeholder);
debug!(?placeholder_reg);
placeholder_reg
},
types: &mut |_bound_ty: ty::BoundTy| {
unreachable!("we only replace regions in nll_relate, not types")
},
consts: &mut |_bound_var: ty::BoundVar, _ty| {
unreachable!("we only replace regions in nll_relate, not consts")
},
};
infcx.tcx.replace_bound_vars_uncached(binder, delegate)
};
debug!(?value);
f(self, value)
}
#[instrument(skip(self), level = "debug")]
fn instantiate_binder_with_existentials<T>(&mut self, binder: ty::Binder<'tcx, T>) -> T
where
T: ty::TypeFoldable<TyCtxt<'tcx>> + Copy,
{
if let Some(inner) = binder.no_bound_vars() {
return inner;
}
let infcx = self.type_checker.infcx;
let mut reg_map = FxHashMap::default();
let delegate = FnMutDelegate {
regions: &mut |br: ty::BoundRegion| {
if let Some(ex_reg_var) = reg_map.get(&br) {
return *ex_reg_var;
} else {
let ex_reg_var = self.next_existential_region_var(true, br.kind.get_name());
debug!(?ex_reg_var);
reg_map.insert(br, ex_reg_var);
ex_reg_var
}
},
types: &mut |_bound_ty: ty::BoundTy| {
unreachable!("we only replace regions in nll_relate, not types")
},
consts: &mut |_bound_var: ty::BoundVar, _ty| {
unreachable!("we only replace regions in nll_relate, not consts")
},
};
let replaced = infcx.tcx.replace_bound_vars_uncached(binder, delegate);
debug!(?replaced);
replaced
}
fn create_next_universe(&mut self) -> ty::UniverseIndex {
@ -143,22 +295,6 @@ impl<'tcx> TypeRelatingDelegate<'tcx> for NllTypeRelatingDelegate<'_, '_, 'tcx>
reg
}
#[instrument(skip(self), level = "debug")]
fn generalize_existential(&mut self, universe: ty::UniverseIndex) -> ty::Region<'tcx> {
let reg = self.type_checker.infcx.next_nll_region_var_in_universe(
NllRegionVariableOrigin::Existential { from_forall: false },
universe,
);
if cfg!(debug_assertions) {
let mut var_to_origin = self.type_checker.infcx.reg_var_to_origin.borrow_mut();
let prev = var_to_origin.insert(reg.as_var(), RegionCtxt::Existential(None));
assert_eq!(prev, None);
}
reg
}
fn push_outlives(
&mut self,
sup: ty::Region<'tcx>,
@ -179,11 +315,250 @@ impl<'tcx> TypeRelatingDelegate<'tcx> for NllTypeRelatingDelegate<'_, '_, 'tcx>
},
);
}
}
fn forbid_inference_vars() -> bool {
impl<'bccx, 'tcx> TypeRelation<'tcx> for NllTypeRelating<'_, 'bccx, 'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.type_checker.infcx.tcx
}
fn tag(&self) -> &'static str {
"nll::subtype"
}
fn a_is_expected(&self) -> bool {
true
}
#[instrument(skip(self, info), level = "trace", ret)]
fn relate_with_variance<T: Relate<'tcx>>(
&mut self,
variance: ty::Variance,
info: ty::VarianceDiagInfo<'tcx>,
a: T,
b: T,
) -> RelateResult<'tcx, T> {
let old_ambient_variance = self.ambient_variance;
self.ambient_variance = self.ambient_variance.xform(variance);
self.ambient_variance_info = self.ambient_variance_info.xform(info);
debug!(?self.ambient_variance);
// In a bivariant context this always succeeds.
let r =
if self.ambient_variance == ty::Variance::Bivariant { a } else { self.relate(a, b)? };
self.ambient_variance = old_ambient_variance;
Ok(r)
}
#[instrument(skip(self), level = "debug")]
fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
let infcx = self.type_checker.infcx;
let a = self.type_checker.infcx.shallow_resolve(a);
assert!(!b.has_non_region_infer(), "unexpected inference var {:?}", b);
if a == b {
return Ok(a);
}
match (a.kind(), b.kind()) {
(_, &ty::Infer(ty::TyVar(_))) => {
span_bug!(
self.span(),
"should not be relating type variables on the right in MIR typeck"
);
}
(&ty::Infer(ty::TyVar(a_vid)), _) => {
infcx.instantiate_ty_var(self, true, a_vid, self.ambient_variance, b)?
}
(
&ty::Alias(ty::Opaque, ty::AliasTy { def_id: a_def_id, .. }),
&ty::Alias(ty::Opaque, ty::AliasTy { def_id: b_def_id, .. }),
) if a_def_id == b_def_id || infcx.next_trait_solver() => {
infcx.super_combine_tys(self, a, b).map(|_| ()).or_else(|err| {
// This behavior is only there for the old solver, the new solver
// shouldn't ever fail. Instead, it unconditionally emits an
// alias-relate goal.
assert!(!self.type_checker.infcx.next_trait_solver());
self.tcx().dcx().span_delayed_bug(
self.span(),
"failure to relate an opaque to itself should result in an error later on",
);
if a_def_id.is_local() { self.relate_opaques(a, b) } else { Err(err) }
})?;
}
(&ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }), _)
| (_, &ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }))
if def_id.is_local() && !self.type_checker.infcx.next_trait_solver() =>
{
self.relate_opaques(a, b)?;
}
_ => {
debug!(?a, ?b, ?self.ambient_variance);
// Will also handle unification of `IntVar` and `FloatVar`.
self.type_checker.infcx.super_combine_tys(self, a, b)?;
}
}
Ok(a)
}
#[instrument(skip(self), level = "trace")]
fn regions(
&mut self,
a: ty::Region<'tcx>,
b: ty::Region<'tcx>,
) -> RelateResult<'tcx, ty::Region<'tcx>> {
debug!(?self.ambient_variance);
if self.ambient_covariance() {
// Covariant: &'a u8 <: &'b u8. Hence, `'a: 'b`.
self.push_outlives(a, b, self.ambient_variance_info);
}
if self.ambient_contravariance() {
// Contravariant: &'b u8 <: &'a u8. Hence, `'b: 'a`.
self.push_outlives(b, a, self.ambient_variance_info);
}
Ok(a)
}
fn consts(
&mut self,
a: ty::Const<'tcx>,
b: ty::Const<'tcx>,
) -> RelateResult<'tcx, ty::Const<'tcx>> {
let a = self.type_checker.infcx.shallow_resolve(a);
assert!(!a.has_non_region_infer(), "unexpected inference var {:?}", a);
assert!(!b.has_non_region_infer(), "unexpected inference var {:?}", b);
self.type_checker.infcx.super_combine_consts(self, a, b)
}
#[instrument(skip(self), level = "trace")]
fn binders<T>(
&mut self,
a: ty::Binder<'tcx, T>,
b: ty::Binder<'tcx, T>,
) -> RelateResult<'tcx, ty::Binder<'tcx, T>>
where
T: Relate<'tcx>,
{
// We want that
//
// ```
// for<'a> fn(&'a u32) -> &'a u32 <:
// fn(&'b u32) -> &'b u32
// ```
//
// but not
//
// ```
// fn(&'a u32) -> &'a u32 <:
// for<'b> fn(&'b u32) -> &'b u32
// ```
//
// We therefore proceed as follows:
//
// - Instantiate binders on `b` universally, yielding a universe U1.
// - Instantiate binders on `a` existentially in U1.
debug!(?self.ambient_variance);
if let (Some(a), Some(b)) = (a.no_bound_vars(), b.no_bound_vars()) {
// Fast path for the common case.
self.relate(a, b)?;
return Ok(ty::Binder::dummy(a));
}
if self.ambient_covariance() {
// Covariance, so we want `for<..> A <: for<..> B` --
// therefore we compare any instantiation of A (i.e., A
// instantiated with existentials) against every
// instantiation of B (i.e., B instantiated with
// universals).
// Reset the ambient variance to covariant. This is needed
// to correctly handle cases like
//
// for<'a> fn(&'a u32, &'a u32) == for<'b, 'c> fn(&'b u32, &'c u32)
//
// Somewhat surprisingly, these two types are actually
// **equal**, even though the one on the right looks more
// polymorphic. The reason is due to subtyping. To see it,
// consider that each function can call the other:
//
// - The left function can call the right with `'b` and
// `'c` both equal to `'a`
//
// - The right function can call the left with `'a` set to
// `{P}`, where P is the point in the CFG where the call
// itself occurs. Note that `'b` and `'c` must both
// include P. At the point, the call works because of
// subtyping (i.e., `&'b u32 <: &{P} u32`).
let variance = std::mem::replace(&mut self.ambient_variance, ty::Variance::Covariant);
// Note: the order here is important. Create the placeholders first, otherwise
// we assign the wrong universe to the existential!
self.enter_forall(b, |this, b| {
let a = this.instantiate_binder_with_existentials(a);
this.relate(a, b)
})?;
self.ambient_variance = variance;
}
if self.ambient_contravariance() {
// Contravariance, so we want `for<..> A :> for<..> B`
// -- therefore we compare every instantiation of A (i.e.,
// A instantiated with universals) against any
// instantiation of B (i.e., B instantiated with
// existentials). Opposite of above.
// Reset ambient variance to contravariance. See the
// covariant case above for an explanation.
let variance =
std::mem::replace(&mut self.ambient_variance, ty::Variance::Contravariant);
self.enter_forall(a, |this, a| {
let b = this.instantiate_binder_with_existentials(b);
this.relate(a, b)
})?;
self.ambient_variance = variance;
}
Ok(a)
}
}
impl<'bccx, 'tcx> ObligationEmittingRelation<'tcx> for NllTypeRelating<'_, 'bccx, 'tcx> {
fn span(&self) -> Span {
self.locations.span(self.type_checker.body)
}
fn param_env(&self) -> ty::ParamEnv<'tcx> {
self.type_checker.param_env
}
fn register_predicates(&mut self, obligations: impl IntoIterator<Item: ty::ToPredicate<'tcx>>) {
self.register_obligations(
obligations
.into_iter()
.map(|to_pred| {
Obligation::new(self.tcx(), ObligationCause::dummy(), self.param_env(), to_pred)
})
.collect(),
);
}
fn register_obligations(&mut self, obligations: PredicateObligations<'tcx>) {
let _: Result<_, ErrorGuaranteed> = self.type_checker.fully_perform_op(
self.locations,
@ -196,4 +571,32 @@ impl<'tcx> TypeRelatingDelegate<'tcx> for NllTypeRelatingDelegate<'_, '_, 'tcx>
},
);
}
fn alias_relate_direction(&self) -> ty::AliasRelationDirection {
unreachable!("manually overridden to handle ty::Variance::Contravariant ambient variance")
}
fn register_type_relate_obligation(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) {
self.register_predicates([ty::Binder::dummy(match self.ambient_variance {
ty::Variance::Covariant => ty::PredicateKind::AliasRelate(
a.into(),
b.into(),
ty::AliasRelationDirection::Subtype,
),
// a :> b is b <: a
ty::Variance::Contravariant => ty::PredicateKind::AliasRelate(
b.into(),
a.into(),
ty::AliasRelationDirection::Subtype,
),
ty::Variance::Invariant => ty::PredicateKind::AliasRelate(
a.into(),
b.into(),
ty::AliasRelationDirection::Equate,
),
ty::Variance::Bivariant => {
unreachable!("cannot defer an alias-relate goal with Bivariant variance (yet?)")
}
})]);
}
}

View file

@ -16,7 +16,7 @@
#![allow(rustc::untranslatable_diagnostic)]
use rustc_data_structures::fx::FxIndexMap;
use rustc_errors::Diagnostic;
use rustc_errors::DiagnosticBuilder;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::lang_items::LangItem;
use rustc_hir::BodyOwnerKind;
@ -343,7 +343,7 @@ impl<'tcx> UniversalRegions<'tcx> {
/// that this region imposes on others. The methods in this file
/// handle the part about dumping the inference context internal
/// state.
pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diagnostic) {
pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut DiagnosticBuilder<'_, ()>) {
match self.defining_ty {
DefiningTy::Closure(def_id, args) => {
let v = with_no_trimmed_paths!(

View file

@ -773,7 +773,7 @@ pub(super) fn expand_global_asm<'cx>(
kind: ast::VisibilityKind::Inherited,
tokens: None,
},
span: ecx.with_def_site_ctxt(sp),
span: sp,
tokens: None,
})])
} else {

View file

@ -1,6 +1,6 @@
use rustc_errors::{
codes::*, AddToDiagnostic, DiagCtxt, Diagnostic, DiagnosticBuilder, EmissionGuarantee,
IntoDiagnostic, Level, MultiSpan, SingleLabelManySpans, SubdiagnosticMessageOp,
codes::*, AddToDiagnostic, DiagCtxt, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic,
Level, MultiSpan, SingleLabelManySpans, SubdiagnosticMessageOp,
};
use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_span::{symbol::Ident, Span, Symbol};
@ -611,7 +611,11 @@ pub(crate) struct FormatUnusedArg {
// Allow the singular form to be a subdiagnostic of the multiple-unused
// form of diagnostic.
impl AddToDiagnostic for FormatUnusedArg {
fn add_to_diagnostic_with<F: SubdiagnosticMessageOp>(self, diag: &mut Diagnostic, f: F) {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self,
diag: &mut DiagnosticBuilder<'_, G>,
f: F,
) {
diag.arg("named", self.named);
let msg = f(diag, crate::fluent_generated::builtin_macros_format_unused_arg.into());
diag.span_label(self.span, msg);

View file

@ -1152,17 +1152,26 @@ fn codegen_regular_intrinsic_call<'tcx>(
ret.write_cvalue(fx, ret_val);
}
sym::fadd_fast | sym::fsub_fast | sym::fmul_fast | sym::fdiv_fast | sym::frem_fast => {
sym::fadd_fast
| sym::fsub_fast
| sym::fmul_fast
| sym::fdiv_fast
| sym::frem_fast
| sym::fadd_algebraic
| sym::fsub_algebraic
| sym::fmul_algebraic
| sym::fdiv_algebraic
| sym::frem_algebraic => {
intrinsic_args!(fx, args => (x, y); intrinsic);
let res = crate::num::codegen_float_binop(
fx,
match intrinsic {
sym::fadd_fast => BinOp::Add,
sym::fsub_fast => BinOp::Sub,
sym::fmul_fast => BinOp::Mul,
sym::fdiv_fast => BinOp::Div,
sym::frem_fast => BinOp::Rem,
sym::fadd_fast | sym::fadd_algebraic => BinOp::Add,
sym::fsub_fast | sym::fsub_algebraic => BinOp::Sub,
sym::fmul_fast | sym::fmul_algebraic => BinOp::Mul,
sym::fdiv_fast | sym::fdiv_algebraic => BinOp::Div,
sym::frem_fast | sym::frem_algebraic => BinOp::Rem,
_ => unreachable!(),
},
x,

View file

@ -705,6 +705,31 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> {
self.frem(lhs, rhs)
}
fn fadd_algebraic(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
// NOTE: it seems like we cannot enable fast-mode for a single operation in GCC.
lhs + rhs
}
fn fsub_algebraic(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
// NOTE: it seems like we cannot enable fast-mode for a single operation in GCC.
lhs - rhs
}
fn fmul_algebraic(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
// NOTE: it seems like we cannot enable fast-mode for a single operation in GCC.
lhs * rhs
}
fn fdiv_algebraic(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
// NOTE: it seems like we cannot enable fast-mode for a single operation in GCC.
lhs / rhs
}
fn frem_algebraic(&mut self, lhs: RValue<'gcc>, rhs: RValue<'gcc>) -> RValue<'gcc> {
// NOTE: it seems like we cannot enable fast-mode for a single operation in GCC.
self.frem(lhs, rhs)
}
fn checked_binop(&mut self, oop: OverflowOp, typ: Ty<'_>, lhs: Self::Value, rhs: Self::Value) -> (Self::Value, Self::Value) {
self.gcc_checked_binop(oop, typ, lhs, rhs)
}

View file

@ -340,6 +340,46 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
}
}
fn fadd_algebraic(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
unsafe {
let instr = llvm::LLVMBuildFAdd(self.llbuilder, lhs, rhs, UNNAMED);
llvm::LLVMRustSetAlgebraicMath(instr);
instr
}
}
fn fsub_algebraic(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
unsafe {
let instr = llvm::LLVMBuildFSub(self.llbuilder, lhs, rhs, UNNAMED);
llvm::LLVMRustSetAlgebraicMath(instr);
instr
}
}
fn fmul_algebraic(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
unsafe {
let instr = llvm::LLVMBuildFMul(self.llbuilder, lhs, rhs, UNNAMED);
llvm::LLVMRustSetAlgebraicMath(instr);
instr
}
}
fn fdiv_algebraic(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
unsafe {
let instr = llvm::LLVMBuildFDiv(self.llbuilder, lhs, rhs, UNNAMED);
llvm::LLVMRustSetAlgebraicMath(instr);
instr
}
}
fn frem_algebraic(&mut self, lhs: &'ll Value, rhs: &'ll Value) -> &'ll Value {
unsafe {
let instr = llvm::LLVMBuildFRem(self.llbuilder, lhs, rhs, UNNAMED);
llvm::LLVMRustSetAlgebraicMath(instr);
instr
}
}
fn checked_binop(
&mut self,
oop: OverflowOp,
@ -1327,17 +1367,17 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
pub fn vector_reduce_fmul(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
unsafe { llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src) }
}
pub fn vector_reduce_fadd_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
pub fn vector_reduce_fadd_algebraic(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
unsafe {
let instr = llvm::LLVMRustBuildVectorReduceFAdd(self.llbuilder, acc, src);
llvm::LLVMRustSetFastMath(instr);
llvm::LLVMRustSetAlgebraicMath(instr);
instr
}
}
pub fn vector_reduce_fmul_fast(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
pub fn vector_reduce_fmul_algebraic(&mut self, acc: &'ll Value, src: &'ll Value) -> &'ll Value {
unsafe {
let instr = llvm::LLVMRustBuildVectorReduceFMul(self.llbuilder, acc, src);
llvm::LLVMRustSetFastMath(instr);
llvm::LLVMRustSetAlgebraicMath(instr);
instr
}
}

View file

@ -1880,14 +1880,14 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
arith_red!(simd_reduce_mul_ordered: vector_reduce_mul, vector_reduce_fmul, true, mul, 1.0);
arith_red!(
simd_reduce_add_unordered: vector_reduce_add,
vector_reduce_fadd_fast,
vector_reduce_fadd_algebraic,
false,
add,
0.0
);
arith_red!(
simd_reduce_mul_unordered: vector_reduce_mul,
vector_reduce_fmul_fast,
vector_reduce_fmul_algebraic,
false,
mul,
1.0

View file

@ -1618,6 +1618,7 @@ extern "C" {
) -> &'a Value;
pub fn LLVMRustSetFastMath(Instr: &Value);
pub fn LLVMRustSetAlgebraicMath(Instr: &Value);
// Miscellaneous instructions
pub fn LLVMRustGetInstrProfIncrementIntrinsic(M: &Module) -> &Value;

View file

@ -48,7 +48,7 @@ libc = "0.2.50"
[dependencies.object]
version = "0.32.1"
default-features = false
features = ["read_core", "elf", "macho", "pe", "xcoff", "unaligned", "archive", "write"]
features = ["read_core", "elf", "macho", "pe", "xcoff", "unaligned", "archive", "write", "wasm"]
[target.'cfg(windows)'.dependencies.windows]
version = "0.52.0"

View file

@ -3,7 +3,7 @@ use rustc_ast::CRATE_NODE_ID;
use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
use rustc_data_structures::memmap::Mmap;
use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_errors::{DiagCtxt, ErrorGuaranteed};
use rustc_errors::{DiagCtxt, ErrorGuaranteed, FatalError};
use rustc_fs_util::{fix_windows_verbatim_for_gcc, try_canonicalize};
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
use rustc_metadata::find_native_static_library;
@ -487,7 +487,9 @@ fn collate_raw_dylibs<'a, 'b>(
}
}
}
sess.compile_status()?;
if let Some(guar) = sess.dcx().has_errors() {
return Err(guar);
}
Ok(dylib_table
.into_iter()
.map(|(name, imports)| {
@ -720,10 +722,7 @@ fn link_dwarf_object<'a>(
Ok(())
}) {
Ok(()) => {}
Err(e) => {
sess.dcx().emit_err(errors::ThorinErrorWrapper(e));
sess.dcx().abort_if_errors();
}
Err(e) => sess.dcx().emit_fatal(errors::ThorinErrorWrapper(e)),
}
}
@ -999,7 +998,7 @@ fn link_natively<'a>(
sess.dcx().emit_note(errors::CheckInstalledVisualStudio);
sess.dcx().emit_note(errors::InsufficientVSCodeProduct);
}
sess.dcx().abort_if_errors();
FatalError.raise();
}
}

View file

@ -626,7 +626,7 @@ impl<'a> Linker for GccLinker<'a> {
// it does support --strip-all as a compatibility alias for -s.
// The --strip-debug case is handled by running an external
// `strip` utility as a separate step after linking.
if self.sess.target.os != "illumos" {
if !self.sess.target.is_like_solaris {
self.linker_arg("--strip-debug");
}
}

View file

@ -15,6 +15,7 @@ use rustc_data_structures::owned_slice::{try_slice_owned, OwnedSlice};
use rustc_metadata::creader::MetadataLoader;
use rustc_metadata::fs::METADATA_FILENAME;
use rustc_metadata::EncodedMetadata;
use rustc_serialize::leb128;
use rustc_session::Session;
use rustc_span::sym;
use rustc_target::abi::Endian;
@ -420,10 +421,9 @@ pub enum MetadataPosition {
/// it's not in an allowlist of otherwise well known dwarf section names to
/// go into the final artifact.
///
/// * WebAssembly - we actually don't have any container format for this
/// target. WebAssembly doesn't support the `dylib` crate type anyway so
/// there's no need for us to support this at this time. Consequently the
/// metadata bytes are simply stored as-is into an rlib.
/// * WebAssembly - this uses wasm files themselves as the object file format
/// so an empty file with no linking metadata but a single custom section is
/// created holding our metadata.
///
/// * COFF - Windows-like targets create an object with a section that has
/// the `IMAGE_SCN_LNK_REMOVE` flag set which ensures that if the linker
@ -438,22 +438,13 @@ pub fn create_wrapper_file(
data: &[u8],
) -> (Vec<u8>, MetadataPosition) {
let Some(mut file) = create_object_file(sess) else {
// This is used to handle all "other" targets. This includes targets
// in two categories:
//
// * Some targets don't have support in the `object` crate just yet
// to write an object file. These targets are likely to get filled
// out over time.
//
// * Targets like WebAssembly don't support dylibs, so the purpose
// of putting metadata in object files, to support linking rlibs
// into dylibs, is moot.
//
// In both of these cases it means that linking into dylibs will
// not be supported by rustc. This doesn't matter for targets like
// WebAssembly and for targets not supported by the `object` crate
// yet it means that work will need to be done in the `object` crate
// to add a case above.
if sess.target.is_like_wasm {
return (create_metadata_file_for_wasm(data, &section_name), MetadataPosition::First);
}
// Targets using this branch don't have support implemented here yet or
// they're not yet implemented in the `object` crate and will likely
// fill out this module over time.
return (data.to_vec(), MetadataPosition::Last);
};
let section = if file.format() == BinaryFormat::Xcoff {
@ -532,6 +523,9 @@ pub fn create_compressed_metadata_file(
packed_metadata.extend(metadata.raw_data());
let Some(mut file) = create_object_file(sess) else {
if sess.target.is_like_wasm {
return create_metadata_file_for_wasm(&packed_metadata, b".rustc");
}
return packed_metadata.to_vec();
};
if file.format() == BinaryFormat::Xcoff {
@ -624,3 +618,57 @@ pub fn create_compressed_metadata_file_for_xcoff(
file.append_section_data(section, data, 1);
file.write().unwrap()
}
/// Creates a simple WebAssembly object file, which is itself a wasm module,
/// that contains a custom section of the name `section_name` with contents
/// `data`.
///
/// NB: the `object` crate does not yet have support for writing the the wasm
/// object file format. The format is simple enough that for now an extra crate
/// from crates.io (such as `wasm-encoder`). The file format is:
///
/// * 4-byte header "\0asm"
/// * 4-byte version number - 1u32 in little-endian format
/// * concatenated sections, which for this object is always "custom sections"
///
/// Custom sections are then defined by:
/// * 1-byte section identifier - 0 for a custom section
/// * leb-encoded section length (size of the contents beneath this bullet)
/// * leb-encoded custom section name length
/// * custom section name
/// * section contents
///
/// One custom section, `linking`, is added here in accordance with
/// <https://github.com/WebAssembly/tool-conventions/blob/main/Linking.md>
/// which is required to inform LLD that this is an object file but it should
/// otherwise basically ignore it if it otherwise looks at it. The linking
/// section currently is defined by a single version byte (2) and then further
/// sections, but we have no more sections, so it's just the byte "2".
///
/// The next custom section is the one we're interested in.
pub fn create_metadata_file_for_wasm(data: &[u8], section_name: &[u8]) -> Vec<u8> {
let mut bytes = b"\0asm\x01\0\0\0".to_vec();
let mut append_custom_section = |section_name: &[u8], data: &[u8]| {
let mut section_name_len = [0; leb128::max_leb128_len::<usize>()];
let off = leb128::write_usize_leb128(&mut section_name_len, section_name.len());
let section_name_len = &section_name_len[..off];
let mut section_len = [0; leb128::max_leb128_len::<usize>()];
let off = leb128::write_usize_leb128(
&mut section_len,
data.len() + section_name_len.len() + section_name.len(),
);
let section_len = &section_len[..off];
bytes.push(0u8);
bytes.extend_from_slice(section_len);
bytes.extend_from_slice(section_name_len);
bytes.extend_from_slice(section_name);
bytes.extend_from_slice(data);
};
append_custom_section(b"linking", &[2]);
append_custom_section(section_name, data);
bytes
}

View file

@ -1856,9 +1856,7 @@ impl SharedEmitterMain {
Ok(SharedEmitterMessage::Diagnostic(diag)) => {
let dcx = sess.dcx();
let mut d = rustc_errors::Diagnostic::new_with_messages(diag.lvl, diag.msgs);
if let Some(code) = diag.code {
d.code(code);
}
d.code = diag.code; // may be `None`, that's ok
d.replace_args(diag.args);
dcx.emit_diagnostic(d);
}

View file

@ -449,10 +449,7 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
let Some(llfn) = cx.declare_c_main(llfty) else {
// FIXME: We should be smart and show a better diagnostic here.
let span = cx.tcx().def_span(rust_main_def_id);
let dcx = cx.tcx().dcx();
dcx.emit_err(errors::MultipleMainFunctions { span });
dcx.abort_if_errors();
bug!();
cx.tcx().dcx().emit_fatal(errors::MultipleMainFunctions { span });
};
// `main` should respect same config for frame pointer elimination as rest of code

View file

@ -250,6 +250,38 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
}
}
}
sym::fadd_algebraic
| sym::fsub_algebraic
| sym::fmul_algebraic
| sym::fdiv_algebraic
| sym::frem_algebraic => match float_type_width(arg_tys[0]) {
Some(_width) => match name {
sym::fadd_algebraic => {
bx.fadd_algebraic(args[0].immediate(), args[1].immediate())
}
sym::fsub_algebraic => {
bx.fsub_algebraic(args[0].immediate(), args[1].immediate())
}
sym::fmul_algebraic => {
bx.fmul_algebraic(args[0].immediate(), args[1].immediate())
}
sym::fdiv_algebraic => {
bx.fdiv_algebraic(args[0].immediate(), args[1].immediate())
}
sym::frem_algebraic => {
bx.frem_algebraic(args[0].immediate(), args[1].immediate())
}
_ => bug!(),
},
None => {
bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicFloatType {
span,
name,
ty: arg_tys[0],
});
return Ok(());
}
},
sym::float_to_int_unchecked => {
if float_type_width(arg_tys[0]).is_none() {

View file

@ -86,22 +86,27 @@ pub trait BuilderMethods<'a, 'tcx>:
fn add(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn fadd(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn fadd_fast(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn fadd_algebraic(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn sub(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn fsub(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn fsub_fast(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn fsub_algebraic(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn mul(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn fmul(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn fmul_fast(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn fmul_algebraic(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn udiv(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn exactudiv(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn sdiv(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn exactsdiv(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn fdiv(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn fdiv_fast(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn fdiv_algebraic(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn urem(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn srem(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn frem(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn frem_fast(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn frem_algebraic(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn shl(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn lshr(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;
fn ashr(&mut self, lhs: Self::Value, rhs: Self::Value) -> Self::Value;

View file

@ -3,10 +3,11 @@ use either::{Left, Right};
use rustc_hir::def::DefKind;
use rustc_middle::mir::interpret::{AllocId, ErrorHandled, InterpErrorInfo};
use rustc_middle::mir::{self, ConstAlloc, ConstValue};
use rustc_middle::query::TyCtxtAt;
use rustc_middle::traits::Reveal;
use rustc_middle::ty::layout::LayoutOf;
use rustc_middle::ty::print::with_no_trimmed_paths;
use rustc_middle::ty::{self, TyCtxt};
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::def_id::LocalDefId;
use rustc_span::Span;
use rustc_target::abi::{self, Abi};
@ -87,13 +88,16 @@ fn eval_body_using_ecx<'mir, 'tcx>(
}
/// The `InterpCx` is only meant to be used to do field and index projections into constants for
/// `simd_shuffle` and const patterns in match arms. It never performs alignment checks.
/// `simd_shuffle` and const patterns in match arms.
///
/// This should *not* be used to do any actual interpretation. In particular, alignment checks are
/// turned off!
///
/// The function containing the `match` that is currently being analyzed may have generic bounds
/// that inform us about the generic bounds of the constant. E.g., using an associated constant
/// of a function's generic parameter will require knowledge about the bounds on the generic
/// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
pub(crate) fn mk_eval_cx<'mir, 'tcx>(
pub(crate) fn mk_eval_cx_to_read_const_val<'mir, 'tcx>(
tcx: TyCtxt<'tcx>,
root_span: Span,
param_env: ty::ParamEnv<'tcx>,
@ -108,6 +112,19 @@ pub(crate) fn mk_eval_cx<'mir, 'tcx>(
)
}
/// Create an interpreter context to inspect the given `ConstValue`.
/// Returns both the context and an `OpTy` that represents the constant.
pub fn mk_eval_cx_for_const_val<'mir, 'tcx>(
tcx: TyCtxtAt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
val: mir::ConstValue<'tcx>,
ty: Ty<'tcx>,
) -> Option<(CompileTimeEvalContext<'mir, 'tcx>, OpTy<'tcx>)> {
let ecx = mk_eval_cx_to_read_const_val(tcx.tcx, tcx.span, param_env, CanAccessMutGlobal::No);
let op = ecx.const_val_to_op(val, ty, None).ok()?;
Some((ecx, op))
}
/// This function converts an interpreter value into a MIR constant.
///
/// The `for_diagnostics` flag turns the usual rules for returning `ConstValue::Scalar` into a
@ -203,7 +220,7 @@ pub(crate) fn turn_into_const_value<'tcx>(
let def_id = cid.instance.def.def_id();
let is_static = tcx.is_static(def_id);
// This is just accessing an already computed constant, so no need to check alignment here.
let ecx = mk_eval_cx(
let ecx = mk_eval_cx_to_read_const_val(
tcx,
tcx.def_span(key.value.instance.def_id()),
key.param_env,

View file

@ -393,11 +393,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir,
if ecx.tcx.is_ctfe_mir_available(def) {
Ok(ecx.tcx.mir_for_ctfe(def))
} else if ecx.tcx.def_kind(def) == DefKind::AssocConst {
let guar = ecx
.tcx
.dcx()
.delayed_bug("This is likely a const item that is missing from its impl");
throw_inval!(AlreadyReported(guar.into()));
ecx.tcx.dcx().bug("This is likely a const item that is missing from its impl");
} else {
// `find_mir_or_eval_fn` checks that this is a const fn before even calling us,
// so this should be unreachable.

View file

@ -47,8 +47,7 @@ pub(crate) fn try_destructure_mir_constant_for_user_output<'tcx>(
ty: Ty<'tcx>,
) -> Option<mir::DestructuredConstant<'tcx>> {
let param_env = ty::ParamEnv::reveal_all();
let ecx = mk_eval_cx(tcx.tcx, tcx.span, param_env, CanAccessMutGlobal::No);
let op = ecx.const_val_to_op(val, ty, None).ok()?;
let (ecx, op) = mk_eval_cx_for_const_val(tcx, param_env, val, ty)?;
// We go to `usize` as we cannot allocate anything bigger anyway.
let (field_count, variant, down) = match ty.kind() {

View file

@ -5,7 +5,7 @@ use rustc_middle::ty::{self, ScalarInt, Ty, TyCtxt};
use rustc_span::DUMMY_SP;
use rustc_target::abi::{Abi, VariantIdx};
use super::eval_queries::{mk_eval_cx, op_to_const};
use super::eval_queries::{mk_eval_cx_to_read_const_val, op_to_const};
use super::machine::CompileTimeEvalContext;
use super::{ValTreeCreationError, ValTreeCreationResult, VALTREE_MAX_NODES};
use crate::const_eval::CanAccessMutGlobal;
@ -223,7 +223,7 @@ pub(crate) fn eval_to_valtree<'tcx>(
let const_alloc = tcx.eval_to_allocation_raw(param_env.and(cid))?;
// FIXME Need to provide a span to `eval_to_valtree`
let ecx = mk_eval_cx(
let ecx = mk_eval_cx_to_read_const_val(
tcx,
DUMMY_SP,
param_env,
@ -287,7 +287,8 @@ pub fn valtree_to_const_value<'tcx>(
}
}
ty::Ref(_, inner_ty, _) => {
let mut ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, CanAccessMutGlobal::No);
let mut ecx =
mk_eval_cx_to_read_const_val(tcx, DUMMY_SP, param_env, CanAccessMutGlobal::No);
let imm = valtree_to_ref(&mut ecx, valtree, *inner_ty);
let imm = ImmTy::from_immediate(imm, tcx.layout_of(param_env_ty).unwrap());
op_to_const(&ecx, &imm.into(), /* for diagnostics */ false)
@ -314,7 +315,8 @@ pub fn valtree_to_const_value<'tcx>(
bug!("could not find non-ZST field during in {layout:#?}");
}
let mut ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, CanAccessMutGlobal::No);
let mut ecx =
mk_eval_cx_to_read_const_val(tcx, DUMMY_SP, param_env, CanAccessMutGlobal::No);
// Need to create a place for this valtree.
let place = create_valtree_place(&mut ecx, layout, valtree);

View file

@ -249,7 +249,7 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> {
let secondary_errors = mem::take(&mut self.secondary_errors);
if self.error_emitted.is_none() {
for error in secondary_errors {
error.emit();
self.error_emitted = Some(error.emit());
}
} else {
assert!(self.tcx.dcx().has_errors().is_some());
@ -329,9 +329,7 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> {
fn check_static(&mut self, def_id: DefId, span: Span) {
if self.tcx.is_thread_local_static(def_id) {
self.tcx
.dcx()
.span_delayed_bug(span, "tls access is checked in `Rvalue::ThreadLocalRef`");
self.tcx.dcx().span_bug(span, "tls access is checked in `Rvalue::ThreadLocalRef`");
}
self.check_op_spanned(ops::StaticAccess, span)
}

View file

@ -93,6 +93,9 @@ pub struct FnCallNonConst<'tcx> {
}
impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> {
// FIXME: make this translatable
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)]
fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, _: Span) -> DiagnosticBuilder<'tcx> {
let FnCallNonConst { caller, callee, args, span, call_source, feature } = *self;
let ConstCx { tcx, param_env, .. } = *ccx;
@ -321,6 +324,8 @@ impl<'tcx> NonConstOp<'tcx> for FnCallUnstable {
.dcx()
.create_err(errors::UnstableConstFn { span, def_path: ccx.tcx.def_path_str(def_id) });
// FIXME: make this translatable
#[allow(rustc::untranslatable_diagnostic)]
if ccx.is_const_stable_const_fn() {
err.help("const-stable functions can only call other const-stable functions");
} else if ccx.tcx.sess.is_nightly_build() {
@ -591,6 +596,8 @@ impl<'tcx> NonConstOp<'tcx> for StaticAccess {
span,
format!("referencing statics in {}s is unstable", ccx.const_kind(),),
);
// FIXME: make this translatable
#[allow(rustc::untranslatable_diagnostic)]
err
.note("`static` and `const` variables can refer to other `const` variables. A `const` variable, however, cannot refer to a `static` variable.")
.help("to fix this, the value can be extracted to a `const` and then used.");

View file

@ -517,7 +517,7 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> {
fn visit_source_scope(&mut self, scope: SourceScope) {
if self.body.source_scopes.get(scope).is_none() {
self.tcx.dcx().span_delayed_bug(
self.tcx.dcx().span_bug(
self.body.span,
format!(
"broken MIR in {:?} ({}):\ninvalid source scope {:?}",

View file

@ -6,7 +6,7 @@ use rustc_middle::ty::layout::LayoutOf;
use rustc_span::symbol::Symbol;
use rustc_type_ir::Mutability;
use crate::const_eval::{mk_eval_cx, CanAccessMutGlobal, CompileTimeEvalContext};
use crate::const_eval::{mk_eval_cx_to_read_const_val, CanAccessMutGlobal, CompileTimeEvalContext};
use crate::interpret::*;
/// Allocate a `const core::panic::Location` with the provided filename and line/column numbers.
@ -57,7 +57,12 @@ pub(crate) fn const_caller_location_provider(
col: u32,
) -> mir::ConstValue<'_> {
trace!("const_caller_location: {}:{}:{}", file, line, col);
let mut ecx = mk_eval_cx(tcx.tcx, tcx.span, ty::ParamEnv::reveal_all(), CanAccessMutGlobal::No);
let mut ecx = mk_eval_cx_to_read_const_val(
tcx.tcx,
tcx.span,
ty::ParamEnv::reveal_all(),
CanAccessMutGlobal::No,
);
let loc_place = alloc_caller_location(&mut ecx, file, line, col);
if intern_const_alloc_recursive(&mut ecx, InternKind::Constant, &loc_place).is_err() {

View file

@ -144,16 +144,6 @@ pub const EXIT_FAILURE: i32 = 1;
pub const DEFAULT_BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\
?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md";
pub fn abort_on_err<T>(result: Result<T, ErrorGuaranteed>, sess: &Session) -> T {
match result {
Err(..) => {
sess.dcx().abort_if_errors();
panic!("error reported but abort_if_errors didn't abort???");
}
Ok(x) => x,
}
}
pub trait Callbacks {
/// Called before creating the compiler instance
fn config(&mut self, _config: &mut interface::Config) {}
@ -349,27 +339,33 @@ fn run_compiler(
},
};
callbacks.config(&mut config);
default_early_dcx.abort_if_errors();
drop(default_early_dcx);
callbacks.config(&mut config);
interface::run_compiler(config, |compiler| {
let sess = &compiler.sess;
let codegen_backend = &*compiler.codegen_backend;
// This is used for early exits unrelated to errors. E.g. when just
// printing some information without compiling, or exiting immediately
// after parsing, etc.
let early_exit = || {
if let Some(guar) = sess.dcx().has_errors() { Err(guar) } else { Ok(()) }
};
// This implements `-Whelp`. It should be handled very early, like
// `--help`/`-Zhelp`/`-Chelp`. This is the earliest it can run, because
// it must happen after lints are registered, during session creation.
if sess.opts.describe_lints {
describe_lints(sess);
return sess.compile_status();
return early_exit();
}
let early_dcx = EarlyDiagCtxt::new(sess.opts.error_format);
if print_crate_info(&early_dcx, codegen_backend, sess, has_input) == Compilation::Stop {
return sess.compile_status();
return early_exit();
}
if !has_input {
@ -378,16 +374,16 @@ fn run_compiler(
if !sess.opts.unstable_opts.ls.is_empty() {
list_metadata(&early_dcx, sess, &*codegen_backend.metadata_loader());
return sess.compile_status();
return early_exit();
}
if sess.opts.unstable_opts.link_only {
process_rlink(sess, compiler);
return sess.compile_status();
return early_exit();
}
let linker = compiler.enter(|queries| {
let early_exit = || sess.compile_status().map(|_| None);
let early_exit = || early_exit().map(|_| None);
queries.parse()?;
if let Some(ppm) = &sess.opts.pretty {
@ -659,10 +655,11 @@ fn process_rlink(sess: &Session, compiler: &interface::Compiler) {
};
}
};
let result = compiler.codegen_backend.link(sess, codegen_results, &outputs);
abort_on_err(result, sess);
if compiler.codegen_backend.link(sess, codegen_results, &outputs).is_err() {
FatalError.raise();
}
} else {
dcx.emit_fatal(RlinkNotAFile {})
dcx.emit_fatal(RlinkNotAFile {});
}
}

View file

@ -2,6 +2,7 @@
use rustc_ast as ast;
use rustc_ast_pretty::pprust as pprust_ast;
use rustc_errors::FatalError;
use rustc_hir as hir;
use rustc_hir_pretty as pprust_hir;
use rustc_middle::bug;
@ -18,7 +19,6 @@ use std::fmt::Write;
pub use self::PpMode::*;
pub use self::PpSourceMode::*;
use crate::abort_on_err;
struct AstNoAnn;
@ -243,7 +243,9 @@ impl<'tcx> PrintExtra<'tcx> {
pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
if ppm.needs_analysis() {
abort_on_err(ex.tcx().analysis(()), sess);
if ex.tcx().analysis(()).is_err() {
FatalError.raise();
}
}
let (src, src_name) = get_source(sess);
@ -334,7 +336,9 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
ThirTree => {
let tcx = ex.tcx();
let mut out = String::new();
abort_on_err(rustc_hir_analysis::check_crate(tcx), tcx.sess);
if rustc_hir_analysis::check_crate(tcx).is_err() {
FatalError.raise();
}
debug!("pretty printing THIR tree");
for did in tcx.hir().body_owners() {
let _ = writeln!(out, "{:?}:\n{}\n", did, tcx.thir_tree(did));
@ -344,7 +348,9 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
ThirFlat => {
let tcx = ex.tcx();
let mut out = String::new();
abort_on_err(rustc_hir_analysis::check_crate(tcx), tcx.sess);
if rustc_hir_analysis::check_crate(tcx).is_err() {
FatalError.raise();
}
debug!("pretty printing THIR flat");
for did in tcx.hir().body_owners() {
let _ = writeln!(out, "{:?}:\n{}\n", did, tcx.thir_flat(did));

View file

@ -1,18 +1,22 @@
use crate::snippet::Style;
use crate::{
CodeSuggestion, DiagnosticBuilder, DiagnosticMessage, EmissionGuarantee, ErrCode, Level,
MultiSpan, SubdiagnosticMessage, Substitution, SubstitutionPart, SuggestionStyle,
CodeSuggestion, DiagCtxt, DiagnosticMessage, ErrCode, ErrorGuaranteed, ExplicitBug, Level,
MultiSpan, StashKey, SubdiagnosticMessage, Substitution, SubstitutionPart, SuggestionStyle,
};
use rustc_data_structures::fx::FxIndexMap;
use rustc_error_messages::fluent_value_from_str_list_sep_by_and;
use rustc_error_messages::FluentValue;
use rustc_lint_defs::{Applicability, LintExpectationId};
use rustc_span::source_map::Spanned;
use rustc_span::symbol::Symbol;
use rustc_span::{Span, DUMMY_SP};
use std::borrow::Cow;
use std::fmt::{self, Debug};
use std::hash::{Hash, Hasher};
use std::panic::Location;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::panic;
use std::thread::panicking;
/// Error type for `Diagnostic`'s `suggestions` field, indicating that
/// `.disable_suggestions()` was called on the `Diagnostic`.
@ -39,6 +43,86 @@ pub enum DiagnosticArgValue {
StrListSepByAnd(Vec<Cow<'static, str>>),
}
/// Trait for types that `DiagnosticBuilder::emit` can return as a "guarantee"
/// (or "proof") token that the emission happened.
pub trait EmissionGuarantee: Sized {
/// This exists so that bugs and fatal errors can both result in `!` (an
/// abort) when emitted, but have different aborting behaviour.
type EmitResult = Self;
/// Implementation of `DiagnosticBuilder::emit`, fully controlled by each
/// `impl` of `EmissionGuarantee`, to make it impossible to create a value
/// of `Self::EmitResult` without actually performing the emission.
#[track_caller]
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult;
}
impl EmissionGuarantee for ErrorGuaranteed {
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult {
db.emit_producing_error_guaranteed()
}
}
impl EmissionGuarantee for () {
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult {
db.emit_producing_nothing();
}
}
/// Marker type which enables implementation of `create_bug` and `emit_bug` functions for
/// bug diagnostics.
#[derive(Copy, Clone)]
pub struct BugAbort;
impl EmissionGuarantee for BugAbort {
type EmitResult = !;
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult {
db.emit_producing_nothing();
panic::panic_any(ExplicitBug);
}
}
/// Marker type which enables implementation of `create_fatal` and `emit_fatal` functions for
/// fatal diagnostics.
#[derive(Copy, Clone)]
pub struct FatalAbort;
impl EmissionGuarantee for FatalAbort {
type EmitResult = !;
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult {
db.emit_producing_nothing();
crate::FatalError.raise()
}
}
impl EmissionGuarantee for rustc_span::fatal_error::FatalError {
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult {
db.emit_producing_nothing();
rustc_span::fatal_error::FatalError
}
}
/// Trait implemented by error types. This is rarely implemented manually. Instead, use
/// `#[derive(Diagnostic)]` -- see [rustc_macros::Diagnostic].
#[rustc_diagnostic_item = "IntoDiagnostic"]
pub trait IntoDiagnostic<'a, G: EmissionGuarantee = ErrorGuaranteed> {
/// Write out as a diagnostic out of `DiagCtxt`.
#[must_use]
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G>;
}
impl<'a, T, G> IntoDiagnostic<'a, G> for Spanned<T>
where
T: IntoDiagnostic<'a, G>,
G: EmissionGuarantee,
{
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> {
self.node.into_diagnostic(dcx, level).with_span(self.span)
}
}
/// Converts a value of a type into a `DiagnosticArg` (typically a field of an `IntoDiagnostic`
/// struct). Implemented as a custom trait rather than `From` so that it is implemented on the type
/// being converted rather than on `DiagnosticArgValue`, which enables types from other `rustc_*`
@ -71,17 +155,21 @@ where
Self: Sized,
{
/// Add a subdiagnostic to an existing diagnostic.
fn add_to_diagnostic(self, diag: &mut Diagnostic) {
fn add_to_diagnostic<G: EmissionGuarantee>(self, diag: &mut DiagnosticBuilder<'_, G>) {
self.add_to_diagnostic_with(diag, |_, m| m);
}
/// Add a subdiagnostic to an existing diagnostic where `f` is invoked on every message used
/// (to optionally perform eager translation).
fn add_to_diagnostic_with<F: SubdiagnosticMessageOp>(self, diag: &mut Diagnostic, f: F);
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self,
diag: &mut DiagnosticBuilder<'_, G>,
f: F,
);
}
pub trait SubdiagnosticMessageOp =
Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage;
pub trait SubdiagnosticMessageOp<G> =
Fn(&mut DiagnosticBuilder<'_, G>, SubdiagnosticMessage) -> SubdiagnosticMessage;
/// Trait implemented by lint types. This should not be implemented manually. Instead, use
/// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic].
@ -93,32 +181,6 @@ pub trait DecorateLint<'a, G: EmissionGuarantee> {
fn msg(&self) -> DiagnosticMessage;
}
#[must_use]
#[derive(Clone, Debug, Encodable, Decodable)]
pub struct Diagnostic {
// NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
// outside of what methods in this crate themselves allow.
pub(crate) level: Level,
pub messages: Vec<(DiagnosticMessage, Style)>,
pub code: Option<ErrCode>,
pub span: MultiSpan,
pub children: Vec<SubDiagnostic>,
pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
args: FxIndexMap<DiagnosticArgName, DiagnosticArgValue>,
/// This is not used for highlighting or rendering any error message. Rather, it can be used
/// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
/// `span` if there is one. Otherwise, it is `DUMMY_SP`.
pub sort_span: Span,
pub is_lint: Option<IsLint>,
/// With `-Ztrack_diagnostics` enabled,
/// we print where in rustc this error was emitted.
pub(crate) emitted_at: DiagnosticLocation,
}
#[derive(Clone, Debug, Encodable, Decodable)]
pub struct DiagnosticLocation {
file: Cow<'static, str>,
@ -129,7 +191,7 @@ pub struct DiagnosticLocation {
impl DiagnosticLocation {
#[track_caller]
fn caller() -> Self {
let loc = Location::caller();
let loc = panic::Location::caller();
DiagnosticLocation { file: loc.file().into(), line: loc.line(), col: loc.column() }
}
}
@ -148,15 +210,6 @@ pub struct IsLint {
has_future_breakage: bool,
}
/// A "sub"-diagnostic attached to a parent diagnostic.
/// For example, a note attached to an error.
#[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
pub struct SubDiagnostic {
pub level: Level,
pub messages: Vec<(DiagnosticMessage, Style)>,
pub span: MultiSpan,
}
#[derive(Debug, PartialEq, Eq)]
pub struct DiagnosticStyledString(pub Vec<StringPart>);
@ -206,6 +259,36 @@ impl StringPart {
}
}
/// The main part of a diagnostic. Note that `DiagnosticBuilder`, which wraps
/// this type, is used for most operations, and should be used instead whenever
/// possible. This type should only be used when `DiagnosticBuilder`'s lifetime
/// causes difficulties, e.g. when storing diagnostics within `DiagCtxt`.
#[must_use]
#[derive(Clone, Debug, Encodable, Decodable)]
pub struct Diagnostic {
// NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
// outside of what methods in this crate themselves allow.
pub(crate) level: Level,
pub messages: Vec<(DiagnosticMessage, Style)>,
pub code: Option<ErrCode>,
pub span: MultiSpan,
pub children: Vec<SubDiagnostic>,
pub suggestions: Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
args: FxIndexMap<DiagnosticArgName, DiagnosticArgValue>,
/// This is not used for highlighting or rendering any error message. Rather, it can be used
/// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
/// `span` if there is one. Otherwise, it is `DUMMY_SP`.
pub sort_span: Span,
pub is_lint: Option<IsLint>,
/// With `-Ztrack_diagnostics` enabled,
/// we print where in rustc this error was emitted.
pub(crate) emitted_at: DiagnosticLocation,
}
impl Diagnostic {
#[track_caller]
pub fn new<M: Into<DiagnosticMessage>>(level: Level, message: M) -> Self {
@ -289,6 +372,216 @@ impl Diagnostic {
}
}
// See comment on `DiagnosticBuilder::subdiagnostic_message_to_diagnostic_message`.
pub(crate) fn subdiagnostic_message_to_diagnostic_message(
&self,
attr: impl Into<SubdiagnosticMessage>,
) -> DiagnosticMessage {
let msg =
self.messages.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
msg.with_subdiagnostic_message(attr.into())
}
pub(crate) fn sub(
&mut self,
level: Level,
message: impl Into<SubdiagnosticMessage>,
span: MultiSpan,
) {
let sub = SubDiagnostic {
level,
messages: vec![(
self.subdiagnostic_message_to_diagnostic_message(message),
Style::NoStyle,
)],
span,
};
self.children.push(sub);
}
pub(crate) fn arg(&mut self, name: impl Into<DiagnosticArgName>, arg: impl IntoDiagnosticArg) {
self.args.insert(name.into(), arg.into_diagnostic_arg());
}
pub fn args(&self) -> impl Iterator<Item = DiagnosticArg<'_>> {
self.args.iter()
}
pub fn replace_args(&mut self, args: FxIndexMap<DiagnosticArgName, DiagnosticArgValue>) {
self.args = args;
}
/// Fields used for Hash, and PartialEq trait.
fn keys(
&self,
) -> (
&Level,
&[(DiagnosticMessage, Style)],
&Option<ErrCode>,
&MultiSpan,
&[SubDiagnostic],
&Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
Vec<(&DiagnosticArgName, &DiagnosticArgValue)>,
&Option<IsLint>,
) {
(
&self.level,
&self.messages,
&self.code,
&self.span,
&self.children,
&self.suggestions,
self.args().collect(),
// omit self.sort_span
&self.is_lint,
// omit self.emitted_at
)
}
}
impl Hash for Diagnostic {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
self.keys().hash(state);
}
}
impl PartialEq for Diagnostic {
fn eq(&self, other: &Self) -> bool {
self.keys() == other.keys()
}
}
/// A "sub"-diagnostic attached to a parent diagnostic.
/// For example, a note attached to an error.
#[derive(Clone, Debug, PartialEq, Hash, Encodable, Decodable)]
pub struct SubDiagnostic {
pub level: Level,
pub messages: Vec<(DiagnosticMessage, Style)>,
pub span: MultiSpan,
}
/// Used for emitting structured error messages and other diagnostic information.
/// Wraps a `Diagnostic`, adding some useful things.
/// - The `dcx` field, allowing it to (a) emit itself, and (b) do a drop check
/// that it has been emitted or cancelled.
/// - The `EmissionGuarantee`, which determines the type returned from `emit`.
///
/// Each constructed `DiagnosticBuilder` must be consumed by a function such as
/// `emit`, `cancel`, `delay_as_bug`, or `into_diagnostic`. A panic occurrs if a
/// `DiagnosticBuilder` is dropped without being consumed by one of these
/// functions.
///
/// If there is some state in a downstream crate you would like to
/// access in the methods of `DiagnosticBuilder` here, consider
/// extending `DiagCtxtFlags`.
#[must_use]
pub struct DiagnosticBuilder<'a, G: EmissionGuarantee = ErrorGuaranteed> {
pub dcx: &'a DiagCtxt,
/// Why the `Option`? It is always `Some` until the `DiagnosticBuilder` is
/// consumed via `emit`, `cancel`, etc. At that point it is consumed and
/// replaced with `None`. Then `drop` checks that it is `None`; if not, it
/// panics because a diagnostic was built but not used.
///
/// Why the Box? `Diagnostic` is a large type, and `DiagnosticBuilder` is
/// often used as a return value, especially within the frequently-used
/// `PResult` type. In theory, return value optimization (RVO) should avoid
/// unnecessary copying. In practice, it does not (at the time of writing).
diag: Option<Box<Diagnostic>>,
_marker: PhantomData<G>,
}
// Cloning a `DiagnosticBuilder` is a recipe for a diagnostic being emitted
// twice, which would be bad.
impl<G> !Clone for DiagnosticBuilder<'_, G> {}
rustc_data_structures::static_assert_size!(
DiagnosticBuilder<'_, ()>,
2 * std::mem::size_of::<usize>()
);
impl<G: EmissionGuarantee> Deref for DiagnosticBuilder<'_, G> {
type Target = Diagnostic;
fn deref(&self) -> &Diagnostic {
self.diag.as_ref().unwrap()
}
}
impl<G: EmissionGuarantee> DerefMut for DiagnosticBuilder<'_, G> {
fn deref_mut(&mut self) -> &mut Diagnostic {
self.diag.as_mut().unwrap()
}
}
impl<G: EmissionGuarantee> Debug for DiagnosticBuilder<'_, G> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.diag.fmt(f)
}
}
/// `DiagnosticBuilder` impls many `&mut self -> &mut Self` methods. Each one
/// modifies an existing diagnostic, either in a standalone fashion, e.g.
/// `err.code(code);`, or in a chained fashion to make multiple modifications,
/// e.g. `err.code(code).span(span);`.
///
/// This macro creates an equivalent `self -> Self` method, with a `with_`
/// prefix. This can be used in a chained fashion when making a new diagnostic,
/// e.g. `let err = struct_err(msg).with_code(code);`, or emitting a new
/// diagnostic, e.g. `struct_err(msg).with_code(code).emit();`.
///
/// Although the latter method can be used to modify an existing diagnostic,
/// e.g. `err = err.with_code(code);`, this should be avoided because the former
/// method gives shorter code, e.g. `err.code(code);`.
///
/// Note: the `with_` methods are added only when needed. If you want to use
/// one and it's not defined, feel free to add it.
///
/// Note: any doc comments must be within the `with_fn!` call.
macro_rules! with_fn {
{
$with_f:ident,
$(#[$attrs:meta])*
pub fn $f:ident(&mut $self:ident, $($name:ident: $ty:ty),* $(,)?) -> &mut Self {
$($body:tt)*
}
} => {
// The original function.
$(#[$attrs])*
#[doc = concat!("See [`DiagnosticBuilder::", stringify!($f), "()`].")]
pub fn $f(&mut $self, $($name: $ty),*) -> &mut Self {
$($body)*
}
// The `with_*` variant.
$(#[$attrs])*
#[doc = concat!("See [`DiagnosticBuilder::", stringify!($f), "()`].")]
pub fn $with_f(mut $self, $($name: $ty),*) -> Self {
$self.$f($($name),*);
$self
}
};
}
impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
#[rustc_lint_diagnostics]
#[track_caller]
pub fn new<M: Into<DiagnosticMessage>>(dcx: &'a DiagCtxt, level: Level, message: M) -> Self {
Self::new_diagnostic(dcx, Diagnostic::new(level, message))
}
/// Creates a new `DiagnosticBuilder` with an already constructed
/// diagnostic.
#[track_caller]
pub(crate) fn new_diagnostic(dcx: &'a DiagCtxt, diag: Diagnostic) -> Self {
debug!("Created new diagnostic");
Self { dcx, diag: Some(Box::new(diag)), _marker: PhantomData }
}
/// Delay emission of this diagnostic as a bug.
///
/// This can be useful in contexts where an error indicates a bug but
@ -309,6 +602,7 @@ impl Diagnostic {
self.level = Level::DelayedBug;
}
with_fn! { with_span_label,
/// Appends a labeled span to the diagnostic.
///
/// Labels are used to convey additional context for the diagnostic's primary span. They will
@ -323,10 +617,12 @@ impl Diagnostic {
/// primary.
#[rustc_lint_diagnostics]
pub fn span_label(&mut self, span: Span, label: impl Into<SubdiagnosticMessage>) -> &mut Self {
self.span.push_span_label(span, self.subdiagnostic_message_to_diagnostic_message(label));
let msg = self.subdiagnostic_message_to_diagnostic_message(label);
self.span.push_span_label(span, msg);
self
}
} }
with_fn! { with_span_labels,
/// Labels all the given spans with the provided label.
/// See [`Self::span_label()`] for more information.
pub fn span_labels(&mut self, spans: impl IntoIterator<Item = Span>, label: &str) -> &mut Self {
@ -334,7 +630,7 @@ impl Diagnostic {
self.span_label(span, label.to_string());
}
self
}
} }
pub fn replace_span_with(&mut self, after: Span, keep_label: bool) -> &mut Self {
let before = self.span.clone();
@ -412,39 +708,40 @@ impl Diagnostic {
self
}
with_fn! { with_note,
/// Add a note attached to this diagnostic.
#[rustc_lint_diagnostics]
pub fn note(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
self.sub(Level::Note, msg, MultiSpan::new());
self
}
} }
fn highlighted_note(&mut self, msg: Vec<StringPart>) -> &mut Self {
self.sub_with_highlights(Level::Note, msg, MultiSpan::new());
self
}
/// Prints the span with a note above it.
/// This is like [`Diagnostic::note()`], but it gets its own span.
/// This is like [`DiagnosticBuilder::note()`], but it's only printed once.
pub fn note_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
self.sub(Level::OnceNote, msg, MultiSpan::new());
self
}
with_fn! { with_span_note,
/// Prints the span with a note above it.
/// This is like [`Diagnostic::note()`], but it gets its own span.
/// This is like [`DiagnosticBuilder::note()`], but it gets its own span.
#[rustc_lint_diagnostics]
pub fn span_note<S: Into<MultiSpan>>(
pub fn span_note(
&mut self,
sp: S,
sp: impl Into<MultiSpan>,
msg: impl Into<SubdiagnosticMessage>,
) -> &mut Self {
self.sub(Level::Note, msg, sp.into());
self
}
} }
/// Prints the span with a note above it.
/// This is like [`Diagnostic::note()`], but it gets its own span.
/// This is like [`DiagnosticBuilder::note_once()`], but it gets its own span.
pub fn span_note_once<S: Into<MultiSpan>>(
&mut self,
sp: S,
@ -454,15 +751,16 @@ impl Diagnostic {
self
}
with_fn! { with_warn,
/// Add a warning attached to this diagnostic.
#[rustc_lint_diagnostics]
pub fn warn(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
self.sub(Level::Warning, msg, MultiSpan::new());
self
}
} }
/// Prints the span with a warning above it.
/// This is like [`Diagnostic::warn()`], but it gets its own span.
/// This is like [`DiagnosticBuilder::warn()`], but it gets its own span.
#[rustc_lint_diagnostics]
pub fn span_warn<S: Into<MultiSpan>>(
&mut self,
@ -473,15 +771,15 @@ impl Diagnostic {
self
}
with_fn! { with_help,
/// Add a help message attached to this diagnostic.
#[rustc_lint_diagnostics]
pub fn help(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
self.sub(Level::Help, msg, MultiSpan::new());
self
}
} }
/// Prints the span with a help above it.
/// This is like [`Diagnostic::help()`], but it gets its own span.
/// This is like [`DiagnosticBuilder::help()`], but it's only printed once.
pub fn help_once(&mut self, msg: impl Into<SubdiagnosticMessage>) -> &mut Self {
self.sub(Level::OnceHelp, msg, MultiSpan::new());
self
@ -494,7 +792,7 @@ impl Diagnostic {
}
/// Prints the span with some help above it.
/// This is like [`Diagnostic::help()`], but it gets its own span.
/// This is like [`DiagnosticBuilder::help()`], but it gets its own span.
#[rustc_lint_diagnostics]
pub fn span_help<S: Into<MultiSpan>>(
&mut self,
@ -531,6 +829,7 @@ impl Diagnostic {
}
}
with_fn! { with_multipart_suggestion,
/// Show a suggestion that has multiple parts to it.
/// In other words, multiple changes need to be applied as part of this suggestion.
pub fn multipart_suggestion(
@ -545,7 +844,7 @@ impl Diagnostic {
applicability,
SuggestionStyle::ShowCode,
)
}
} }
/// Show a suggestion that has multiple parts to it, always as it's own subdiagnostic.
/// In other words, multiple changes need to be applied as part of this suggestion.
@ -562,7 +861,8 @@ impl Diagnostic {
SuggestionStyle::ShowAlways,
)
}
/// [`Diagnostic::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
/// [`DiagnosticBuilder::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
pub fn multipart_suggestion_with_style(
&mut self,
msg: impl Into<SubdiagnosticMessage>,
@ -619,6 +919,7 @@ impl Diagnostic {
)
}
with_fn! { with_span_suggestion,
/// Prints out a message with a suggested edit of the code.
///
/// In case of short messages and a simple suggestion, rustc displays it as a label:
@ -651,9 +952,9 @@ impl Diagnostic {
SuggestionStyle::ShowCode,
);
self
}
} }
/// [`Diagnostic::span_suggestion()`] but you can set the [`SuggestionStyle`].
/// [`DiagnosticBuilder::span_suggestion()`] but you can set the [`SuggestionStyle`].
pub fn span_suggestion_with_style(
&mut self,
sp: Span,
@ -677,6 +978,7 @@ impl Diagnostic {
self
}
with_fn! { with_span_suggestion_verbose,
/// Always show the suggested change.
pub fn span_suggestion_verbose(
&mut self,
@ -693,10 +995,11 @@ impl Diagnostic {
SuggestionStyle::ShowAlways,
);
self
}
} }
with_fn! { with_span_suggestions,
/// Prints out a message with multiple suggested edits of the code.
/// See also [`Diagnostic::span_suggestion()`].
/// See also [`DiagnosticBuilder::span_suggestion()`].
pub fn span_suggestions(
&mut self,
sp: Span,
@ -711,9 +1014,8 @@ impl Diagnostic {
applicability,
SuggestionStyle::ShowCode,
)
}
} }
/// [`Diagnostic::span_suggestions()`] but you can set the [`SuggestionStyle`].
pub fn span_suggestions_with_style(
&mut self,
sp: Span,
@ -743,7 +1045,7 @@ impl Diagnostic {
/// Prints out a message with multiple suggested edits of the code, where each edit consists of
/// multiple parts.
/// See also [`Diagnostic::multipart_suggestion()`].
/// See also [`DiagnosticBuilder::multipart_suggestion()`].
pub fn multipart_suggestions(
&mut self,
msg: impl Into<SubdiagnosticMessage>,
@ -785,6 +1087,7 @@ impl Diagnostic {
self
}
with_fn! { with_span_suggestion_short,
/// Prints out a message with a suggested edit of the code. If the suggestion is presented
/// inline, it will only show the message and not the suggestion.
///
@ -804,7 +1107,7 @@ impl Diagnostic {
SuggestionStyle::HideCodeInline,
);
self
}
} }
/// Prints out a message for a suggestion without showing the suggested code.
///
@ -829,6 +1132,7 @@ impl Diagnostic {
self
}
with_fn! { with_tool_only_span_suggestion,
/// Adds a suggestion to the JSON output that will not be shown in the CLI.
///
/// This is intended to be used for suggestions that are *very* obvious in what the changes
@ -849,7 +1153,7 @@ impl Diagnostic {
SuggestionStyle::CompletelyHidden,
);
self
}
} }
/// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
/// [rustc_macros::Subdiagnostic]). Performs eager translation of any translatable messages
@ -868,45 +1172,45 @@ impl Diagnostic {
self
}
pub fn span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self {
with_fn! { with_span,
/// Add a span.
pub fn span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self {
self.span = sp.into();
if let Some(span) = self.span.primary_span() {
self.sort_span = span;
}
self
}
} }
pub fn is_lint(&mut self, name: String, has_future_breakage: bool) -> &mut Self {
self.is_lint = Some(IsLint { name, has_future_breakage });
self
}
with_fn! { with_code,
/// Add an error code.
pub fn code(&mut self, code: ErrCode) -> &mut Self {
self.code = Some(code);
self
}
} }
with_fn! { with_primary_message,
/// Add a primary message.
pub fn primary_message(&mut self, msg: impl Into<DiagnosticMessage>) -> &mut Self {
self.messages[0] = (msg.into(), Style::NoStyle);
self
}
pub fn args(&self) -> impl Iterator<Item = DiagnosticArg<'_>> {
self.args.iter()
}
} }
with_fn! { with_arg,
/// Add an argument.
pub fn arg(
&mut self,
name: impl Into<DiagnosticArgName>,
arg: impl IntoDiagnosticArg,
) -> &mut Self {
self.args.insert(name.into(), arg.into_diagnostic_arg());
self.deref_mut().arg(name, arg);
self
}
pub fn replace_args(&mut self, args: FxIndexMap<DiagnosticArgName, DiagnosticArgValue>) {
self.args = args;
}
} }
/// Helper function that takes a `SubdiagnosticMessage` and returns a `DiagnosticMessage` by
/// combining it with the primary message of the diagnostic (if translatable, otherwise it just
@ -915,9 +1219,7 @@ impl Diagnostic {
&self,
attr: impl Into<SubdiagnosticMessage>,
) -> DiagnosticMessage {
let msg =
self.messages.iter().map(|(msg, _)| msg).next().expect("diagnostic with no messages");
msg.with_subdiagnostic_message(attr.into())
self.deref().subdiagnostic_message_to_diagnostic_message(attr)
}
/// Convenience function for internal use, clients should use one of the
@ -925,15 +1227,7 @@ impl Diagnostic {
///
/// Used by `proc_macro_server` for implementing `server::Diagnostic`.
pub fn sub(&mut self, level: Level, message: impl Into<SubdiagnosticMessage>, span: MultiSpan) {
let sub = SubDiagnostic {
level,
messages: vec![(
self.subdiagnostic_message_to_diagnostic_message(message),
Style::NoStyle,
)],
span,
};
self.children.push(sub);
self.deref_mut().sub(level, message, span);
}
/// Convenience function for internal use, clients should use one of the
@ -947,45 +1241,111 @@ impl Diagnostic {
self.children.push(sub);
}
/// Fields used for Hash, and PartialEq trait
fn keys(
&self,
) -> (
&Level,
&[(DiagnosticMessage, Style)],
&Option<ErrCode>,
&MultiSpan,
&[SubDiagnostic],
&Result<Vec<CodeSuggestion>, SuggestionsDisabled>,
Vec<(&DiagnosticArgName, &DiagnosticArgValue)>,
&Option<IsLint>,
) {
(
&self.level,
&self.messages,
&self.code,
&self.span,
&self.children,
&self.suggestions,
self.args().collect(),
// omit self.sort_span
&self.is_lint,
// omit self.emitted_at
)
/// Takes the diagnostic. For use by methods that consume the
/// DiagnosticBuilder: `emit`, `cancel`, etc. Afterwards, `drop` is the
/// only code that will be run on `self`.
fn take_diag(&mut self) -> Diagnostic {
Box::into_inner(self.diag.take().unwrap())
}
/// Most `emit_producing_guarantee` functions use this as a starting point.
fn emit_producing_nothing(mut self) {
let diag = self.take_diag();
self.dcx.emit_diagnostic(diag);
}
/// `ErrorGuaranteed::emit_producing_guarantee` uses this.
fn emit_producing_error_guaranteed(mut self) -> ErrorGuaranteed {
let diag = self.take_diag();
// The only error levels that produce `ErrorGuaranteed` are
// `Error` and `DelayedBug`. But `DelayedBug` should never occur here
// because delayed bugs have their level changed to `Bug` when they are
// actually printed, so they produce an ICE.
//
// (Also, even though `level` isn't `pub`, the whole `Diagnostic` could
// be overwritten with a new one thanks to `DerefMut`. So this assert
// protects against that, too.)
assert!(
matches!(diag.level, Level::Error | Level::DelayedBug),
"invalid diagnostic level ({:?})",
diag.level,
);
let guar = self.dcx.emit_diagnostic(diag);
guar.unwrap()
}
/// Emit and consume the diagnostic.
#[track_caller]
pub fn emit(self) -> G::EmitResult {
G::emit_producing_guarantee(self)
}
/// Emit the diagnostic unless `delay` is true,
/// in which case the emission will be delayed as a bug.
///
/// See `emit` and `delay_as_bug` for details.
#[track_caller]
pub fn emit_unless(mut self, delay: bool) -> G::EmitResult {
if delay {
self.downgrade_to_delayed_bug();
}
self.emit()
}
/// Cancel and consume the diagnostic. (A diagnostic must either be emitted or
/// cancelled or it will panic when dropped).
pub fn cancel(mut self) {
self.diag = None;
drop(self);
}
/// Stashes diagnostic for possible later improvement in a different,
/// later stage of the compiler. The diagnostic can be accessed with
/// the provided `span` and `key` through [`DiagCtxt::steal_diagnostic()`].
pub fn stash(mut self, span: Span, key: StashKey) {
self.dcx.stash_diagnostic(span, key, self.take_diag());
}
/// Delay emission of this diagnostic as a bug.
///
/// This can be useful in contexts where an error indicates a bug but
/// typically this only happens when other compilation errors have already
/// happened. In those cases this can be used to defer emission of this
/// diagnostic as a bug in the compiler only if no other errors have been
/// emitted.
///
/// In the meantime, though, callsites are required to deal with the "bug"
/// locally in whichever way makes the most sense.
#[track_caller]
pub fn delay_as_bug(mut self) -> G::EmitResult {
self.downgrade_to_delayed_bug();
self.emit()
}
}
impl Hash for Diagnostic {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
self.keys().hash(state);
/// Destructor bomb: every `DiagnosticBuilder` must be consumed (emitted,
/// cancelled, etc.) or we emit a bug.
impl<G: EmissionGuarantee> Drop for DiagnosticBuilder<'_, G> {
fn drop(&mut self) {
match self.diag.take() {
Some(diag) if !panicking() => {
self.dcx.emit_diagnostic(Diagnostic::new(
Level::Bug,
DiagnosticMessage::from("the following error was constructed but not emitted"),
));
self.dcx.emit_diagnostic(*diag);
panic!("error was constructed but not emitted");
}
_ => {}
}
}
}
impl PartialEq for Diagnostic {
fn eq(&self, other: &Self) -> bool {
self.keys() == other.keys()
}
#[macro_export]
macro_rules! struct_span_code_err {
($dcx:expr, $span:expr, $code:expr, $($message:tt)*) => ({
$dcx.struct_span_err($span, format!($($message)*)).with_code($code)
})
}

View file

@ -1,441 +0,0 @@
use crate::diagnostic::IntoDiagnosticArg;
use crate::{DiagCtxt, Level, MultiSpan, StashKey};
use crate::{
Diagnostic, DiagnosticMessage, DiagnosticStyledString, ErrCode, ErrorGuaranteed, ExplicitBug,
SubdiagnosticMessage,
};
use rustc_lint_defs::Applicability;
use rustc_span::source_map::Spanned;
use rustc_span::Span;
use std::borrow::Cow;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::panic;
use std::thread::panicking;
/// Trait implemented by error types. This is rarely implemented manually. Instead, use
/// `#[derive(Diagnostic)]` -- see [rustc_macros::Diagnostic].
#[rustc_diagnostic_item = "IntoDiagnostic"]
pub trait IntoDiagnostic<'a, G: EmissionGuarantee = ErrorGuaranteed> {
/// Write out as a diagnostic out of `DiagCtxt`.
#[must_use]
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G>;
}
impl<'a, T, G> IntoDiagnostic<'a, G> for Spanned<T>
where
T: IntoDiagnostic<'a, G>,
G: EmissionGuarantee,
{
fn into_diagnostic(self, dcx: &'a DiagCtxt, level: Level) -> DiagnosticBuilder<'a, G> {
self.node.into_diagnostic(dcx, level).with_span(self.span)
}
}
/// Used for emitting structured error messages and other diagnostic information.
/// Each constructed `DiagnosticBuilder` must be consumed by a function such as
/// `emit`, `cancel`, `delay_as_bug`, or `into_diagnostic`. A panic occurrs if a
/// `DiagnosticBuilder` is dropped without being consumed by one of these
/// functions.
///
/// If there is some state in a downstream crate you would like to
/// access in the methods of `DiagnosticBuilder` here, consider
/// extending `DiagCtxtFlags`.
#[must_use]
pub struct DiagnosticBuilder<'a, G: EmissionGuarantee = ErrorGuaranteed> {
pub dcx: &'a DiagCtxt,
/// Why the `Option`? It is always `Some` until the `DiagnosticBuilder` is
/// consumed via `emit`, `cancel`, etc. At that point it is consumed and
/// replaced with `None`. Then `drop` checks that it is `None`; if not, it
/// panics because a diagnostic was built but not used.
///
/// Why the Box? `Diagnostic` is a large type, and `DiagnosticBuilder` is
/// often used as a return value, especially within the frequently-used
/// `PResult` type. In theory, return value optimization (RVO) should avoid
/// unnecessary copying. In practice, it does not (at the time of writing).
diag: Option<Box<Diagnostic>>,
_marker: PhantomData<G>,
}
// Cloning a `DiagnosticBuilder` is a recipe for a diagnostic being emitted
// twice, which would be bad.
impl<G> !Clone for DiagnosticBuilder<'_, G> {}
rustc_data_structures::static_assert_size!(
DiagnosticBuilder<'_, ()>,
2 * std::mem::size_of::<usize>()
);
/// Trait for types that `DiagnosticBuilder::emit` can return as a "guarantee"
/// (or "proof") token that the emission happened.
pub trait EmissionGuarantee: Sized {
/// This exists so that bugs and fatal errors can both result in `!` (an
/// abort) when emitted, but have different aborting behaviour.
type EmitResult = Self;
/// Implementation of `DiagnosticBuilder::emit`, fully controlled by each
/// `impl` of `EmissionGuarantee`, to make it impossible to create a value
/// of `Self::EmitResult` without actually performing the emission.
#[track_caller]
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult;
}
impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
/// Takes the diagnostic. For use by methods that consume the
/// DiagnosticBuilder: `emit`, `cancel`, etc. Afterwards, `drop` is the
/// only code that will be run on `self`.
fn take_diag(&mut self) -> Diagnostic {
Box::into_inner(self.diag.take().unwrap())
}
/// Most `emit_producing_guarantee` functions use this as a starting point.
fn emit_producing_nothing(mut self) {
let diag = self.take_diag();
self.dcx.emit_diagnostic(diag);
}
/// `ErrorGuaranteed::emit_producing_guarantee` uses this.
fn emit_producing_error_guaranteed(mut self) -> ErrorGuaranteed {
let diag = self.take_diag();
// The only error levels that produce `ErrorGuaranteed` are
// `Error` and `DelayedBug`. But `DelayedBug` should never occur here
// because delayed bugs have their level changed to `Bug` when they are
// actually printed, so they produce an ICE.
//
// (Also, even though `level` isn't `pub`, the whole `Diagnostic` could
// be overwritten with a new one thanks to `DerefMut`. So this assert
// protects against that, too.)
assert!(
matches!(diag.level, Level::Error | Level::DelayedBug),
"invalid diagnostic level ({:?})",
diag.level,
);
let guar = self.dcx.emit_diagnostic(diag);
guar.unwrap()
}
}
impl EmissionGuarantee for ErrorGuaranteed {
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult {
db.emit_producing_error_guaranteed()
}
}
impl EmissionGuarantee for () {
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult {
db.emit_producing_nothing();
}
}
/// Marker type which enables implementation of `create_bug` and `emit_bug` functions for
/// bug diagnostics.
#[derive(Copy, Clone)]
pub struct BugAbort;
impl EmissionGuarantee for BugAbort {
type EmitResult = !;
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult {
db.emit_producing_nothing();
panic::panic_any(ExplicitBug);
}
}
/// Marker type which enables implementation of `create_fatal` and `emit_fatal` functions for
/// fatal diagnostics.
#[derive(Copy, Clone)]
pub struct FatalAbort;
impl EmissionGuarantee for FatalAbort {
type EmitResult = !;
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult {
db.emit_producing_nothing();
crate::FatalError.raise()
}
}
impl EmissionGuarantee for rustc_span::fatal_error::FatalError {
fn emit_producing_guarantee(db: DiagnosticBuilder<'_, Self>) -> Self::EmitResult {
db.emit_producing_nothing();
rustc_span::fatal_error::FatalError
}
}
/// `DiagnosticBuilder` impls `DerefMut`, which allows access to the fields and
/// methods of the embedded `Diagnostic`. However, that doesn't allow method
/// chaining at the `DiagnosticBuilder` level. Each use of this macro defines
/// two builder methods at that level, both of which wrap the equivalent method
/// in `Diagnostic`.
/// - A `&mut self -> &mut Self` method, with the same name as the underlying
/// `Diagnostic` method. It is mostly to modify existing diagnostics, either
/// in a standalone fashion, e.g. `err.code(code)`, or in a chained fashion
/// to make multiple modifications, e.g. `err.code(code).span(span)`.
/// - A `self -> Self` method, which has a `with_` prefix added.
/// It is mostly used in a chained fashion when producing a new diagnostic,
/// e.g. `let err = struct_err(msg).with_code(code)`, or when emitting a new
/// diagnostic , e.g. `struct_err(msg).with_code(code).emit()`.
///
/// Although the latter method can be used to modify an existing diagnostic,
/// e.g. `err = err.with_code(code)`, this should be avoided because the former
/// method gives shorter code, e.g. `err.code(code)`.
macro_rules! forward {
(
($f:ident, $with_f:ident)($($name:ident: $ty:ty),* $(,)?)
) => {
#[doc = concat!("See [`Diagnostic::", stringify!($f), "()`].")]
pub fn $f(&mut self, $($name: $ty),*) -> &mut Self {
self.diag.as_mut().unwrap().$f($($name),*);
self
}
#[doc = concat!("See [`Diagnostic::", stringify!($f), "()`].")]
pub fn $with_f(mut self, $($name: $ty),*) -> Self {
self.diag.as_mut().unwrap().$f($($name),*);
self
}
};
}
impl<G: EmissionGuarantee> Deref for DiagnosticBuilder<'_, G> {
type Target = Diagnostic;
fn deref(&self) -> &Diagnostic {
self.diag.as_ref().unwrap()
}
}
impl<G: EmissionGuarantee> DerefMut for DiagnosticBuilder<'_, G> {
fn deref_mut(&mut self) -> &mut Diagnostic {
self.diag.as_mut().unwrap()
}
}
impl<'a, G: EmissionGuarantee> DiagnosticBuilder<'a, G> {
#[rustc_lint_diagnostics]
#[track_caller]
pub fn new<M: Into<DiagnosticMessage>>(dcx: &'a DiagCtxt, level: Level, message: M) -> Self {
Self::new_diagnostic(dcx, Diagnostic::new(level, message))
}
/// Creates a new `DiagnosticBuilder` with an already constructed
/// diagnostic.
#[track_caller]
pub(crate) fn new_diagnostic(dcx: &'a DiagCtxt, diag: Diagnostic) -> Self {
debug!("Created new diagnostic");
Self { dcx, diag: Some(Box::new(diag)), _marker: PhantomData }
}
/// Emit and consume the diagnostic.
#[track_caller]
pub fn emit(self) -> G::EmitResult {
G::emit_producing_guarantee(self)
}
/// Emit the diagnostic unless `delay` is true,
/// in which case the emission will be delayed as a bug.
///
/// See `emit` and `delay_as_bug` for details.
#[track_caller]
pub fn emit_unless(mut self, delay: bool) -> G::EmitResult {
if delay {
self.downgrade_to_delayed_bug();
}
self.emit()
}
/// Cancel and consume the diagnostic. (A diagnostic must either be emitted or
/// cancelled or it will panic when dropped).
pub fn cancel(mut self) {
self.diag = None;
drop(self);
}
/// Stashes diagnostic for possible later improvement in a different,
/// later stage of the compiler. The diagnostic can be accessed with
/// the provided `span` and `key` through [`DiagCtxt::steal_diagnostic()`].
pub fn stash(mut self, span: Span, key: StashKey) {
self.dcx.stash_diagnostic(span, key, self.take_diag());
}
/// Delay emission of this diagnostic as a bug.
///
/// This can be useful in contexts where an error indicates a bug but
/// typically this only happens when other compilation errors have already
/// happened. In those cases this can be used to defer emission of this
/// diagnostic as a bug in the compiler only if no other errors have been
/// emitted.
///
/// In the meantime, though, callsites are required to deal with the "bug"
/// locally in whichever way makes the most sense.
#[track_caller]
pub fn delay_as_bug(mut self) -> G::EmitResult {
self.downgrade_to_delayed_bug();
self.emit()
}
forward!((span_label, with_span_label)(
span: Span,
label: impl Into<SubdiagnosticMessage>,
));
forward!((span_labels, with_span_labels)(
spans: impl IntoIterator<Item = Span>,
label: &str,
));
forward!((note_expected_found, with_note_expected_found)(
expected_label: &dyn fmt::Display,
expected: DiagnosticStyledString,
found_label: &dyn fmt::Display,
found: DiagnosticStyledString,
));
forward!((note_expected_found_extra, with_note_expected_found_extra)(
expected_label: &dyn fmt::Display,
expected: DiagnosticStyledString,
found_label: &dyn fmt::Display,
found: DiagnosticStyledString,
expected_extra: &dyn fmt::Display,
found_extra: &dyn fmt::Display,
));
forward!((note, with_note)(
msg: impl Into<SubdiagnosticMessage>,
));
forward!((note_once, with_note_once)(
msg: impl Into<SubdiagnosticMessage>,
));
forward!((span_note, with_span_note)(
sp: impl Into<MultiSpan>,
msg: impl Into<SubdiagnosticMessage>,
));
forward!((span_note_once, with_span_note_once)(
sp: impl Into<MultiSpan>,
msg: impl Into<SubdiagnosticMessage>,
));
forward!((warn, with_warn)(
msg: impl Into<SubdiagnosticMessage>,
));
forward!((span_warn, with_span_warn)(
sp: impl Into<MultiSpan>,
msg: impl Into<SubdiagnosticMessage>,
));
forward!((help, with_help)(
msg: impl Into<SubdiagnosticMessage>,
));
forward!((help_once, with_help_once)(
msg: impl Into<SubdiagnosticMessage>,
));
forward!((span_help, with_span_help_once)(
sp: impl Into<MultiSpan>,
msg: impl Into<SubdiagnosticMessage>,
));
forward!((multipart_suggestion, with_multipart_suggestion)(
msg: impl Into<SubdiagnosticMessage>,
suggestion: Vec<(Span, String)>,
applicability: Applicability,
));
forward!((multipart_suggestion_verbose, with_multipart_suggestion_verbose)(
msg: impl Into<SubdiagnosticMessage>,
suggestion: Vec<(Span, String)>,
applicability: Applicability,
));
forward!((tool_only_multipart_suggestion, with_tool_only_multipart_suggestion)(
msg: impl Into<SubdiagnosticMessage>,
suggestion: Vec<(Span, String)>,
applicability: Applicability,
));
forward!((span_suggestion, with_span_suggestion)(
sp: Span,
msg: impl Into<SubdiagnosticMessage>,
suggestion: impl ToString,
applicability: Applicability,
));
forward!((span_suggestions, with_span_suggestions)(
sp: Span,
msg: impl Into<SubdiagnosticMessage>,
suggestions: impl IntoIterator<Item = String>,
applicability: Applicability,
));
forward!((multipart_suggestions, with_multipart_suggestions)(
msg: impl Into<SubdiagnosticMessage>,
suggestions: impl IntoIterator<Item = Vec<(Span, String)>>,
applicability: Applicability,
));
forward!((span_suggestion_short, with_span_suggestion_short)(
sp: Span,
msg: impl Into<SubdiagnosticMessage>,
suggestion: impl ToString,
applicability: Applicability,
));
forward!((span_suggestion_verbose, with_span_suggestion_verbose)(
sp: Span,
msg: impl Into<SubdiagnosticMessage>,
suggestion: impl ToString,
applicability: Applicability,
));
forward!((span_suggestion_hidden, with_span_suggestion_hidden)(
sp: Span,
msg: impl Into<SubdiagnosticMessage>,
suggestion: impl ToString,
applicability: Applicability,
));
forward!((tool_only_span_suggestion, with_tool_only_span_suggestion)(
sp: Span,
msg: impl Into<SubdiagnosticMessage>,
suggestion: impl ToString,
applicability: Applicability,
));
forward!((primary_message, with_primary_message)(
msg: impl Into<DiagnosticMessage>,
));
forward!((span, with_span)(
sp: impl Into<MultiSpan>,
));
forward!((is_lint, with_is_lint)(
name: String, has_future_breakage: bool,
));
forward!((code, with_code)(
code: ErrCode,
));
forward!((arg, with_arg)(
name: impl Into<Cow<'static, str>>, arg: impl IntoDiagnosticArg,
));
forward!((subdiagnostic, with_subdiagnostic)(
dcx: &DiagCtxt,
subdiagnostic: impl crate::AddToDiagnostic,
));
}
impl<G: EmissionGuarantee> Debug for DiagnosticBuilder<'_, G> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.diag.fmt(f)
}
}
/// Destructor bomb: every `DiagnosticBuilder` must be consumed (emitted,
/// cancelled, etc.) or we emit a bug.
impl<G: EmissionGuarantee> Drop for DiagnosticBuilder<'_, G> {
fn drop(&mut self) {
match self.diag.take() {
Some(diag) if !panicking() => {
self.dcx.emit_diagnostic(Diagnostic::new(
Level::Bug,
DiagnosticMessage::from("the following error was constructed but not emitted"),
));
self.dcx.emit_diagnostic(*diag);
panic!("error was constructed but not emitted");
}
_ => {}
}
}
}
#[macro_export]
macro_rules! struct_span_code_err {
($dcx:expr, $span:expr, $code:expr, $($message:tt)*) => ({
$dcx.struct_span_err($span, format!($($message)*)).with_code($code)
})
}

View file

@ -299,7 +299,11 @@ pub struct SingleLabelManySpans {
pub label: &'static str,
}
impl AddToDiagnostic for SingleLabelManySpans {
fn add_to_diagnostic_with<F: SubdiagnosticMessageOp>(self, diag: &mut crate::Diagnostic, _: F) {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self,
diag: &mut DiagnosticBuilder<'_, G>,
_: F,
) {
diag.span_labels(self.spans, self.label);
}
}
@ -312,23 +316,6 @@ pub struct ExpectedLifetimeParameter {
pub count: usize,
}
#[derive(Subdiagnostic)]
#[note(errors_delayed_at_with_newline)]
pub struct DelayedAtWithNewline {
#[primary_span]
pub span: Span,
pub emitted_at: DiagnosticLocation,
pub note: Backtrace,
}
#[derive(Subdiagnostic)]
#[note(errors_delayed_at_without_newline)]
pub struct DelayedAtWithoutNewline {
#[primary_span]
pub span: Span,
pub emitted_at: DiagnosticLocation,
pub note: Backtrace,
}
impl IntoDiagnosticArg for DiagnosticLocation {
fn into_diagnostic_arg(self) -> DiagnosticArgValue {
DiagnosticArgValue::Str(Cow::from(self.to_string()))
@ -341,13 +328,6 @@ impl IntoDiagnosticArg for Backtrace {
}
}
#[derive(Subdiagnostic)]
#[note(errors_invalid_flushed_delayed_diagnostic_level)]
pub struct InvalidFlushedDelayedDiagnosticLevel {
#[primary_span]
pub span: Span,
pub level: Level,
}
impl IntoDiagnosticArg for Level {
fn into_diagnostic_arg(self) -> DiagnosticArgValue {
DiagnosticArgValue::Str(Cow::from(self.to_string()))

View file

@ -599,7 +599,7 @@ impl Emitter for SilentEmitter {
fn emit_diagnostic(&mut self, mut diag: Diagnostic) {
if diag.level == Level::Fatal {
diag.note(self.fatal_note.clone());
diag.sub(Level::Note, self.fatal_note.clone(), MultiSpan::new());
self.fatal_dcx.emit_diagnostic(diag);
}
}

View file

@ -37,16 +37,13 @@ extern crate self as rustc_errors;
pub use codes::*;
pub use diagnostic::{
AddToDiagnostic, DecorateLint, Diagnostic, DiagnosticArg, DiagnosticArgName,
DiagnosticArgValue, DiagnosticStyledString, IntoDiagnosticArg, StringPart, SubDiagnostic,
SubdiagnosticMessageOp,
};
pub use diagnostic_builder::{
BugAbort, DiagnosticBuilder, EmissionGuarantee, FatalAbort, IntoDiagnostic,
AddToDiagnostic, BugAbort, DecorateLint, Diagnostic, DiagnosticArg, DiagnosticArgName,
DiagnosticArgValue, DiagnosticBuilder, DiagnosticStyledString, EmissionGuarantee, FatalAbort,
IntoDiagnostic, IntoDiagnosticArg, StringPart, SubDiagnostic, SubdiagnosticMessageOp,
};
pub use diagnostic_impls::{
DiagnosticArgFromDisplay, DiagnosticSymbolList, ExpectedLifetimeParameter,
IndicateAnonymousLifetime, InvalidFlushedDelayedDiagnosticLevel, SingleLabelManySpans,
IndicateAnonymousLifetime, SingleLabelManySpans,
};
pub use emitter::ColorConfig;
pub use rustc_error_messages::{
@ -62,7 +59,6 @@ pub use snippet::Style;
// See https://github.com/rust-lang/rust/pull/115393.
pub use termcolor::{Color, ColorSpec, WriteColor};
use crate::diagnostic_impls::{DelayedAtWithNewline, DelayedAtWithoutNewline};
use emitter::{is_case_difference, DynEmitter, Emitter, HumanEmitter};
use registry::Registry;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
@ -88,7 +84,6 @@ use Level::*;
pub mod annotate_snippet_emitter_writer;
pub mod codes;
mod diagnostic;
mod diagnostic_builder;
mod diagnostic_impls;
pub mod emitter;
pub mod error;
@ -476,9 +471,10 @@ struct DiagCtxtInner {
emitted_diagnostics: FxHashSet<Hash128>,
/// Stashed diagnostics emitted in one stage of the compiler that may be
/// stolen by other stages (e.g. to improve them and add more information).
/// The stashed diagnostics count towards the total error count.
/// When `.abort_if_errors()` is called, these are also emitted.
/// stolen and emitted/cancelled by other stages (e.g. to improve them and
/// add more information). All stashed diagnostics must be emitted with
/// `emit_stashed_diagnostics` by the time the `DiagCtxtInner` is dropped,
/// otherwise an assertion failure will occur.
stashed_diagnostics: FxIndexMap<(Span, StashKey), Diagnostic>,
future_breakage_diagnostics: Vec<Diagnostic>,
@ -563,7 +559,9 @@ pub struct DiagCtxtFlags {
impl Drop for DiagCtxtInner {
fn drop(&mut self) {
self.emit_stashed_diagnostics();
// Any stashed diagnostics should have been handled by
// `emit_stashed_diagnostics` by now.
assert!(self.stashed_diagnostics.is_empty());
if self.err_guars.is_empty() {
self.flush_delayed()
@ -755,17 +753,24 @@ impl DiagCtxt {
}
/// Emit all stashed diagnostics.
pub fn emit_stashed_diagnostics(&self) {
pub fn emit_stashed_diagnostics(&self) -> Option<ErrorGuaranteed> {
self.inner.borrow_mut().emit_stashed_diagnostics()
}
/// This excludes lint errors, delayed bugs, and stashed errors.
/// This excludes lint errors, delayed bugs and stashed errors.
#[inline]
pub fn err_count(&self) -> usize {
pub fn err_count_excluding_lint_errs(&self) -> usize {
self.inner.borrow().err_guars.len()
}
/// This excludes normal errors, lint errors and delayed bugs. Unless
/// This excludes delayed bugs and stashed errors.
#[inline]
pub fn err_count(&self) -> usize {
let inner = self.inner.borrow();
inner.err_guars.len() + inner.lint_err_guars.len()
}
/// This excludes normal errors, lint errors, and delayed bugs. Unless
/// absolutely necessary, avoid using this. It's dubious because stashed
/// errors can later be cancelled, so the presence of a stashed error at
/// some point of time doesn't guarantee anything -- there are no
@ -774,27 +779,29 @@ impl DiagCtxt {
self.inner.borrow().stashed_err_count
}
/// This excludes lint errors, delayed bugs, and stashed errors.
/// This excludes lint errors, delayed bugs, and stashed errors. Unless
/// absolutely necessary, prefer `has_errors` to this method.
pub fn has_errors_excluding_lint_errors(&self) -> Option<ErrorGuaranteed> {
self.inner.borrow().has_errors_excluding_lint_errors()
}
/// This excludes delayed bugs and stashed errors.
pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
self.inner.borrow().has_errors()
}
/// This excludes delayed bugs and stashed errors. Unless absolutely
/// necessary, prefer `has_errors` to this method.
pub fn has_errors_or_lint_errors(&self) -> Option<ErrorGuaranteed> {
self.inner.borrow().has_errors_or_lint_errors()
}
/// This excludes stashed errors. Unless absolutely necessary, prefer
/// `has_errors` or `has_errors_or_lint_errors` to this method.
pub fn has_errors_or_lint_errors_or_delayed_bugs(&self) -> Option<ErrorGuaranteed> {
self.inner.borrow().has_errors_or_lint_errors_or_delayed_bugs()
/// `has_errors` to this method.
pub fn has_errors_or_delayed_bugs(&self) -> Option<ErrorGuaranteed> {
self.inner.borrow().has_errors_or_delayed_bugs()
}
pub fn print_error_count(&self, registry: &Registry) {
let mut inner = self.inner.borrow_mut();
inner.emit_stashed_diagnostics();
// Any stashed diagnostics should have been handled by
// `emit_stashed_diagnostics` by now.
assert!(inner.stashed_diagnostics.is_empty());
if inner.treat_err_as_bug() {
return;
@ -869,10 +876,12 @@ impl DiagCtxt {
}
}
/// This excludes delayed bugs and stashed errors. Used for early aborts
/// after errors occurred -- e.g. because continuing in the face of errors is
/// likely to lead to bad results, such as spurious/uninteresting
/// additional errors -- when returning an error `Result` is difficult.
pub fn abort_if_errors(&self) {
let mut inner = self.inner.borrow_mut();
inner.emit_stashed_diagnostics();
if !inner.err_guars.is_empty() {
if self.has_errors().is_some() {
FatalError.raise();
}
}
@ -1273,10 +1282,10 @@ impl DiagCtxt {
// `DiagCtxtInner::foo`.
impl DiagCtxtInner {
/// Emit all stashed diagnostics.
fn emit_stashed_diagnostics(&mut self) {
fn emit_stashed_diagnostics(&mut self) -> Option<ErrorGuaranteed> {
let mut guar = None;
let has_errors = !self.err_guars.is_empty();
for (_, diag) in std::mem::take(&mut self.stashed_diagnostics).into_iter() {
// Decrement the count tracking the stash; emitting will increment it.
if diag.is_error() {
if diag.is_lint.is_none() {
self.stashed_err_count -= 1;
@ -1289,8 +1298,9 @@ impl DiagCtxtInner {
continue;
}
}
self.emit_diagnostic(diag);
guar = guar.or(self.emit_diagnostic(diag));
}
guar
}
// Return value is only `Some` if the level is `Error` or `DelayedBug`.
@ -1334,7 +1344,7 @@ impl DiagCtxtInner {
DelayedBug => {
// If we have already emitted at least one error, we don't need
// to record the delayed bug, because it'll never be used.
return if let Some(guar) = self.has_errors_or_lint_errors() {
return if let Some(guar) = self.has_errors() {
Some(guar)
} else {
let backtrace = std::backtrace::Backtrace::capture();
@ -1395,9 +1405,8 @@ impl DiagCtxtInner {
};
diagnostic.children.extract_if(already_emitted_sub).for_each(|_| {});
if already_emitted {
diagnostic.note(
"duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`",
);
let msg = "duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`";
diagnostic.sub(Level::Note, msg, MultiSpan::new());
}
if is_error {
@ -1451,17 +1460,16 @@ impl DiagCtxtInner {
.is_some_and(|c| self.err_guars.len() + self.lint_err_guars.len() + 1 >= c.get())
}
fn has_errors(&self) -> Option<ErrorGuaranteed> {
fn has_errors_excluding_lint_errors(&self) -> Option<ErrorGuaranteed> {
self.err_guars.get(0).copied()
}
fn has_errors_or_lint_errors(&self) -> Option<ErrorGuaranteed> {
self.has_errors().or_else(|| self.lint_err_guars.get(0).copied())
fn has_errors(&self) -> Option<ErrorGuaranteed> {
self.has_errors_excluding_lint_errors().or_else(|| self.lint_err_guars.get(0).copied())
}
fn has_errors_or_lint_errors_or_delayed_bugs(&self) -> Option<ErrorGuaranteed> {
self.has_errors_or_lint_errors()
.or_else(|| self.delayed_bugs.get(0).map(|(_, guar)| guar).copied())
fn has_errors_or_delayed_bugs(&self) -> Option<ErrorGuaranteed> {
self.has_errors().or_else(|| self.delayed_bugs.get(0).map(|(_, guar)| guar).copied())
}
/// Translate `message` eagerly with `args` to `SubdiagnosticMessage::Eager`.
@ -1483,7 +1491,22 @@ impl DiagCtxtInner {
self.emitter.translate_message(&message, &args).map_err(Report::new).unwrap().to_string()
}
fn eagerly_translate_for_subdiag(
&self,
diag: &Diagnostic,
msg: impl Into<SubdiagnosticMessage>,
) -> SubdiagnosticMessage {
let args = diag.args();
let msg = diag.subdiagnostic_message_to_diagnostic_message(msg);
self.eagerly_translate(msg, args)
}
fn flush_delayed(&mut self) {
// Stashed diagnostics must be emitted before delayed bugs are flushed.
// Otherwise, we might ICE prematurely when errors would have
// eventually happened.
assert!(self.stashed_diagnostics.is_empty());
if self.delayed_bugs.is_empty() {
return;
}
@ -1527,17 +1550,14 @@ impl DiagCtxtInner {
if bug.level != DelayedBug {
// NOTE(eddyb) not panicking here because we're already producing
// an ICE, and the more information the merrier.
let subdiag = InvalidFlushedDelayedDiagnosticLevel {
span: bug.span.primary_span().unwrap(),
level: bug.level,
};
// FIXME: Cannot use `Diagnostic::subdiagnostic` which takes `DiagCtxt`, but it
// just uses `DiagCtxtInner` functions.
subdiag.add_to_diagnostic_with(&mut bug, |diag, msg| {
let args = diag.args();
let msg = diag.subdiagnostic_message_to_diagnostic_message(msg);
self.eagerly_translate(msg, args)
});
//
// We are at the `Diagnostic`/`DiagCtxtInner` level rather than
// the usual `DiagnosticBuilder`/`DiagCtxt` level, so we must
// augment `bug` in a lower-level fashion.
bug.arg("level", bug.level);
let msg = crate::fluent_generated::errors_invalid_flushed_delayed_diagnostic_level;
let msg = self.eagerly_translate_for_subdiag(&bug, msg); // after the `arg` call
bug.sub(Level::Note, msg, bug.span.primary_span().unwrap().into());
}
bug.level = Bug;
@ -1571,39 +1591,22 @@ impl DelayedDiagnostic {
DelayedDiagnostic { inner: diagnostic, note: backtrace }
}
fn decorate(mut self, dcx: &DiagCtxtInner) -> Diagnostic {
// FIXME: Cannot use `Diagnostic::subdiagnostic` which takes `DiagCtxt`, but it
// just uses `DiagCtxtInner` functions.
let subdiag_with = |diag: &mut Diagnostic, msg| {
let args = diag.args();
let msg = diag.subdiagnostic_message_to_diagnostic_message(msg);
dcx.eagerly_translate(msg, args)
};
match self.note.status() {
BacktraceStatus::Captured => {
let inner = &self.inner;
let subdiag = DelayedAtWithNewline {
span: inner.span.primary_span().unwrap_or(DUMMY_SP),
emitted_at: inner.emitted_at.clone(),
note: self.note,
};
subdiag.add_to_diagnostic_with(&mut self.inner, subdiag_with);
}
fn decorate(self, dcx: &DiagCtxtInner) -> Diagnostic {
// We are at the `Diagnostic`/`DiagCtxtInner` level rather than the
// usual `DiagnosticBuilder`/`DiagCtxt` level, so we must construct
// `diag` in a lower-level fashion.
let mut diag = self.inner;
let msg = match self.note.status() {
BacktraceStatus::Captured => crate::fluent_generated::errors_delayed_at_with_newline,
// Avoid the needless newline when no backtrace has been captured,
// the display impl should just be a single line.
_ => {
let inner = &self.inner;
let subdiag = DelayedAtWithoutNewline {
span: inner.span.primary_span().unwrap_or(DUMMY_SP),
emitted_at: inner.emitted_at.clone(),
note: self.note,
};
subdiag.add_to_diagnostic_with(&mut self.inner, subdiag_with);
}
}
self.inner
_ => crate::fluent_generated::errors_delayed_at_without_newline,
};
diag.arg("emitted_at", diag.emitted_at.clone());
diag.arg("note", self.note);
let msg = dcx.eagerly_translate_for_subdiag(&diag, msg); // after the `arg` calls
diag.sub(Level::Note, msg, diag.span.primary_span().unwrap_or(DUMMY_SP).into());
diag
}
}
@ -1745,9 +1748,9 @@ impl Level {
}
// FIXME(eddyb) this doesn't belong here AFAICT, should be moved to callsite.
pub fn add_elided_lifetime_in_path_suggestion<E: EmissionGuarantee>(
pub fn add_elided_lifetime_in_path_suggestion<G: EmissionGuarantee>(
source_map: &SourceMap,
diag: &mut DiagnosticBuilder<'_, E>,
diag: &mut DiagnosticBuilder<'_, G>,
n: usize,
path_span: Span,
incl_angl_brckt: bool,

View file

@ -22,6 +22,10 @@ expand_collapse_debuginfo_illegal =
expand_count_repetition_misplaced =
`count` can not be placed inside the inner-most repetition
expand_custom_attribute_panicked =
custom attribute panicked
.help = message: {$message}
expand_duplicate_matcher_binding = duplicate matcher binding
.label = duplicate binding
.label2 = previous binding
@ -115,6 +119,10 @@ expand_only_one_argument =
expand_only_one_word =
must only be one word
expand_proc_macro_derive_panicked =
proc-macro derive panicked
.help = message: {$message}
expand_proc_macro_derive_tokens =
proc-macro derive produced unparsable tokens

View file

@ -1176,6 +1176,8 @@ impl<'a> ExtCtxt<'a> {
for (span, notes) in self.expansions.iter() {
let mut db = self.dcx().create_note(errors::TraceMacro { span: *span });
for note in notes {
// FIXME: make this translatable
#[allow(rustc::untranslatable_diagnostic)]
db.note(note.clone());
}
db.emit();

View file

@ -384,6 +384,7 @@ impl<'a> StripUnconfigured<'a> {
);
if attr.is_doc_comment() {
#[allow(rustc::untranslatable_diagnostic)]
err.help("`///` is for documentation comments. For a plain comment, use `//`.");
}

View file

@ -392,6 +392,36 @@ pub(crate) struct ProcMacroPanickedHelp {
pub message: String,
}
#[derive(Diagnostic)]
#[diag(expand_proc_macro_derive_panicked)]
pub(crate) struct ProcMacroDerivePanicked {
#[primary_span]
pub span: Span,
#[subdiagnostic]
pub message: Option<ProcMacroDerivePanickedHelp>,
}
#[derive(Subdiagnostic)]
#[help(expand_help)]
pub(crate) struct ProcMacroDerivePanickedHelp {
pub message: String,
}
#[derive(Diagnostic)]
#[diag(expand_custom_attribute_panicked)]
pub(crate) struct CustomAttributePanicked {
#[primary_span]
pub span: Span,
#[subdiagnostic]
pub message: Option<CustomAttributePanickedHelp>,
}
#[derive(Subdiagnostic)]
#[help(expand_help)]
pub(crate) struct CustomAttributePanickedHelp {
pub message: String,
}
#[derive(Diagnostic)]
#[diag(expand_proc_macro_derive_tokens)]
pub struct ProcMacroDeriveTokens {

View file

@ -7,7 +7,7 @@ use crate::mbe::{
use rustc_ast::token::{self, Token, TokenKind};
use rustc_ast::tokenstream::TokenStream;
use rustc_ast_pretty::pprust;
use rustc_errors::{Applicability, DiagCtxt, Diagnostic, DiagnosticBuilder, DiagnosticMessage};
use rustc_errors::{Applicability, DiagCtxt, DiagnosticBuilder, DiagnosticMessage};
use rustc_parse::parser::{Parser, Recovery};
use rustc_span::source_map::SourceMap;
use rustc_span::symbol::Ident;
@ -285,7 +285,11 @@ pub(super) fn emit_frag_parse_err(
e.emit();
}
pub(crate) fn annotate_err_with_kind(err: &mut Diagnostic, kind: AstFragmentKind, span: Span) {
pub(crate) fn annotate_err_with_kind(
err: &mut DiagnosticBuilder<'_>,
kind: AstFragmentKind,
span: Span,
) {
match kind {
AstFragmentKind::Ty => {
err.span_label(span, "this macro call doesn't expand to a type");
@ -313,7 +317,7 @@ enum ExplainDocComment {
pub(super) fn annotate_doc_comment(
dcx: &DiagCtxt,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
sm: &SourceMap,
span: Span,
) {

View file

@ -93,11 +93,12 @@ impl base::AttrProcMacro for AttrProcMacro {
let server = proc_macro_server::Rustc::new(ecx);
self.client.run(&strategy, server, annotation, annotated, proc_macro_backtrace).map_err(
|e| {
let mut err = ecx.dcx().struct_span_err(span, "custom attribute panicked");
if let Some(s) = e.as_str() {
err.help(format!("message: {s}"));
}
err.emit()
ecx.dcx().emit_err(errors::CustomAttributePanicked {
span,
message: e.as_str().map(|message| errors::CustomAttributePanickedHelp {
message: message.into(),
}),
})
},
)
}
@ -146,11 +147,14 @@ impl MultiItemModifier for DeriveProcMacro {
match self.client.run(&strategy, server, input, proc_macro_backtrace) {
Ok(stream) => stream,
Err(e) => {
let mut err = ecx.dcx().struct_span_err(span, "proc-macro derive panicked");
if let Some(s) = e.as_str() {
err.help(format!("message: {s}"));
}
err.emit();
ecx.dcx().emit_err({
errors::ProcMacroDerivePanicked {
span,
message: e.as_str().map(|message| {
errors::ProcMacroDerivePanickedHelp { message: message.into() }
}),
}
});
return ExpandResult::Ready(vec![]);
}
}

View file

@ -10,7 +10,7 @@ use rustc_ast::util::literal::escape_byte_str_symbol;
use rustc_ast_pretty::pprust;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::Lrc;
use rustc_errors::{ErrorGuaranteed, MultiSpan, PResult};
use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed, MultiSpan, PResult};
use rustc_parse::lexer::nfc_normalize;
use rustc_parse::parse_stream_from_source_str;
use rustc_session::parse::ParseSess;
@ -509,13 +509,14 @@ impl server::FreeFunctions for Rustc<'_, '_> {
}
fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) {
let mut diag =
rustc_errors::Diagnostic::new(diagnostic.level.to_internal(), diagnostic.message);
let message = rustc_errors::DiagnosticMessage::from(diagnostic.message);
let mut diag: DiagnosticBuilder<'_, rustc_errors::ErrorGuaranteed> =
DiagnosticBuilder::new(&self.sess().dcx, diagnostic.level.to_internal(), message);
diag.span(MultiSpan::from_spans(diagnostic.spans));
for child in diagnostic.children {
diag.sub(child.level.to_internal(), child.message, MultiSpan::from_spans(child.spans));
}
self.sess().dcx.emit_diagnostic(diag);
diag.emit();
}
}

View file

@ -71,14 +71,21 @@ impl hir::Pat<'_> {
/// Call `f` on every "binding" in a pattern, e.g., on `a` in
/// `match foo() { Some(a) => (), None => () }`.
///
/// When encountering an or-pattern `p_0 | ... | p_n` only `p_0` will be visited.
/// When encountering an or-pattern `p_0 | ... | p_n` only the first non-never pattern will be
/// visited. If they're all never patterns we visit nothing, which is ok since a never pattern
/// cannot have bindings.
pub fn each_binding_or_first(
&self,
f: &mut impl FnMut(hir::BindingAnnotation, HirId, Span, Ident),
) {
self.walk(|p| match &p.kind {
PatKind::Or(ps) => {
ps[0].each_binding_or_first(f);
for p in *ps {
if !p.is_never_pattern() {
p.each_binding_or_first(f);
break;
}
}
false
}
PatKind::Binding(bm, _, ident, _) => {

View file

@ -454,9 +454,9 @@ impl<'tcx> dyn AstConv<'tcx> + '_ {
// for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
// for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
let late_bound_in_projection_ty =
tcx.collect_constrained_late_bound_regions(&projection_ty);
tcx.collect_constrained_late_bound_regions(projection_ty);
let late_bound_in_term =
tcx.collect_referenced_late_bound_regions(&trait_ref.rebind(term));
tcx.collect_referenced_late_bound_regions(trait_ref.rebind(term));
debug!(?late_bound_in_projection_ty);
debug!(?late_bound_in_term);

View file

@ -9,7 +9,7 @@ use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
use rustc_data_structures::sorted_map::SortedMap;
use rustc_data_structures::unord::UnordMap;
use rustc_errors::{
codes::*, pluralize, struct_span_code_err, Applicability, Diagnostic, ErrorGuaranteed,
codes::*, pluralize, struct_span_code_err, Applicability, DiagnosticBuilder, ErrorGuaranteed,
};
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId};
@ -371,7 +371,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
// FIXME(fmease): Heavily adapted from `rustc_hir_typeck::method::suggest`. Deduplicate.
fn note_ambiguous_inherent_assoc_type(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
candidates: Vec<DefId>,
span: Span,
) {
@ -429,7 +429,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
let tcx = self.tcx();
let adt_did = self_ty.ty_adt_def().map(|def| def.did());
let add_def_label = |err: &mut Diagnostic| {
let add_def_label = |err: &mut DiagnosticBuilder<'_>| {
if let Some(did) = adt_did {
err.span_label(
tcx.def_span(did),

View file

@ -6,7 +6,7 @@ use crate::astconv::{
use crate::structured_errors::{GenericArgsInfo, StructuredDiagnostic, WrongNumberOfGenericArgs};
use rustc_ast::ast::ParamKindOrd;
use rustc_errors::{
codes::*, struct_span_code_err, Applicability, Diagnostic, ErrorGuaranteed, MultiSpan,
codes::*, struct_span_code_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, MultiSpan,
};
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
@ -47,7 +47,7 @@ fn generic_arg_mismatch_err(
}
}
let add_braces_suggestion = |arg: &GenericArg<'_>, err: &mut Diagnostic| {
let add_braces_suggestion = |arg: &GenericArg<'_>, err: &mut DiagnosticBuilder<'_>| {
let suggestions = vec![
(arg.span().shrink_to_lo(), String::from("{ ")),
(arg.span().shrink_to_hi(), String::from(" }")),

View file

@ -1,5 +1,5 @@
use rustc_ast::TraitObjectSyntax;
use rustc_errors::{codes::*, Diagnostic, StashKey};
use rustc_errors::{codes::*, DiagnosticBuilder, EmissionGuarantee, StashKey};
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
use rustc_lint_defs::{builtin::BARE_TRAIT_OBJECTS, Applicability};
@ -10,10 +10,10 @@ use super::AstConv;
impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
/// Make sure that we are in the condition to suggest the blanket implementation.
pub(super) fn maybe_lint_blanket_trait_impl(
pub(super) fn maybe_lint_blanket_trait_impl<G: EmissionGuarantee>(
&self,
self_ty: &hir::Ty<'_>,
diag: &mut Diagnostic,
diag: &mut DiagnosticBuilder<'_, G>,
) {
let tcx = self.tcx();
let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id;
@ -75,7 +75,11 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
}
/// Make sure that we are in the condition to suggest `impl Trait`.
fn maybe_lint_impl_trait(&self, self_ty: &hir::Ty<'_>, diag: &mut Diagnostic) -> bool {
fn maybe_lint_impl_trait(
&self,
self_ty: &hir::Ty<'_>,
diag: &mut DiagnosticBuilder<'_>,
) -> bool {
let tcx = self.tcx();
let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id;
let (sig, generics, owner) = match tcx.hir_node_by_def_id(parent_id) {

View file

@ -18,8 +18,8 @@ use crate::require_c_abi_if_c_variadic;
use rustc_ast::TraitObjectSyntax;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_errors::{
codes::*, struct_span_code_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed,
FatalError, MultiSpan,
codes::*, struct_span_code_err, Applicability, DiagnosticBuilder, ErrorGuaranteed, FatalError,
MultiSpan,
};
use rustc_hir as hir;
use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
@ -1237,8 +1237,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
// trait reference.
let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) else {
// A cycle error occurred, most likely.
let guar = tcx.dcx().span_delayed_bug(span, "expected cycle error");
return Err(guar);
tcx.dcx().span_bug(span, "expected cycle error");
};
self.one_bound_for_assoc_item(
@ -1425,17 +1424,16 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
vec![]
};
let (impl_, (assoc_item, def_scope)) =
crate::traits::project::with_replaced_escaping_bound_vars(
infcx,
&mut universes,
self_ty,
|self_ty| {
self.select_inherent_assoc_type_candidates(
infcx, name, span, self_ty, param_env, candidates,
)
},
)?;
let (impl_, (assoc_item, def_scope)) = crate::traits::with_replaced_escaping_bound_vars(
infcx,
&mut universes,
self_ty,
|self_ty| {
self.select_inherent_assoc_type_candidates(
infcx, name, span, self_ty, param_env, candidates,
)
},
)?;
self.check_assoc_ty(assoc_item, name, def_scope, block, span);
@ -1725,7 +1723,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
pub fn prohibit_generics<'a>(
&self,
segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
extend: impl Fn(&mut Diagnostic),
extend: impl Fn(&mut DiagnosticBuilder<'_>),
) -> bool {
let args = segments.clone().flat_map(|segment| segment.args().args);
@ -2679,9 +2677,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
// for<'a> fn(&'a String) -> &'a str <-- 'a is ok
let inputs = bare_fn_ty.inputs();
let late_bound_in_args =
tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
let output = bare_fn_ty.output();
let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
struct_span_code_err!(

View file

@ -257,8 +257,7 @@ fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) {
fn check_opaque(tcx: TyCtxt<'_>, def_id: LocalDefId) {
let item = tcx.hir().expect_item(def_id);
let hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) = item.kind else {
tcx.dcx().span_delayed_bug(item.span, "expected opaque item");
return;
tcx.dcx().span_bug(item.span, "expected opaque item");
};
// HACK(jynelson): trying to infer the type of `impl trait` breaks documenting
@ -382,10 +381,10 @@ fn check_opaque_meets_bounds<'tcx>(
Ok(()) => {}
Err(ty_err) => {
let ty_err = ty_err.to_string(tcx);
return Err(tcx.dcx().span_delayed_bug(
tcx.dcx().span_bug(
span,
format!("could not unify `{hidden_ty}` with revealed type:\n{ty_err}"),
));
);
}
}
@ -1248,7 +1247,7 @@ fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {
fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) {
// Helper closure to reduce duplicate code. This gets called everytime we detect a duplicate.
// Here `idx` refers to the order of which the discriminant appears, and its index in `vs`
let report = |dis: Discr<'tcx>, idx, err: &mut Diagnostic| {
let report = |dis: Discr<'tcx>, idx, err: &mut DiagnosticBuilder<'_>| {
let var = adt.variant(idx); // HIR for the duplicate discriminant
let (span, display_discr) = match var.discr {
ty::VariantDiscr::Explicit(discr_def_id) => {

View file

@ -734,11 +734,12 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
remapped_types.insert(def_id, ty::EarlyBinder::bind(ty));
}
Err(err) => {
let reported = tcx.dcx().span_delayed_bug(
return_span,
format!("could not fully resolve: {ty} => {err:?}"),
);
remapped_types.insert(def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, reported)));
// This code path is not reached in any tests, but may be
// reachable. If this is triggered, it should be converted to
// `span_delayed_bug` and the triggering case turned into a
// test.
tcx.dcx()
.span_bug(return_span, format!("could not fully resolve: {ty} => {err:?}"));
}
}
}
@ -917,7 +918,13 @@ impl<'tcx> ty::FallibleTypeFolder<TyCtxt<'tcx>> for RemapHiddenTyRegions<'tcx> {
.with_note(format!("hidden type inferred to be `{}`", self.ty))
.emit()
}
_ => self.tcx.dcx().delayed_bug("should've been able to remap region"),
_ => {
// This code path is not reached in any tests, but may be
// reachable. If this is triggered, it should be converted
// to `delayed_bug` and the triggering case turned into a
// test.
self.tcx.dcx().bug("should've been able to remap region");
}
};
return Err(guar);
};
@ -1276,9 +1283,10 @@ fn compare_number_of_generics<'tcx>(
// inheriting the generics from will also have mismatched arguments, and
// we'll report an error for that instead. Delay a bug for safety, though.
if trait_.is_impl_trait_in_trait() {
return Err(tcx.dcx().delayed_bug(
"errors comparing numbers of generics of trait/impl functions were not emitted",
));
// FIXME: no tests trigger this. If you find example code that does
// trigger this, please add it to the test suite.
tcx.dcx()
.bug("errors comparing numbers of generics of trait/impl functions were not emitted");
}
let matchings = [

View file

@ -154,8 +154,10 @@ pub(super) fn check_refining_return_position_impl_trait_in_trait<'tcx>(
trait_m_sig.inputs_and_output,
));
if !ocx.select_all_or_error().is_empty() {
tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (selection)");
return;
// This code path is not reached in any tests, but may be reachable. If
// this is triggered, it should be converted to `delayed_bug` and the
// triggering case turned into a test.
tcx.dcx().bug("encountered errors when checking RPITIT refinement (selection)");
}
let outlives_env = OutlivesEnvironment::with_bounds(
param_env,
@ -163,13 +165,17 @@ pub(super) fn check_refining_return_position_impl_trait_in_trait<'tcx>(
);
let errors = infcx.resolve_regions(&outlives_env);
if !errors.is_empty() {
tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (regions)");
return;
// This code path is not reached in any tests, but may be reachable. If
// this is triggered, it should be converted to `delayed_bug` and the
// triggering case turned into a test.
tcx.dcx().bug("encountered errors when checking RPITIT refinement (regions)");
}
// Resolve any lifetime variables that may have been introduced during normalization.
let Ok((trait_bounds, impl_bounds)) = infcx.fully_resolve((trait_bounds, impl_bounds)) else {
tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (resolution)");
return;
// This code path is not reached in any tests, but may be reachable. If
// this is triggered, it should be converted to `delayed_bug` and the
// triggering case turned into a test.
tcx.dcx().bug("encountered errors when checking RPITIT refinement (resolution)");
};
// For quicker lookup, use an `IndexSet` (we don't use one earlier because

View file

@ -123,7 +123,12 @@ pub fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -
| sym::variant_count
| sym::is_val_statically_known
| sym::ptr_mask
| sym::debug_assertions => hir::Unsafety::Normal,
| sym::debug_assertions
| sym::fadd_algebraic
| sym::fsub_algebraic
| sym::fmul_algebraic
| sym::fdiv_algebraic
| sym::frem_algebraic => hir::Unsafety::Normal,
_ => hir::Unsafety::Unsafe,
};
@ -405,6 +410,11 @@ pub fn check_intrinsic_type(
sym::fadd_fast | sym::fsub_fast | sym::fmul_fast | sym::fdiv_fast | sym::frem_fast => {
(1, 0, vec![param(0), param(0)], param(0))
}
sym::fadd_algebraic
| sym::fsub_algebraic
| sym::fmul_algebraic
| sym::fdiv_algebraic
| sym::frem_algebraic => (1, 0, vec![param(0), param(0)], param(0)),
sym::float_to_int_unchecked => (2, 0, vec![param(0)], param(1)),
sym::assume => (0, 1, vec![tcx.types.bool], Ty::new_unit(tcx)),

View file

@ -78,7 +78,7 @@ use std::num::NonZero;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_errors::ErrorGuaranteed;
use rustc_errors::{pluralize, struct_span_code_err, Diagnostic, DiagnosticBuilder};
use rustc_errors::{pluralize, struct_span_code_err, DiagnosticBuilder};
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::intravisit::Visitor;
use rustc_index::bit_set::BitSet;

View file

@ -1087,14 +1087,8 @@ fn check_type_defn<'tcx>(
packed && {
let ty = tcx.type_of(variant.tail().did).instantiate_identity();
let ty = tcx.erase_regions(ty);
if ty.has_infer() {
tcx.dcx()
.span_delayed_bug(item.span, format!("inference variables in {ty:?}"));
// Just treat unresolved type expression as if it needs drop.
true
} else {
ty.needs_drop(tcx, tcx.param_env(item.owner_id))
}
assert!(!ty.has_infer());
ty.needs_drop(tcx, tcx.param_env(item.owner_id))
}
};
// All fields (except for possibly the last) should be sized.

View file

@ -144,7 +144,7 @@ impl<'tcx> InherentCollect<'tcx> {
let id = id.owner_id.def_id;
let item_span = self.tcx.def_span(id);
let self_ty = self.tcx.type_of(id).instantiate_identity();
let self_ty = peel_off_weak_aliases(self.tcx, self_ty);
let self_ty = self.tcx.peel_off_weak_alias_tys(self_ty);
match *self_ty.kind() {
ty::Adt(def, _) => self.check_def_id(id, self_ty, def.did()),
ty::Foreign(did) => self.check_def_id(id, self_ty, did),
@ -186,30 +186,3 @@ impl<'tcx> InherentCollect<'tcx> {
}
}
}
/// Peel off all weak alias types in this type until there are none left.
///
/// <div class="warning">
///
/// This assumes that `ty` gets normalized later and that any overflows occurring
/// during said normalization get reported.
///
/// </div>
fn peel_off_weak_aliases<'tcx>(tcx: TyCtxt<'tcx>, mut ty: Ty<'tcx>) -> Ty<'tcx> {
let ty::Alias(ty::Weak, _) = ty.kind() else { return ty };
let limit = tcx.recursion_limit();
let mut depth = 0;
while let ty::Alias(ty::Weak, alias) = ty.kind() {
if !limit.value_within_limit(depth) {
let guar = tcx.dcx().delayed_bug("overflow expanding weak alias type");
return Ty::new_error(tcx, guar);
}
ty = tcx.type_of(alias.def_id).instantiate(tcx, alias.args);
depth += 1;
}
ty
}

View file

@ -1,20 +1,12 @@
//! Orphan checker: every impl either implements a trait defined in this
//! crate or pertains to a type defined in this crate.
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{DelayDm, ErrorGuaranteed};
use rustc_errors::ErrorGuaranteed;
use rustc_hir as hir;
use rustc_middle::ty::util::CheckRegions;
use rustc_middle::ty::GenericArgs;
use rustc_middle::ty::{
self, AliasKind, ImplPolarity, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt,
TypeVisitor,
};
use rustc_session::lint;
use rustc_span::def_id::{DefId, LocalDefId};
use rustc_middle::ty::{self, AliasKind, Ty, TyCtxt, TypeVisitableExt};
use rustc_span::def_id::LocalDefId;
use rustc_span::Span;
use rustc_trait_selection::traits;
use std::ops::ControlFlow;
use crate::errors;
@ -26,30 +18,17 @@ pub(crate) fn orphan_check_impl(
let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity();
trait_ref.error_reported()?;
let ret = do_orphan_check_impl(tcx, trait_ref, impl_def_id);
if tcx.trait_is_auto(trait_ref.def_id) {
lint_auto_trait_impl(tcx, trait_ref, impl_def_id);
}
ret
}
fn do_orphan_check_impl<'tcx>(
tcx: TyCtxt<'tcx>,
trait_ref: ty::TraitRef<'tcx>,
def_id: LocalDefId,
) -> Result<(), ErrorGuaranteed> {
let trait_def_id = trait_ref.def_id;
match traits::orphan_check(tcx, def_id.to_def_id()) {
match traits::orphan_check(tcx, impl_def_id.to_def_id()) {
Ok(()) => {}
Err(err) => {
let item = tcx.hir().expect_item(def_id);
let item = tcx.hir().expect_item(impl_def_id);
let hir::ItemKind::Impl(impl_) = item.kind else {
bug!("{:?} is not an impl: {:?}", def_id, item);
bug!("{:?} is not an impl: {:?}", impl_def_id, item);
};
let tr = impl_.of_trait.as_ref().unwrap();
let sp = tcx.def_span(def_id);
let sp = tcx.def_span(impl_def_id);
emit_orphan_check_error(
tcx,
@ -193,7 +172,7 @@ fn do_orphan_check_impl<'tcx>(
// impl<T> AutoTrait for T {}
// impl<T: ?Sized> AutoTrait for T {}
ty::Param(..) => (
if self_ty.is_sized(tcx, tcx.param_env(def_id)) {
if self_ty.is_sized(tcx, tcx.param_env(impl_def_id)) {
LocalImpl::Allow
} else {
LocalImpl::Disallow { problematic_kind: "generic type" }
@ -250,7 +229,7 @@ fn do_orphan_check_impl<'tcx>(
| ty::Bound(..)
| ty::Placeholder(..)
| ty::Infer(..) => {
let sp = tcx.def_span(def_id);
let sp = tcx.def_span(impl_def_id);
span_bug!(sp, "weird self type for autotrait impl")
}
@ -262,7 +241,7 @@ fn do_orphan_check_impl<'tcx>(
LocalImpl::Allow => {}
LocalImpl::Disallow { problematic_kind } => {
return Err(tcx.dcx().emit_err(errors::TraitsWithDefaultImpl {
span: tcx.def_span(def_id),
span: tcx.def_span(impl_def_id),
traits: tcx.def_path_str(trait_def_id),
problematic_kind,
self_ty,
@ -274,13 +253,13 @@ fn do_orphan_check_impl<'tcx>(
NonlocalImpl::Allow => {}
NonlocalImpl::DisallowBecauseNonlocal => {
return Err(tcx.dcx().emit_err(errors::CrossCrateTraitsDefined {
span: tcx.def_span(def_id),
span: tcx.def_span(impl_def_id),
traits: tcx.def_path_str(trait_def_id),
}));
}
NonlocalImpl::DisallowOther => {
return Err(tcx.dcx().emit_err(errors::CrossCrateTraits {
span: tcx.def_span(def_id),
span: tcx.def_span(impl_def_id),
traits: tcx.def_path_str(trait_def_id),
self_ty,
}));
@ -445,146 +424,3 @@ fn emit_orphan_check_error<'tcx>(
}
})
}
/// Lint impls of auto traits if they are likely to have
/// unsound or surprising effects on auto impls.
fn lint_auto_trait_impl<'tcx>(
tcx: TyCtxt<'tcx>,
trait_ref: ty::TraitRef<'tcx>,
impl_def_id: LocalDefId,
) {
if trait_ref.args.len() != 1 {
tcx.dcx().span_delayed_bug(
tcx.def_span(impl_def_id),
"auto traits cannot have generic parameters",
);
return;
}
let self_ty = trait_ref.self_ty();
let (self_type_did, args) = match self_ty.kind() {
ty::Adt(def, args) => (def.did(), args),
_ => {
// FIXME: should also lint for stuff like `&i32` but
// considering that auto traits are unstable, that
// isn't too important for now as this only affects
// crates using `nightly`, and std.
return;
}
};
// Impls which completely cover a given root type are fine as they
// disable auto impls entirely. So only lint if the args
// are not a permutation of the identity args.
let Err(arg) = tcx.uses_unique_generic_params(args, CheckRegions::No) else {
// ok
return;
};
// Ideally:
//
// - compute the requirements for the auto impl candidate
// - check whether these are implied by the non covering impls
// - if not, emit the lint
//
// What we do here is a bit simpler:
//
// - badly check if an auto impl candidate definitely does not apply
// for the given simplified type
// - if so, do not lint
if fast_reject_auto_impl(tcx, trait_ref.def_id, self_ty) {
// ok
return;
}
tcx.node_span_lint(
lint::builtin::SUSPICIOUS_AUTO_TRAIT_IMPLS,
tcx.local_def_id_to_hir_id(impl_def_id),
tcx.def_span(impl_def_id),
DelayDm(|| {
format!(
"cross-crate traits with a default impl, like `{}`, \
should not be specialized",
tcx.def_path_str(trait_ref.def_id),
)
}),
|lint| {
let item_span = tcx.def_span(self_type_did);
let self_descr = tcx.def_descr(self_type_did);
match arg {
ty::util::NotUniqueParam::DuplicateParam(arg) => {
lint.note(format!("`{arg}` is mentioned multiple times"));
}
ty::util::NotUniqueParam::NotParam(arg) => {
lint.note(format!("`{arg}` is not a generic parameter"));
}
}
lint.span_note(
item_span,
format!(
"try using the same sequence of generic parameters as the {self_descr} definition",
),
);
},
);
}
fn fast_reject_auto_impl<'tcx>(tcx: TyCtxt<'tcx>, trait_def_id: DefId, self_ty: Ty<'tcx>) -> bool {
struct DisableAutoTraitVisitor<'tcx> {
tcx: TyCtxt<'tcx>,
trait_def_id: DefId,
self_ty_root: Ty<'tcx>,
seen: FxHashSet<DefId>,
}
impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for DisableAutoTraitVisitor<'tcx> {
type BreakTy = ();
fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
let tcx = self.tcx;
if ty != self.self_ty_root {
for impl_def_id in tcx.non_blanket_impls_for_ty(self.trait_def_id, ty) {
match tcx.impl_polarity(impl_def_id) {
ImplPolarity::Negative => return ControlFlow::Break(()),
ImplPolarity::Reservation => {}
// FIXME(@lcnr): That's probably not good enough, idk
//
// We might just want to take the rustdoc code and somehow avoid
// explicit impls for `Self`.
ImplPolarity::Positive => return ControlFlow::Continue(()),
}
}
}
match ty.kind() {
ty::Adt(def, args) if def.is_phantom_data() => args.visit_with(self),
ty::Adt(def, args) => {
// @lcnr: This is the only place where cycles can happen. We avoid this
// by only visiting each `DefId` once.
//
// This will be is incorrect in subtle cases, but I don't care :)
if self.seen.insert(def.did()) {
for ty in def.all_fields().map(|field| field.ty(tcx, args)) {
ty.visit_with(self)?;
}
}
ControlFlow::Continue(())
}
_ => ty.super_visit_with(self),
}
}
}
let self_ty_root = match self_ty.kind() {
ty::Adt(def, _) => Ty::new_adt(tcx, *def, GenericArgs::identity_for_item(tcx, def.did())),
_ => unimplemented!("unexpected self ty {:?}", self_ty),
};
self_ty_root
.visit_with(&mut DisableAutoTraitVisitor {
tcx,
self_ty_root,
trait_def_id,
seen: FxHashSet::default(),
})
.is_break()
}

View file

@ -520,7 +520,7 @@ fn get_new_lifetime_name<'tcx>(
generics: &hir::Generics<'tcx>,
) -> String {
let existing_lifetimes = tcx
.collect_referenced_late_bound_regions(&poly_trait_ref)
.collect_referenced_late_bound_regions(poly_trait_ref)
.into_iter()
.filter_map(|lt| {
if let ty::BoundRegionKind::BrNamed(_, name) = lt {
@ -1630,7 +1630,7 @@ fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>(
#[instrument(level = "debug", skip(tcx))]
fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
let mut result = tcx.explicit_predicates_of(def_id);
debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result,);
debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result);
let inferred_outlives = tcx.inferred_outlives_of(def_id);
if !inferred_outlives.is_empty() {
debug!(

View file

@ -315,7 +315,7 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics {
if is_host_effect {
if let Some(idx) = host_effect_index {
tcx.dcx().span_delayed_bug(
tcx.dcx().span_bug(
param.span,
format!("parent also has host effect param? index: {idx}, def: {def_id:?}"),
);

View file

@ -1331,7 +1331,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
}
}
self.tcx.dcx().span_delayed_bug(
self.tcx.dcx().span_bug(
lifetime_ref.ident.span,
format!("Could not resolve {:?} in scope {:#?}", lifetime_ref, self.scope,),
);
@ -1465,10 +1465,9 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
}
}
self.tcx.dcx().span_delayed_bug(
self.tcx.hir().span(hir_id),
format!("could not resolve {param_def_id:?}"),
);
self.tcx
.dcx()
.span_bug(self.tcx.hir().span(hir_id), format!("could not resolve {param_def_id:?}"));
}
#[instrument(level = "debug", skip(self))]

View file

@ -1,8 +1,8 @@
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_middle::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor};
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::Span;
use rustc_type_ir::fold::TypeFoldable;
use std::ops::ControlFlow;
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
@ -33,62 +33,47 @@ pub fn parameters_for_impl<'tcx>(
impl_trait_ref: Option<ty::TraitRef<'tcx>>,
) -> FxHashSet<Parameter> {
let vec = match impl_trait_ref {
Some(tr) => parameters_for(tcx, &tr, false),
None => parameters_for(tcx, &impl_self_ty, false),
Some(tr) => parameters_for(tcx, tr, false),
None => parameters_for(tcx, impl_self_ty, false),
};
vec.into_iter().collect()
}
/// If `include_nonconstraining` is false, returns the list of parameters that are
/// constrained by `t` - i.e., the value of each parameter in the list is
/// uniquely determined by `t` (see RFC 447). If it is true, return the list
/// of parameters whose values are needed in order to constrain `ty` - these
/// constrained by `value` - i.e., the value of each parameter in the list is
/// uniquely determined by `value` (see RFC 447). If it is true, return the list
/// of parameters whose values are needed in order to constrain `value` - these
/// differ, with the latter being a superset, in the presence of projections.
pub fn parameters_for<'tcx>(
tcx: TyCtxt<'tcx>,
t: &impl TypeVisitable<TyCtxt<'tcx>>,
value: impl TypeFoldable<TyCtxt<'tcx>>,
include_nonconstraining: bool,
) -> Vec<Parameter> {
let mut collector =
ParameterCollector { tcx, parameters: vec![], include_nonconstraining, depth: 0 };
t.visit_with(&mut collector);
let mut collector = ParameterCollector { parameters: vec![], include_nonconstraining };
let value = if !include_nonconstraining { tcx.expand_weak_alias_tys(value) } else { value };
value.visit_with(&mut collector);
collector.parameters
}
struct ParameterCollector<'tcx> {
tcx: TyCtxt<'tcx>,
struct ParameterCollector {
parameters: Vec<Parameter>,
include_nonconstraining: bool,
depth: usize,
}
impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ParameterCollector<'tcx> {
impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ParameterCollector {
fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
match *t.kind() {
// Projections are not injective in general.
ty::Alias(ty::Projection | ty::Inherent | ty::Opaque, _)
if !self.include_nonconstraining =>
{
// Projections are not injective in general.
return ControlFlow::Continue(());
}
ty::Alias(ty::Weak, alias) if !self.include_nonconstraining => {
if !self.tcx.recursion_limit().value_within_limit(self.depth) {
// Other constituent types may still constrain some generic params, consider
// `<T> (Overflow, T)` for example. Therefore we want to continue instead of
// breaking. Only affects diagnostics.
return ControlFlow::Continue(());
}
self.depth += 1;
return ensure_sufficient_stack(|| {
self.tcx
.type_of(alias.def_id)
.instantiate(self.tcx, alias.args)
.visit_with(self)
});
}
ty::Param(data) => {
self.parameters.push(Parameter::from(data));
// All weak alias types should've been expanded beforehand.
ty::Alias(ty::Weak, _) if !self.include_nonconstraining => {
bug!("unexpected weak alias type")
}
ty::Param(param) => self.parameters.push(Parameter::from(param)),
_ => {}
}
@ -224,12 +209,12 @@ pub fn setup_constraining_predicates<'tcx>(
// `<<T as Bar>::Baz as Iterator>::Output = <U as Iterator>::Output`
// Then the projection only applies if `T` is known, but it still
// does not determine `U`.
let inputs = parameters_for(tcx, &projection.projection_ty, true);
let inputs = parameters_for(tcx, projection.projection_ty, true);
let relies_only_on_inputs = inputs.iter().all(|p| input_parameters.contains(p));
if !relies_only_on_inputs {
continue;
}
input_parameters.extend(parameters_for(tcx, &projection.term, false));
input_parameters.extend(parameters_for(tcx, projection.term, false));
} else {
continue;
}

View file

@ -111,7 +111,7 @@ fn enforce_impl_params_are_constrained(
match item.kind {
ty::AssocKind::Type => {
if item.defaultness(tcx).has_value() {
cgp::parameters_for(tcx, &tcx.type_of(def_id).instantiate_identity(), true)
cgp::parameters_for(tcx, tcx.type_of(def_id).instantiate_identity(), true)
} else {
vec![]
}

View file

@ -133,7 +133,7 @@ fn check_always_applicable(
res = res.and(check_constness(tcx, impl1_def_id, impl2_node, span));
res = res.and(check_static_lifetimes(tcx, &parent_args, span));
res = res.and(check_duplicate_params(tcx, impl1_args, &parent_args, span));
res = res.and(check_duplicate_params(tcx, impl1_args, parent_args, span));
res = res.and(check_predicates(tcx, impl1_def_id, impl1_args, impl2_node, impl2_args, span));
res
@ -266,15 +266,15 @@ fn unconstrained_parent_impl_args<'tcx>(
continue;
}
unconstrained_parameters.extend(cgp::parameters_for(tcx, &projection_ty, true));
unconstrained_parameters.extend(cgp::parameters_for(tcx, projection_ty, true));
for param in cgp::parameters_for(tcx, &projected_ty, false) {
for param in cgp::parameters_for(tcx, projected_ty, false) {
if !unconstrained_parameters.contains(&param) {
constrained_params.insert(param.0);
}
}
unconstrained_parameters.extend(cgp::parameters_for(tcx, &projected_ty, true));
unconstrained_parameters.extend(cgp::parameters_for(tcx, projected_ty, true));
}
}
@ -309,7 +309,7 @@ fn unconstrained_parent_impl_args<'tcx>(
fn check_duplicate_params<'tcx>(
tcx: TyCtxt<'tcx>,
impl1_args: GenericArgsRef<'tcx>,
parent_args: &Vec<GenericArg<'tcx>>,
parent_args: Vec<GenericArg<'tcx>>,
span: Span,
) -> Result<(), ErrorGuaranteed> {
let mut base_params = cgp::parameters_for(tcx, parent_args, true);

View file

@ -198,6 +198,17 @@ pub fn check_crate(tcx: TyCtxt<'_>) -> Result<(), ErrorGuaranteed> {
collect::test_opaque_hidden_types(tcx)?;
}
// Make sure we evaluate all static and (non-associated) const items, even if unused.
// If any of these fail to evaluate, we do not want this crate to pass compilation.
tcx.hir().par_body_owners(|item_def_id| {
let def_kind = tcx.def_kind(item_def_id);
match def_kind {
DefKind::Static(_) => tcx.ensure().eval_static_initializer(item_def_id),
DefKind::Const => tcx.ensure().const_eval_poly(item_def_id.into()),
_ => (),
}
});
// Freeze definitions as we don't add new ones at this point. This improves performance by
// allowing lock-free access to them.
tcx.untracked().definitions.freeze();

View file

@ -1,5 +1,5 @@
use crate::structured_errors::StructuredDiagnostic;
use rustc_errors::{codes::*, pluralize, Applicability, Diagnostic, DiagnosticBuilder, MultiSpan};
use rustc_errors::{codes::*, pluralize, Applicability, DiagnosticBuilder, MultiSpan};
use rustc_hir as hir;
use rustc_middle::ty::{self as ty, AssocItems, AssocKind, TyCtxt};
use rustc_session::Session;
@ -525,7 +525,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
}
/// Builds the `expected 1 type argument / supplied 2 type arguments` message.
fn notify(&self, err: &mut Diagnostic) {
fn notify(&self, err: &mut DiagnosticBuilder<'_>) {
let (quantifier, bound) = self.get_quantifier_and_bound();
let provided_args = self.num_provided_args();
@ -577,7 +577,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
}
}
fn suggest(&self, err: &mut Diagnostic) {
fn suggest(&self, err: &mut DiagnosticBuilder<'_>) {
debug!(
"suggest(self.provided {:?}, self.gen_args.span(): {:?})",
self.num_provided_args(),
@ -605,7 +605,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
/// ```text
/// type Map = HashMap<String>;
/// ```
fn suggest_adding_args(&self, err: &mut Diagnostic) {
fn suggest_adding_args(&self, err: &mut DiagnosticBuilder<'_>) {
if self.gen_args.parenthesized != hir::GenericArgsParentheses::No {
return;
}
@ -624,7 +624,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
}
}
fn suggest_adding_lifetime_args(&self, err: &mut Diagnostic) {
fn suggest_adding_lifetime_args(&self, err: &mut DiagnosticBuilder<'_>) {
debug!("suggest_adding_lifetime_args(path_segment: {:?})", self.path_segment);
let num_missing_args = self.num_missing_lifetime_args();
let num_params_to_take = num_missing_args;
@ -678,7 +678,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
}
}
fn suggest_adding_type_and_const_args(&self, err: &mut Diagnostic) {
fn suggest_adding_type_and_const_args(&self, err: &mut DiagnosticBuilder<'_>) {
let num_missing_args = self.num_missing_type_or_const_args();
let msg = format!("add missing {} argument{}", self.kind(), pluralize!(num_missing_args));
@ -738,7 +738,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
/// ```compile_fail
/// Into::into::<Option<_>>(42) // suggests considering `Into::<Option<_>>::into(42)`
/// ```
fn suggest_moving_args_from_assoc_fn_to_trait(&self, err: &mut Diagnostic) {
fn suggest_moving_args_from_assoc_fn_to_trait(&self, err: &mut DiagnosticBuilder<'_>) {
let trait_ = match self.tcx.trait_of_item(self.def_id) {
Some(def_id) => def_id,
None => return,
@ -794,7 +794,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
fn suggest_moving_args_from_assoc_fn_to_trait_for_qualified_path(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
qpath: &'tcx hir::QPath<'tcx>,
msg: String,
num_assoc_fn_excess_args: usize,
@ -827,7 +827,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
fn suggest_moving_args_from_assoc_fn_to_trait_for_method_call(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
trait_def_id: DefId,
expr: &'tcx hir::Expr<'tcx>,
msg: String,
@ -881,7 +881,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
/// ```text
/// type Map = HashMap<String, String, String, String>;
/// ```
fn suggest_removing_args_or_generics(&self, err: &mut Diagnostic) {
fn suggest_removing_args_or_generics(&self, err: &mut DiagnosticBuilder<'_>) {
let num_provided_lt_args = self.num_provided_lifetime_args();
let num_provided_type_const_args = self.num_provided_type_or_const_args();
let unbound_types = self.get_unbound_associated_types();
@ -899,7 +899,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
let provided_args_matches_unbound_traits =
unbound_types.len() == num_redundant_type_or_const_args;
let remove_lifetime_args = |err: &mut Diagnostic| {
let remove_lifetime_args = |err: &mut DiagnosticBuilder<'_>| {
let mut lt_arg_spans = Vec::new();
let mut found_redundant = false;
for arg in self.gen_args.args {
@ -940,7 +940,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
);
};
let remove_type_or_const_args = |err: &mut Diagnostic| {
let remove_type_or_const_args = |err: &mut DiagnosticBuilder<'_>| {
let mut gen_arg_spans = Vec::new();
let mut found_redundant = false;
for arg in self.gen_args.args {
@ -1037,7 +1037,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
}
/// Builds the `type defined here` message.
fn show_definition(&self, err: &mut Diagnostic) {
fn show_definition(&self, err: &mut DiagnosticBuilder<'_>) {
let mut spans: MultiSpan = if let Some(def_span) = self.tcx.def_ident_span(self.def_id) {
if self.tcx.sess.source_map().is_span_accessible(def_span) {
def_span.into()
@ -1088,7 +1088,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
}
/// Add note if `impl Trait` is explicitly specified.
fn note_synth_provided(&self, err: &mut Diagnostic) {
fn note_synth_provided(&self, err: &mut DiagnosticBuilder<'_>) {
if !self.is_synth_provided() {
return;
}

View file

@ -1,6 +1,6 @@
use crate::coercion::{AsCoercionSite, CoerceMany};
use crate::{Diverges, Expectation, FnCtxt, Needs};
use rustc_errors::{Applicability, Diagnostic};
use rustc_errors::{Applicability, DiagnosticBuilder};
use rustc_hir::{
self as hir,
def::{CtorOf, DefKind, Res},
@ -177,7 +177,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn explain_never_type_coerced_to_unit(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
arm: &hir::Arm<'tcx>,
arm_ty: Ty<'tcx>,
prior_arm: Option<(Option<hir::HirId>, Ty<'tcx>, Span)>,
@ -209,7 +209,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn suggest_removing_semicolon_for_coerce(
&self,
diag: &mut Diagnostic,
diag: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'tcx>,
arm_ty: Ty<'tcx>,
prior_arm: Option<(Option<hir::HirId>, Ty<'tcx>, Span)>,
@ -303,7 +303,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// `if let PAT = EXPR {}` expressions that could be turned into `let PAT = EXPR;`.
fn explain_if_expr(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
ret_reason: Option<(Span, String)>,
if_span: Span,
cond_expr: &'tcx hir::Expr<'tcx>,

View file

@ -4,7 +4,7 @@ use super::{Expectation, FnCtxt, TupleArgumentsFlag};
use crate::errors;
use rustc_ast::util::parser::PREC_POSTFIX;
use rustc_errors::{Applicability, Diagnostic, ErrorGuaranteed, StashKey};
use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, StashKey};
use rustc_hir as hir;
use rustc_hir::def::{self, CtorKind, Namespace, Res};
use rustc_hir::def_id::DefId;
@ -347,7 +347,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// likely intention is to call the closure, suggest `(||{})()`. (#55851)
fn identify_bad_closure_def_and_call(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
hir_id: hir::HirId,
callee_node: &hir::ExprKind<'_>,
callee_span: Span,
@ -410,7 +410,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// likely intention is to create an array containing tuples.
fn maybe_suggest_bad_array_definition(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
call_expr: &'tcx hir::Expr<'tcx>,
callee_expr: &'tcx hir::Expr<'tcx>,
) -> bool {
@ -601,7 +601,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// and suggesting the fix if the method probe is successful.
fn suggest_call_as_method(
&self,
diag: &mut Diagnostic,
diag: &mut DiagnosticBuilder<'_, ()>,
segment: &'tcx hir::PathSegment<'tcx>,
arg_exprs: &'tcx [hir::Expr<'tcx>],
call_expr: &'tcx hir::Expr<'tcx>,

View file

@ -33,7 +33,7 @@ use super::FnCtxt;
use crate::errors;
use crate::type_error_struct;
use hir::ExprKind;
use rustc_errors::{codes::*, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed};
use rustc_errors::{codes::*, Applicability, DiagnosticBuilder, ErrorGuaranteed};
use rustc_hir as hir;
use rustc_macros::{TypeFoldable, TypeVisitable};
use rustc_middle::mir::Mutability;
@ -139,10 +139,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
| ty::Never
| ty::Dynamic(_, _, ty::DynStar)
| ty::Error(_) => {
let guar = self
.dcx()
.span_delayed_bug(span, format!("`{t:?}` should be sized but is not?"));
return Err(guar);
self.dcx().span_bug(span, format!("`{t:?}` should be sized but is not?"));
}
})
}
@ -983,7 +980,11 @@ impl<'a, 'tcx> CastCheck<'tcx> {
/// Attempt to suggest using `.is_empty` when trying to cast from a
/// collection type to a boolean.
fn try_suggest_collection_to_bool(&self, fcx: &FnCtxt<'a, 'tcx>, err: &mut Diagnostic) {
fn try_suggest_collection_to_bool(
&self,
fcx: &FnCtxt<'a, 'tcx>,
err: &mut DiagnosticBuilder<'_>,
) {
if self.cast_ty.is_bool() {
let derefed = fcx
.autoderef(self.expr_span, self.expr_ty)

View file

@ -36,9 +36,7 @@
//! ```
use crate::FnCtxt;
use rustc_errors::{
codes::*, struct_span_code_err, Applicability, Diagnostic, DiagnosticBuilder, MultiSpan,
};
use rustc_errors::{codes::*, struct_span_code_err, Applicability, DiagnosticBuilder, MultiSpan};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_hir::intravisit::{self, Visitor};
@ -1439,7 +1437,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
&mut self,
fcx: &FnCtxt<'a, 'tcx>,
cause: &ObligationCause<'tcx>,
augment_error: impl FnOnce(&mut Diagnostic),
augment_error: impl FnOnce(&mut DiagnosticBuilder<'_>),
label_unit_as_expected: bool,
) {
self.coerce_inner(
@ -1462,7 +1460,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
cause: &ObligationCause<'tcx>,
expression: Option<&'tcx hir::Expr<'tcx>>,
mut expression_ty: Ty<'tcx>,
augment_error: impl FnOnce(&mut Diagnostic),
augment_error: impl FnOnce(&mut DiagnosticBuilder<'_>),
label_expression_as_expected: bool,
) {
// Incorporate whatever type inference information we have
@ -1673,7 +1671,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
fn note_unreachable_loop_return(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
tcx: TyCtxt<'tcx>,
expr: &hir::Expr<'tcx>,
ret_exprs: &Vec<&'tcx hir::Expr<'tcx>>,

View file

@ -1,6 +1,6 @@
use crate::FnCtxt;
use rustc_errors::MultiSpan;
use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder};
use rustc_errors::{Applicability, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_hir::def::Res;
use rustc_hir::intravisit::Visitor;
@ -19,7 +19,7 @@ use super::method::probe;
impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub fn emit_type_mismatch_suggestions(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'tcx>,
expr_ty: Ty<'tcx>,
expected: Ty<'tcx>,
@ -70,7 +70,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub fn emit_coerce_suggestions(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'tcx>,
expr_ty: Ty<'tcx>,
expected: Ty<'tcx>,
@ -280,7 +280,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// with some expectation given by `source`.
pub fn note_source_of_type_mismatch_constraint(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
source: TypeMismatchSource<'tcx>,
) -> bool {
@ -550,7 +550,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// expected type.
pub fn annotate_loop_expected_due_to_inference(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
error: Option<TypeError<'tcx>>,
) {
@ -673,7 +673,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn annotate_expected_due_to_let_ty(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
error: Option<TypeError<'tcx>>,
) {
@ -782,7 +782,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn annotate_alternative_method_deref(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
error: Option<TypeError<'tcx>>,
) {
@ -1029,7 +1029,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn explain_self_literal(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'tcx>,
expected: Ty<'tcx>,
found: Ty<'tcx>,
@ -1082,7 +1082,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn note_wrong_return_ty_due_to_generic_arg(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
checked_ty: Ty<'tcx>,
) {

View file

@ -3,8 +3,8 @@ use std::borrow::Cow;
use crate::fluent_generated as fluent;
use rustc_errors::{
codes::*, AddToDiagnostic, Applicability, Diagnostic, DiagnosticArgValue, IntoDiagnosticArg,
MultiSpan, SubdiagnosticMessageOp,
codes::*, AddToDiagnostic, Applicability, DiagnosticArgValue, DiagnosticBuilder,
EmissionGuarantee, IntoDiagnosticArg, MultiSpan, SubdiagnosticMessageOp,
};
use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
use rustc_middle::ty::Ty;
@ -195,7 +195,11 @@ pub struct TypeMismatchFruTypo {
}
impl AddToDiagnostic for TypeMismatchFruTypo {
fn add_to_diagnostic_with<F: SubdiagnosticMessageOp>(self, diag: &mut Diagnostic, _: F) {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self,
diag: &mut DiagnosticBuilder<'_, G>,
_f: F,
) {
diag.arg("expr", self.expr.as_deref().unwrap_or("NONE"));
// Only explain that `a ..b` is a range if it's split up
@ -370,7 +374,11 @@ pub struct RemoveSemiForCoerce {
}
impl AddToDiagnostic for RemoveSemiForCoerce {
fn add_to_diagnostic_with<F: SubdiagnosticMessageOp>(self, diag: &mut Diagnostic, _: F) {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self,
diag: &mut DiagnosticBuilder<'_, G>,
_f: F,
) {
let mut multispan: MultiSpan = self.semi.into();
multispan.push_span_label(self.expr, fluent::hir_typeck_remove_semi_for_coerce_expr);
multispan.push_span_label(self.ret, fluent::hir_typeck_remove_semi_for_coerce_ret);
@ -541,8 +549,12 @@ pub enum CastUnknownPointerSub {
From(Span),
}
impl AddToDiagnostic for CastUnknownPointerSub {
fn add_to_diagnostic_with<F: SubdiagnosticMessageOp>(self, diag: &mut Diagnostic, f: F) {
impl rustc_errors::AddToDiagnostic for CastUnknownPointerSub {
fn add_to_diagnostic_with<G: EmissionGuarantee, F: SubdiagnosticMessageOp<G>>(
self,
diag: &mut DiagnosticBuilder<'_, G>,
f: F,
) {
match self {
CastUnknownPointerSub::To(span) => {
let msg = f(diag, crate::fluent_generated::hir_typeck_label_to);

View file

@ -26,8 +26,8 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_data_structures::unord::UnordMap;
use rustc_errors::{
codes::*, pluralize, struct_span_code_err, AddToDiagnostic, Applicability, Diagnostic,
DiagnosticBuilder, ErrorGuaranteed, StashKey,
codes::*, pluralize, struct_span_code_err, AddToDiagnostic, Applicability, DiagnosticBuilder,
ErrorGuaranteed, StashKey,
};
use rustc_hir as hir;
use rustc_hir::def::{CtorKind, DefKind, Res};
@ -69,23 +69,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&self,
expr: &'tcx hir::Expr<'tcx>,
expected_ty: Ty<'tcx>,
extend_err: impl FnOnce(&mut Diagnostic),
extend_err: impl FnOnce(&mut DiagnosticBuilder<'_>),
) -> Ty<'tcx> {
let mut ty = self.check_expr_with_expectation(expr, ExpectHasType(expected_ty));
// While we don't allow *arbitrary* coercions here, we *do* allow
// coercions from ! to `expected`.
if ty.is_never() {
if let Some(adjustments) = self.typeck_results.borrow().adjustments().get(expr.hir_id) {
let reported = self.dcx().span_delayed_bug(
expr.span,
"expression with never type wound up being adjusted",
);
return if let [Adjustment { kind: Adjust::NeverToAny, target }] = &adjustments[..] {
target.to_owned()
} else {
Ty::new_error(self.tcx(), reported)
};
if let Some(_) = self.typeck_results.borrow().adjustments().get(expr.hir_id) {
self.dcx()
.span_bug(expr.span, "expression with never type wound up being adjusted");
}
let adj_ty = self.next_ty_var(TypeVariableOrigin {
@ -958,7 +951,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
lhs: &'tcx hir::Expr<'tcx>,
code: ErrCode,
op_span: Span,
adjust_err: impl FnOnce(&mut Diagnostic),
adjust_err: impl FnOnce(&mut DiagnosticBuilder<'_>),
) {
if lhs.is_syntactic_place_expr() {
return;
@ -1223,7 +1216,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let lhs_ty = self.check_expr_with_needs(lhs, Needs::MutPlace);
let suggest_deref_binop = |err: &mut Diagnostic, rhs_ty: Ty<'tcx>| {
let suggest_deref_binop = |err: &mut DiagnosticBuilder<'_>, rhs_ty: Ty<'tcx>| {
if let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty) {
// Can only assign if the type is sized, so if `DerefMut` yields a type that is
// unsized, do not suggest dereferencing it.
@ -1322,10 +1315,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// the LUB of the breaks (possibly ! if none); else, it
// is nil. This makes sense because infinite loops
// (which would have type !) are only possible iff we
// permit break with a value [1].
// permit break with a value.
if ctxt.coerce.is_none() && !ctxt.may_break {
// [1]
self.dcx().span_delayed_bug(body.span, "no coercion, but loop may not break");
self.dcx().span_bug(body.span, "no coercion, but loop may not break");
}
ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| Ty::new_unit(self.tcx))
}
@ -2008,7 +2000,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
last_expr_field: &hir::ExprField<'tcx>,
variant: &ty::VariantDef,
args: GenericArgsRef<'tcx>,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
) {
// I don't use 'is_range_literal' because only double-sided, half-open ranges count.
if let ExprKind::Struct(QPath::LangItem(LangItem::Range, ..), [range_start, range_end], _) =
@ -2524,7 +2516,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn suggest_await_on_field_access(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
field_ident: Ident,
base: &'tcx hir::Expr<'tcx>,
ty: Ty<'tcx>,
@ -2723,7 +2715,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.emit()
}
fn point_at_param_definition(&self, err: &mut Diagnostic, param: ty::ParamTy) {
fn point_at_param_definition(&self, err: &mut DiagnosticBuilder<'_>, param: ty::ParamTy) {
let generics = self.tcx.generics_of(self.body_id);
let generic_param = generics.type_param(&param, self.tcx);
if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind {
@ -2742,7 +2734,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn maybe_suggest_array_indexing(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
base: &hir::Expr<'_>,
field: Ident,
@ -2766,7 +2758,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn suggest_first_deref_field(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
base: &hir::Expr<'_>,
field: Ident,

View file

@ -5,7 +5,7 @@ use crate::rvalue_scopes;
use crate::{BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy};
use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{Applicability, Diagnostic, ErrorGuaranteed, MultiSpan, StashKey};
use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, MultiSpan, StashKey};
use rustc_hir as hir;
use rustc_hir::def::{CtorOf, DefKind, Res};
use rustc_hir::def_id::DefId;
@ -1020,7 +1020,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(in super::super) fn note_internal_mutation_in_method(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
expected: Option<Ty<'tcx>>,
found: Ty<'tcx>,

View file

@ -13,7 +13,7 @@ use itertools::Itertools;
use rustc_ast as ast;
use rustc_data_structures::fx::FxIndexSet;
use rustc_errors::{
codes::*, pluralize, Applicability, Diagnostic, ErrorGuaranteed, MultiSpan, StashKey,
codes::*, pluralize, Applicability, DiagnosticBuilder, ErrorGuaranteed, MultiSpan, StashKey,
};
use rustc_hir as hir;
use rustc_hir::def::{CtorOf, DefKind, Res};
@ -740,8 +740,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
});
// We're done if we found errors, but we already emitted them.
if let Some(reported) = reported {
assert!(errors.is_empty());
if let Some(reported) = reported
&& errors.is_empty()
{
return reported;
}
assert!(!errors.is_empty());
@ -1935,7 +1936,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn label_fn_like(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
callable_def_id: Option<DefId>,
callee_ty: Option<Ty<'tcx>>,
call_expr: &'tcx hir::Expr<'tcx>,

View file

@ -12,7 +12,7 @@ use core::cmp::min;
use core::iter;
use rustc_ast::util::parser::{ExprPrecedence, PREC_POSTFIX};
use rustc_data_structures::packed::Pu128;
use rustc_errors::{Applicability, Diagnostic, MultiSpan};
use rustc_errors::{Applicability, DiagnosticBuilder, MultiSpan};
use rustc_hir as hir;
use rustc_hir::def::Res;
use rustc_hir::def::{CtorKind, CtorOf, DefKind};
@ -48,7 +48,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.copied()
}
pub(in super::super) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diagnostic) {
pub(in super::super) fn suggest_semicolon_at_end(
&self,
span: Span,
err: &mut DiagnosticBuilder<'_>,
) {
// This suggestion is incorrect for
// fn foo() -> bool { match () { () => true } || match () { () => true } }
err.span_suggestion_short(
@ -66,7 +70,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// - Possible missing return type if the return type is the default, and not `fn main()`.
pub fn suggest_mismatched_types_on_tail(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &'tcx hir::Expr<'tcx>,
expected: Ty<'tcx>,
found: Ty<'tcx>,
@ -97,7 +101,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// ```
pub(crate) fn suggest_fn_call(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
found: Ty<'tcx>,
can_satisfy: impl FnOnce(Ty<'tcx>) -> bool,
@ -179,7 +183,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub fn suggest_two_fn_call(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
lhs_expr: &'tcx hir::Expr<'tcx>,
lhs_ty: Ty<'tcx>,
rhs_expr: &'tcx hir::Expr<'tcx>,
@ -253,7 +257,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub fn suggest_remove_last_method_call(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'tcx>,
expected: Ty<'tcx>,
) -> bool {
@ -282,7 +286,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub fn suggest_deref_ref_or_into(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'tcx>,
expected: Ty<'tcx>,
found: Ty<'tcx>,
@ -540,7 +544,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// in the heap by calling `Box::new()`.
pub(in super::super) fn suggest_boxing_when_appropriate(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
span: Span,
hir_id: HirId,
expected: Ty<'tcx>,
@ -583,7 +587,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// suggest a non-capturing closure
pub(in super::super) fn suggest_no_capture_closure(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expected: Ty<'tcx>,
found: Ty<'tcx>,
) -> bool {
@ -620,7 +624,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
#[instrument(skip(self, err))]
pub(in super::super) fn suggest_calling_boxed_future_when_appropriate(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
expected: Ty<'tcx>,
found: Ty<'tcx>,
@ -732,7 +736,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.
pub fn suggest_missing_semicolon(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expression: &'tcx hir::Expr<'tcx>,
expected: Ty<'tcx>,
needs_block: bool,
@ -791,7 +795,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
#[instrument(level = "trace", skip(self, err))]
pub(in super::super) fn suggest_missing_return_type(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
fn_decl: &hir::FnDecl<'tcx>,
expected: Ty<'tcx>,
found: Ty<'tcx>,
@ -909,7 +913,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// ```
fn try_suggest_return_impl_trait(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expected: Ty<'tcx>,
found: Ty<'tcx>,
fn_id: hir::HirId,
@ -1014,7 +1018,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(in super::super) fn suggest_missing_break_or_return_expr(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &'tcx hir::Expr<'tcx>,
fn_decl: &hir::FnDecl<'tcx>,
expected: Ty<'tcx>,
@ -1118,7 +1122,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(in super::super) fn suggest_missing_parentheses(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
) -> bool {
let sp = self.tcx.sess.source_map().start_point(expr.span).with_parent(None);
@ -1136,7 +1140,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// if it was possibly mistaken array syntax.
pub(crate) fn suggest_block_to_brackets_peeling_refs(
&self,
diag: &mut Diagnostic,
diag: &mut DiagnosticBuilder<'_>,
mut expr: &hir::Expr<'_>,
mut expr_ty: Ty<'tcx>,
mut expected_ty: Ty<'tcx>,
@ -1163,7 +1167,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_clone_for_ref(
&self,
diag: &mut Diagnostic,
diag: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
expr_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>,
@ -1198,7 +1202,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_copied_cloned_or_as_ref(
&self,
diag: &mut Diagnostic,
diag: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
expr_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>,
@ -1248,7 +1252,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_into(
&self,
diag: &mut Diagnostic,
diag: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
expr_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>,
@ -1311,7 +1315,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// When expecting a `bool` and finding an `Option`, suggests using `let Some(..)` or `.is_some()`
pub(crate) fn suggest_option_to_bool(
&self,
diag: &mut Diagnostic,
diag: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
expr_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>,
@ -1368,7 +1372,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.
pub(crate) fn suggest_block_to_brackets(
&self,
diag: &mut Diagnostic,
diag: &mut DiagnosticBuilder<'_>,
blk: &hir::Block<'_>,
blk_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>,
@ -1408,7 +1412,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
#[instrument(skip(self, err))]
pub(crate) fn suggest_floating_point_literal(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
expected_ty: Ty<'tcx>,
) -> bool {
@ -1479,7 +1483,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
#[instrument(skip(self, err))]
pub(crate) fn suggest_null_ptr_for_literal_zero_given_to_ptr_arg(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
expected_ty: Ty<'tcx>,
) -> bool {
@ -1517,7 +1521,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_associated_const(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'tcx>,
expected_ty: Ty<'tcx>,
) -> bool {
@ -1611,7 +1615,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// which is a side-effect of autoref.
pub(crate) fn note_type_is_not_clone(
&self,
diag: &mut Diagnostic,
diag: &mut DiagnosticBuilder<'_>,
expected_ty: Ty<'tcx>,
found_ty: Ty<'tcx>,
expr: &hir::Expr<'_>,
@ -1811,7 +1815,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&self,
blk: &'tcx hir::Block<'tcx>,
expected_ty: Ty<'tcx>,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
) -> bool {
if let Some((span_semi, boxed)) = self.err_ctxt().could_remove_semicolon(blk, expected_ty) {
if let StatementAsExpression::NeedsBoxing = boxed {
@ -1856,7 +1860,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_missing_unwrap_expect(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'tcx>,
expected: Ty<'tcx>,
found: Ty<'tcx>,
@ -1939,7 +1943,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_coercing_result_via_try_operator(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'tcx>,
expected: Ty<'tcx>,
found: Ty<'tcx>,
@ -1986,7 +1990,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// sole field is of the found type, suggest such variants. (Issue #42764)
pub(crate) fn suggest_compatible_variants(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
expected: Ty<'tcx>,
expr_ty: Ty<'tcx>,
@ -2175,7 +2179,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_non_zero_new_unwrap(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
expected: Ty<'tcx>,
expr_ty: Ty<'tcx>,
@ -2719,7 +2723,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_cast(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
checked_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>,
@ -2847,7 +2851,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let in_const_context = self.tcx.hir().is_inside_const_context(expr.hir_id);
let suggest_fallible_into_or_lhs_from =
|err: &mut Diagnostic, exp_to_found_is_fallible: bool| {
|err: &mut DiagnosticBuilder<'_>, exp_to_found_is_fallible: bool| {
// If we know the expression the expected type is derived from, we might be able
// to suggest a widening conversion rather than a narrowing one (which may
// panic). For example, given x: u8 and y: u32, if we know the span of "x",
@ -2887,7 +2891,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
};
let suggest_to_change_suffix_or_into =
|err: &mut Diagnostic,
|err: &mut DiagnosticBuilder<'_>,
found_to_exp_is_fallible: bool,
exp_to_found_is_fallible: bool| {
let exp_is_lhs = expected_ty_expr.is_some_and(|e| self.tcx.hir().is_lhs(e.hir_id));
@ -3085,7 +3089,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// Identify when the user has written `foo..bar()` instead of `foo.bar()`.
pub(crate) fn suggest_method_call_on_range_literal(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'tcx>,
checked_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>,
@ -3163,7 +3167,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// block without a tail expression.
pub(crate) fn suggest_return_binding_for_missing_tail_expr(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
checked_ty: Ty<'tcx>,
expected_ty: Ty<'tcx>,

View file

@ -48,8 +48,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let to = normalize(to);
trace!(?from, ?to);
if from.has_non_region_infer() || to.has_non_region_infer() {
tcx.dcx().span_delayed_bug(span, "argument to transmute has inference variables");
return;
// Note: this path is currently not reached in any test, so any
// example that triggers this would be worth minimizing and
// converting into a test.
tcx.dcx().span_bug(span, "argument to transmute has inference variables");
}
// Transmutes that are only changing lifetimes are always ok.
if from == to {

View file

@ -570,8 +570,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
_ => {
self.tcx()
.dcx()
.span_delayed_bug(span, "struct or tuple struct pattern not applied to an ADT");
Err(())
.span_bug(span, "struct or tuple struct pattern not applied to an ADT");
}
}
}
@ -583,8 +582,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
match ty.kind() {
ty::Tuple(args) => Ok(args.len()),
_ => {
self.tcx().dcx().span_delayed_bug(span, "tuple pattern not applied to a tuple");
Err(())
self.tcx().dcx().span_bug(span, "tuple pattern not applied to a tuple");
}
}
}

View file

@ -11,7 +11,7 @@ pub use self::suggest::SelfSource;
pub use self::MethodError::*;
use crate::FnCtxt;
use rustc_errors::{Applicability, Diagnostic, SubdiagnosticMessage};
use rustc_errors::{Applicability, DiagnosticBuilder, SubdiagnosticMessage};
use rustc_hir as hir;
use rustc_hir::def::{CtorOf, DefKind, Namespace};
use rustc_hir::def_id::DefId;
@ -126,7 +126,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
#[instrument(level = "debug", skip(self, err, call_expr))]
pub(crate) fn suggest_method_call(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
msg: impl Into<SubdiagnosticMessage> + std::fmt::Debug,
method_name: Ident,
self_ty: Ty<'tcx>,

View file

@ -804,11 +804,10 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
let trait_ref = principal.with_self_ty(self.tcx, self_ty);
self.elaborate_bounds(iter::once(trait_ref), |this, new_trait_ref, item| {
if new_trait_ref.has_non_region_bound_vars() {
this.dcx().span_delayed_bug(
this.dcx().span_bug(
this.span,
"tried to select method from HRTB with non-lifetime bound vars",
);
return;
}
let new_trait_ref = this.instantiate_bound_regions_with_erased(new_trait_ref);

View file

@ -12,8 +12,8 @@ use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
use rustc_data_structures::sorted_map::SortedMap;
use rustc_data_structures::unord::UnordSet;
use rustc_errors::{
codes::*, pluralize, struct_span_code_err, Applicability, Diagnostic, DiagnosticBuilder,
MultiSpan, StashKey,
codes::*, pluralize, struct_span_code_err, Applicability, DiagnosticBuilder, MultiSpan,
StashKey,
};
use rustc_hir as hir;
use rustc_hir::def::DefKind;
@ -34,8 +34,8 @@ use rustc_middle::ty::IsSuggestable;
use rustc_middle::ty::{self, GenericArgKind, Ty, TyCtxt, TypeVisitableExt};
use rustc_span::def_id::DefIdSet;
use rustc_span::symbol::{kw, sym, Ident};
use rustc_span::Symbol;
use rustc_span::{edit_distance, ExpnKind, FileName, MacroKind, Span};
use rustc_span::{Symbol, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt;
use rustc_trait_selection::traits::error_reporting::on_unimplemented::OnUnimplementedNote;
use rustc_trait_selection::traits::error_reporting::on_unimplemented::TypeErrCtxtExt as _;
@ -369,6 +369,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
};
if let Some(file) = file {
err.note(format!("the full type name has been written to '{}'", file.display()));
err.note(format!(
"consider using `--verbose` to print the full type name to the console"
));
}
err
@ -493,6 +496,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if let Some(file) = ty_file {
err.note(format!("the full type name has been written to '{}'", file.display(),));
err.note(format!(
"consider using `--verbose` to print the full type name to the console"
));
}
if rcvr_ty.references_error() {
err.downgrade_to_delayed_bug();
@ -1127,7 +1133,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}
let label_span_not_found = |err: &mut Diagnostic| {
let label_span_not_found = |err: &mut DiagnosticBuilder<'_>| {
if unsatisfied_predicates.is_empty() {
err.span_label(span, format!("{item_kind} not found in `{ty_str}`"));
let is_string_or_ref_str = match rcvr_ty.kind() {
@ -1438,7 +1444,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self_source: SelfSource<'tcx>,
args: Option<&'tcx [hir::Expr<'tcx>]>,
span: Span,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
sources: &mut Vec<CandidateSource>,
sugg_span: Option<Span>,
) {
@ -1584,7 +1590,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// Look at all the associated functions without receivers in the type's inherent impls
/// to look for builders that return `Self`, `Option<Self>` or `Result<Self, _>`.
fn find_builder_fn(&self, err: &mut Diagnostic, rcvr_ty: Ty<'tcx>) {
fn find_builder_fn(&self, err: &mut DiagnosticBuilder<'_>, rcvr_ty: Ty<'tcx>) {
let ty::Adt(adt_def, _) = rcvr_ty.kind() else {
return;
};
@ -1597,7 +1603,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.filter(|item| matches!(item.kind, ty::AssocKind::Fn) && !item.fn_has_self_parameter)
.filter_map(|item| {
// Only assoc fns that return `Self`, `Option<Self>` or `Result<Self, _>`.
let ret_ty = self.tcx.fn_sig(item.def_id).skip_binder().output();
let ret_ty = self
.tcx
.fn_sig(item.def_id)
.instantiate(self.tcx, self.fresh_args_for_item(DUMMY_SP, item.def_id))
.output();
let ret_ty = self.tcx.instantiate_bound_regions_with_erased(ret_ty);
let ty::Adt(def, args) = ret_ty.kind() else {
return None;
@ -1665,7 +1675,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// doesn't take a `self` receiver.
fn suggest_associated_call_syntax(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
static_candidates: &Vec<CandidateSource>,
rcvr_ty: Ty<'tcx>,
source: SelfSource<'tcx>,
@ -1809,7 +1819,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
rcvr_ty: Ty<'tcx>,
expr: &hir::Expr<'_>,
item_name: Ident,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
) -> bool {
let tcx = self.tcx;
let field_receiver = self.autoderef(span, rcvr_ty).find_map(|(ty, _)| match ty.kind() {
@ -2132,7 +2142,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// Suggest calling a method on a field i.e. `a.field.bar()` instead of `a.bar()`
fn suggest_calling_method_on_field(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
source: SelfSource<'tcx>,
span: Span,
actual: Ty<'tcx>,
@ -2212,7 +2222,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn suggest_unwrapping_inner_self(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
source: SelfSource<'tcx>,
actual: Ty<'tcx>,
item_name: Ident,
@ -2401,7 +2411,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn note_unmet_impls_on_type(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
errors: Vec<FulfillmentError<'tcx>>,
suggest_derive: bool,
) {
@ -2484,7 +2494,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn note_predicate_source_and_get_derives(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
unsatisfied_predicates: &[(
ty::Predicate<'tcx>,
Option<ty::Predicate<'tcx>>,
@ -2566,7 +2576,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(crate) fn suggest_derive(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
unsatisfied_predicates: &[(
ty::Predicate<'tcx>,
Option<ty::Predicate<'tcx>>,
@ -2602,7 +2612,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn note_derefed_ty_has_method(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
self_source: SelfSource<'tcx>,
rcvr_ty: Ty<'tcx>,
item_name: Ident,
@ -2682,7 +2692,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn suggest_await_before_method(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
item_name: Ident,
ty: Ty<'tcx>,
call: &hir::Expr<'_>,
@ -2705,7 +2715,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}
fn suggest_use_candidates(&self, err: &mut Diagnostic, msg: String, candidates: Vec<DefId>) {
fn suggest_use_candidates(
&self,
err: &mut DiagnosticBuilder<'_>,
msg: String,
candidates: Vec<DefId>,
) {
let parent_map = self.tcx.visible_parent_map(());
// Separate out candidates that must be imported with a glob, because they are named `_`
@ -2752,7 +2767,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn suggest_valid_traits(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
valid_out_of_scope_traits: Vec<DefId>,
explain: bool,
) -> bool {
@ -2793,7 +2808,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn suggest_traits_to_import(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
span: Span,
rcvr_ty: Ty<'tcx>,
item_name: Ident,
@ -3332,7 +3347,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// FIXME: currently not working for suggesting `map_or_else`, see #102408
pub(crate) fn suggest_else_fn_with_closure(
&self,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
expr: &hir::Expr<'_>,
found: Ty<'tcx>,
expected: Ty<'tcx>,
@ -3458,7 +3473,7 @@ pub fn all_traits(tcx: TyCtxt<'_>) -> Vec<TraitInfo> {
fn print_disambiguation_help<'tcx>(
tcx: TyCtxt<'tcx>,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
source: SelfSource<'tcx>,
args: Option<&'tcx [hir::Expr<'tcx>]>,
trait_ref: ty::TraitRef<'tcx>,

View file

@ -5,7 +5,7 @@ use super::FnCtxt;
use crate::Expectation;
use rustc_ast as ast;
use rustc_data_structures::packed::Pu128;
use rustc_errors::{codes::*, struct_span_code_err, Applicability, Diagnostic, DiagnosticBuilder};
use rustc_errors::{codes::*, struct_span_code_err, Applicability, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use rustc_infer::traits::ObligationCauseCode;
@ -695,7 +695,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
rhs_expr: &'tcx hir::Expr<'tcx>,
lhs_ty: Ty<'tcx>,
rhs_ty: Ty<'tcx>,
err: &mut Diagnostic,
err: &mut DiagnosticBuilder<'_>,
is_assign: IsAssign,
op: hir::BinOp,
) -> bool {

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