From e04e3b386bf6847b9d00c2ecc5ea5d5a430edb2d Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sun, 12 Jul 2026 00:19:02 +0200 Subject: [PATCH 1/2] Rename `rustc_const_eval/src/errors.rs` into `rustc_const_eval/src/diagnostics.rs` --- .../src/check_consts/check.rs | 8 +-- .../rustc_const_eval/src/check_consts/ops.rs | 63 ++++++++++--------- .../rustc_const_eval/src/const_eval/error.rs | 14 ++--- .../src/const_eval/eval_queries.rs | 27 ++++---- .../src/const_eval/machine.rs | 2 +- .../src/{errors.rs => diagnostics.rs} | 0 .../rustc_const_eval/src/interpret/intern.rs | 5 +- .../rustc_const_eval/src/interpret/stack.rs | 14 +++-- compiler/rustc_const_eval/src/lib.rs | 2 +- 9 files changed, 74 insertions(+), 61 deletions(-) rename compiler/rustc_const_eval/src/{errors.rs => diagnostics.rs} (100%) diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index daf51dd967203..20fa1089004a4 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -29,7 +29,7 @@ use super::qualifs::{self, HasMutInterior, NeedsDrop, NeedsNonConstDrop}; use super::resolver::FlowSensitiveAnalysis; use super::{ConstCx, Qualif}; use crate::check_consts::is_fn_or_trait_safe_to_expose_on_stable; -use crate::errors; +use crate::diagnostics; type QualifResults<'mir, 'tcx, Q> = rustc_mir_dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'mir, 'tcx, Q>>; @@ -475,7 +475,7 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> { if self.enforce_recursive_const_stability() && !is_fn_or_trait_safe_to_expose_on_stable(self.tcx, def_id) { - self.dcx().emit_err(errors::UnmarkedConstItemExposed { + self.dcx().emit_err(diagnostics::UnmarkedConstItemExposed { span: self.span, def_path: self.tcx.def_path_str(def_id), }); @@ -874,7 +874,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { // regular stability, and regular stability is checked separately. // However, we *do* have to worry about *recursive* const stability. if !is_const_stable && self.enforce_recursive_const_stability() { - self.dcx().emit_err(errors::UnmarkedIntrinsicExposed { + self.dcx().emit_err(diagnostics::UnmarkedIntrinsicExposed { span: self.span, def_path: self.tcx.def_path_str(callee), }); @@ -988,7 +988,7 @@ fn emit_unstable_in_stable_exposed_error( ) -> ErrorGuaranteed { let attr_span = ccx.tcx.def_span(ccx.def_id()).shrink_to_lo(); - ccx.dcx().emit_err(errors::UnstableInStableExposed { + ccx.dcx().emit_err(diagnostics::UnstableInStableExposed { gate: gate.to_string(), span, attr_span, diff --git a/compiler/rustc_const_eval/src/check_consts/ops.rs b/compiler/rustc_const_eval/src/check_consts/ops.rs index 78b23627f6b5e..1f4b2c7879cc7 100644 --- a/compiler/rustc_const_eval/src/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/check_consts/ops.rs @@ -23,7 +23,7 @@ use rustc_trait_selection::traits::SelectionContext; use tracing::debug; use super::ConstCx; -use crate::errors; +use crate::diagnostics; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Status { @@ -71,7 +71,7 @@ pub trait NonConstOp<'tcx>: std::fmt::Debug { pub(crate) struct FnCallIndirect; impl<'tcx> NonConstOp<'tcx> for FnCallIndirect { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { - ccx.dcx().create_err(errors::UnallowedFnPointerCall { span, kind: ccx.const_kind() }) + ccx.dcx().create_err(diagnostics::UnallowedFnPointerCall { span, kind: ccx.const_kind() }) } } @@ -90,7 +90,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallCVariadic { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { ccx.tcx.sess.create_feature_err( - errors::NonConstCVariadicCall { span, kind: ccx.const_kind() }, + diagnostics::NonConstCVariadicCall { span, kind: ccx.const_kind() }, sym::const_c_variadic, ) } @@ -192,7 +192,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { // FIXME(const_trait_impl) revisit this if !tcx.is_const_trait_impl(data.impl_def_id) { let span = tcx.def_span(data.impl_def_id); - err.subdiagnostic(errors::NonConstImplNote { span }); + err.subdiagnostic(diagnostics::NonConstImplNote { span }); } } } @@ -235,7 +235,7 @@ fn build_error_for_const_call<'tcx>( CallKind::Normal { desugaring: Some((kind, self_ty)), .. } => { macro_rules! error { ($err:ident) => { - tcx.dcx().create_err(errors::$err { + tcx.dcx().create_err(diagnostics::$err { span, ty: self_ty, kind: ccx.const_kind(), @@ -273,14 +273,14 @@ fn build_error_for_const_call<'tcx>( span_bug!(span, "calling const FnDef errored when it shouldn't"); } - Some(errors::NonConstClosureNote::FnDef { span }) + Some(diagnostics::NonConstClosureNote::FnDef { span }) } - FnPtr(..) => Some(errors::NonConstClosureNote::FnPtr { kind }), - Closure(..) => Some(errors::NonConstClosureNote::Closure { kind }), + FnPtr(..) => Some(diagnostics::NonConstClosureNote::FnPtr { kind }), + Closure(..) => Some(diagnostics::NonConstClosureNote::Closure { kind }), _ => None, }; - let mut err = tcx.dcx().create_err(errors::NonConstClosure { + let mut err = tcx.dcx().create_err(diagnostics::NonConstClosure { span, kind: ccx.const_kind(), note, @@ -292,7 +292,7 @@ fn build_error_for_const_call<'tcx>( } CallKind::Operator { trait_id, self_ty, .. } => { let mut err = if let CallSource::MatchCmp = call_source { - tcx.dcx().create_err(errors::NonConstMatchEq { + tcx.dcx().create_err(diagnostics::NonConstMatchEq { span, kind: ccx.const_kind(), ty: self_ty, @@ -323,7 +323,7 @@ fn build_error_for_const_call<'tcx>( { let rhs_pos = span.lo() + BytePos::from_usize(eq_idx + 2 + rhs_idx); let rhs_span = span.with_lo(rhs_pos).with_hi(rhs_pos); - sugg = Some(errors::ConsiderDereferencing { + sugg = Some(diagnostics::ConsiderDereferencing { deref, span: span.shrink_to_lo(), rhs_span, @@ -333,7 +333,7 @@ fn build_error_for_const_call<'tcx>( _ => {} } } - tcx.dcx().create_err(errors::NonConstOperator { + tcx.dcx().create_err(diagnostics::NonConstOperator { span, kind: ccx.const_kind(), sugg, @@ -354,7 +354,7 @@ fn build_error_for_const_call<'tcx>( None }; - let mut err = tcx.dcx().create_err(errors::NonConstDerefCoercion { + let mut err = tcx.dcx().create_err(diagnostics::NonConstDerefCoercion { span, ty: self_ty, kind: ccx.const_kind(), @@ -367,7 +367,7 @@ fn build_error_for_const_call<'tcx>( err } _ if tcx.opt_parent(callee) == tcx.get_diagnostic_item(sym::FmtArgumentsNew) => { - ccx.dcx().create_err(errors::NonConstFmtMacroCall { + ccx.dcx().create_err(diagnostics::NonConstFmtMacroCall { span, kind: ccx.const_kind(), non_or_conditionally, @@ -375,7 +375,7 @@ fn build_error_for_const_call<'tcx>( } _ => { let def_descr = ccx.tcx.def_descr(callee); - let mut err = ccx.dcx().create_err(errors::NonConstFnCall { + let mut err = ccx.dcx().create_err(diagnostics::NonConstFnCall { span, def_descr, def_path_str: ccx.tcx.def_path_str_with_args(callee, args), @@ -471,12 +471,12 @@ impl<'tcx> NonConstOp<'tcx> for CallUnstable { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { assert!(!self.feature_enabled); let mut err = if self.is_function_call { - ccx.dcx().create_err(errors::UnstableConstFn { + ccx.dcx().create_err(diagnostics::UnstableConstFn { span, def_path: ccx.tcx.def_path_str(self.def_id), }) } else { - ccx.dcx().create_err(errors::UnstableConstTrait { + ccx.dcx().create_err(diagnostics::UnstableConstTrait { span, def_path: ccx.tcx.def_path_str(self.def_id), }) @@ -494,7 +494,7 @@ pub(crate) struct IntrinsicNonConst { impl<'tcx> NonConstOp<'tcx> for IntrinsicNonConst { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { - ccx.dcx().create_err(errors::NonConstIntrinsic { + ccx.dcx().create_err(diagnostics::NonConstIntrinsic { span, name: self.name, kind: ccx.const_kind(), @@ -523,7 +523,7 @@ impl<'tcx> NonConstOp<'tcx> for IntrinsicUnstable { } fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { - ccx.dcx().create_err(errors::UnstableIntrinsic { + ccx.dcx().create_err(diagnostics::UnstableIntrinsic { span, name: self.name, feature: self.feature, @@ -556,9 +556,11 @@ impl<'tcx> NonConstOp<'tcx> for Coroutine { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { let msg = format!("{} are not allowed in {}s", self.0.to_plural_string(), ccx.const_kind()); if let Status::Unstable { gate, .. } = self.status_in_item(ccx) { - ccx.tcx.sess.create_feature_err(errors::UnallowedOpInConstContext { span, msg }, gate) + ccx.tcx + .sess + .create_feature_err(diagnostics::UnallowedOpInConstContext { span, msg }, gate) } else { - ccx.dcx().create_err(errors::UnallowedOpInConstContext { span, msg }) + ccx.dcx().create_err(diagnostics::UnallowedOpInConstContext { span, msg }) } } } @@ -567,7 +569,7 @@ impl<'tcx> NonConstOp<'tcx> for Coroutine { pub(crate) struct InlineAsm; impl<'tcx> NonConstOp<'tcx> for InlineAsm { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { - ccx.dcx().create_err(errors::UnallowedInlineAsm { span, kind: ccx.const_kind() }) + ccx.dcx().create_err(diagnostics::UnallowedInlineAsm { span, kind: ccx.const_kind() }) } } @@ -593,7 +595,7 @@ impl<'tcx> NonConstOp<'tcx> for LiveDrop<'tcx> { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { if self.needs_non_const_drop { - ccx.dcx().create_err(errors::LiveDrop { + ccx.dcx().create_err(diagnostics::LiveDrop { span, dropped_ty: self.dropped_ty, kind: ccx.const_kind(), @@ -601,7 +603,7 @@ impl<'tcx> NonConstOp<'tcx> for LiveDrop<'tcx> { }) } else { ccx.tcx.sess.create_feature_err( - errors::LiveDrop { + diagnostics::LiveDrop { span, dropped_ty: self.dropped_ty, kind: ccx.const_kind(), @@ -625,7 +627,8 @@ impl<'tcx> NonConstOp<'tcx> for EscapingCellBorrow { DiagImportance::Secondary } fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { - ccx.dcx().create_err(errors::InteriorMutableBorrowEscaping { span, kind: ccx.const_kind() }) + ccx.dcx() + .create_err(diagnostics::InteriorMutableBorrowEscaping { span, kind: ccx.const_kind() }) } } @@ -647,7 +650,7 @@ impl<'tcx> NonConstOp<'tcx> for EscapingMutBorrow { } fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { - ccx.dcx().create_err(errors::MutableBorrowEscaping { span, kind: ccx.const_kind() }) + ccx.dcx().create_err(diagnostics::MutableBorrowEscaping { span, kind: ccx.const_kind() }) } } @@ -656,7 +659,7 @@ impl<'tcx> NonConstOp<'tcx> for EscapingMutBorrow { pub(crate) struct PanicNonStr; impl<'tcx> NonConstOp<'tcx> for PanicNonStr { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { - ccx.dcx().create_err(errors::PanicNonStrErr { span }) + ccx.dcx().create_err(diagnostics::PanicNonStrErr { span }) } } @@ -668,7 +671,7 @@ pub(crate) struct RawPtrComparison; impl<'tcx> NonConstOp<'tcx> for RawPtrComparison { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { // FIXME(const_trait_impl): revert to span_bug? - ccx.dcx().create_err(errors::RawPtrComparisonErr { span }) + ccx.dcx().create_err(diagnostics::RawPtrComparisonErr { span }) } } @@ -679,7 +682,7 @@ impl<'tcx> NonConstOp<'tcx> for RawPtrComparison { pub(crate) struct RawPtrToIntCast; impl<'tcx> NonConstOp<'tcx> for RawPtrToIntCast { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { - ccx.dcx().create_err(errors::RawPtrToIntErr { span }) + ccx.dcx().create_err(diagnostics::RawPtrToIntErr { span }) } } @@ -688,6 +691,6 @@ impl<'tcx> NonConstOp<'tcx> for RawPtrToIntCast { pub(crate) struct ThreadLocalAccess; impl<'tcx> NonConstOp<'tcx> for ThreadLocalAccess { fn build_error(&self, ccx: &ConstCx<'_, 'tcx>, span: Span) -> Diag<'tcx> { - ccx.dcx().create_err(errors::ThreadLocalAccessErr { span }) + ccx.dcx().create_err(diagnostics::ThreadLocalAccessErr { span }) } } diff --git a/compiler/rustc_const_eval/src/const_eval/error.rs b/compiler/rustc_const_eval/src/const_eval/error.rs index 2c299df7b777d..c9356858f760f 100644 --- a/compiler/rustc_const_eval/src/const_eval/error.rs +++ b/compiler/rustc_const_eval/src/const_eval/error.rs @@ -11,7 +11,7 @@ use rustc_middle::ty::layout::LayoutError; use rustc_span::{DUMMY_SP, Span, Symbol}; use super::CompileTimeMachine; -use crate::errors::{self, FrameNote}; +use crate::diagnostics::{self, FrameNote}; use crate::interpret::{ CtfeProvenance, ErrorHandled, Frame, InterpCx, InterpErrorInfo, InterpErrorKind, MachineStopType, Pointer, err_inval, err_machine_stop, @@ -95,7 +95,7 @@ impl<'tcx> Into> for ConstEvalErrKind { pub(crate) fn get_span_and_frames<'tcx>( tcx: TyCtxtAt<'tcx>, stack: &[Frame<'tcx, impl Provenance, impl Sized>], -) -> (Span, Vec) { +) -> (Span, Vec) { let mut stacktrace = Frame::generate_stacktrace_from_stack(stack, *tcx); // Filter out `requires_caller_location` frames. stacktrace.retain(|frame| !frame.instance.def.requires_caller_location(*tcx)); @@ -106,8 +106,8 @@ pub(crate) fn get_span_and_frames<'tcx>( // Add notes to the backtrace. Don't print a single-line backtrace though. if stacktrace.len() > 1 { // Helper closure to print duplicated lines. - let mut add_frame = |mut frame: errors::FrameNote| { - frames.push(errors::FrameNote { times: 0, ..frame.clone() }); + let mut add_frame = |mut frame: diagnostics::FrameNote| { + frames.push(diagnostics::FrameNote { times: 0, ..frame.clone() }); // Don't print [... additional calls ...] if the number of lines is small if frame.times < 3 { let times = frame.times; @@ -118,7 +118,7 @@ pub(crate) fn get_span_and_frames<'tcx>( } }; - let mut last_frame: Option = None; + let mut last_frame: Option = None; for frame_info in &stacktrace { let frame = frame_info.as_note(*tcx); match last_frame.as_mut() { @@ -207,7 +207,7 @@ pub(super) fn report<'tcx>( { let bytes = ecx.print_alloc_bytes_for_diagnostics(alloc_id); let info = ecx.get_alloc_info(alloc_id); - let raw_bytes = errors::RawBytesNote { + let raw_bytes = diagnostics::RawBytesNote { size: info.size.bytes(), align: info.align.bytes(), bytes, @@ -241,7 +241,7 @@ pub(super) fn lint<'tcx, L>( tcx: TyCtxtAt<'tcx>, machine: &CompileTimeMachine<'tcx>, lint: &'static rustc_session::lint::Lint, - decorator: impl FnOnce(Vec) -> L, + decorator: impl FnOnce(Vec) -> L, ) where L: for<'a> rustc_errors::Diagnostic<'a, ()>, { diff --git a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs index 9a8e95c0bea3c..25537dc3eefce 100644 --- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs @@ -21,7 +21,7 @@ use crate::interpret::{ InterpResult, MPlaceTy, MemoryKind, OpTy, RefTracking, ReturnContinuation, create_static_alloc, intern_const_alloc_recursive, interp_ok, throw_exhaust, }; -use crate::{CTRL_C_RECEIVED, errors}; +use crate::{CTRL_C_RECEIVED, diagnostics}; fn retry_codegen_mode_with_postanalysis<'tcx, K: TypeVisitable>, V>( key: ty::PseudoCanonicalInput<'tcx, K>, @@ -161,28 +161,31 @@ fn intern_and_validate<'tcx, R: InterpretationResult<'tcx>>( Ok(()) => {} Err(InternError::DanglingPointer) => { throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error( - ecx.tcx - .dcx() - .emit_err(errors::DanglingPtrInFinal { span: ecx.tcx.span, kind: intern_kind }), + ecx.tcx.dcx().emit_err(diagnostics::DanglingPtrInFinal { + span: ecx.tcx.span, + kind: intern_kind + }), ))); } Err(InternError::BadMutablePointer) => { throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error( - ecx.tcx - .dcx() - .emit_err(errors::MutablePtrInFinal { span: ecx.tcx.span, kind: intern_kind }), + ecx.tcx.dcx().emit_err(diagnostics::MutablePtrInFinal { + span: ecx.tcx.span, + kind: intern_kind + }), ))); } Err(InternError::ConstAllocNotGlobal) => { throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error( - ecx.tcx.dcx().emit_err(errors::ConstHeapPtrInFinal { span: ecx.tcx.span }), + ecx.tcx.dcx().emit_err(diagnostics::ConstHeapPtrInFinal { span: ecx.tcx.span }), ))); } Err(InternError::PartialPointer) => { throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error( - ecx.tcx - .dcx() - .emit_err(errors::PartialPtrInFinal { span: ecx.tcx.span, kind: intern_kind }), + ecx.tcx.dcx().emit_err(diagnostics::PartialPtrInFinal { + span: ecx.tcx.span, + kind: intern_kind + }), ))); } } @@ -532,7 +535,7 @@ fn report_validation_error<'tcx>( let bytes = ecx.print_alloc_bytes_for_diagnostics(alloc_id); let info = ecx.get_alloc_info(alloc_id); let raw_bytes = - errors::RawBytesNote { size: info.size.bytes(), align: info.align.bytes(), bytes }; + diagnostics::RawBytesNote { size: info.size.bytes(), align: info.align.bytes(), bytes }; crate::const_eval::report(ecx, error, move |diag, span, frames| { diag.span_label(span, "it is undefined behavior to use this value"); diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index e7e1dd2ec0fb0..c5da3253ef2c7 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -18,7 +18,7 @@ use rustc_target::callconv::FnAbi; use tracing::debug; use super::error::*; -use crate::errors::{LongRunning, LongRunningWarn}; +use crate::diagnostics::{LongRunning, LongRunningWarn}; use crate::interpret::{ self, AllocId, AllocInit, AllocRange, ConstAllocation, CtfeProvenance, FnArg, Frame, GlobalAlloc, ImmTy, InterpCx, InterpResult, OpTy, PlaceTy, Pointer, RangeSet, RetagMode, diff --git a/compiler/rustc_const_eval/src/errors.rs b/compiler/rustc_const_eval/src/diagnostics.rs similarity index 100% rename from compiler/rustc_const_eval/src/errors.rs rename to compiler/rustc_const_eval/src/diagnostics.rs diff --git a/compiler/rustc_const_eval/src/interpret/intern.rs b/compiler/rustc_const_eval/src/interpret/intern.rs index 2f27b7e5082f2..f74a85c7340ae 100644 --- a/compiler/rustc_const_eval/src/interpret/intern.rs +++ b/compiler/rustc_const_eval/src/interpret/intern.rs @@ -31,7 +31,7 @@ use tracing::{instrument, trace}; use super::{AllocId, Allocation, InterpCx, MPlaceTy, Machine, MemoryKind, PlaceTy, interp_ok}; use crate::const_eval::DummyMachine; -use crate::{const_eval, errors}; +use crate::{const_eval, diagnostics}; pub trait CompileTimeMachine<'tcx> = Machine< 'tcx, @@ -160,7 +160,8 @@ fn intern_as_new_static<'tcx>( tcx.set_nested_alloc_id_static(alloc_id, feed.def_id()); if tcx.is_thread_local_static(static_id.into()) { - tcx.dcx().emit_err(errors::NestedStaticInThreadLocal { span: tcx.def_span(static_id) }); + tcx.dcx() + .emit_err(diagnostics::NestedStaticInThreadLocal { span: tcx.def_span(static_id) }); } // These do not inherit the codegen attrs of the parent static allocation, since diff --git a/compiler/rustc_const_eval/src/interpret/stack.rs b/compiler/rustc_const_eval/src/interpret/stack.rs index 3e7c57a439c67..d291f1f6fdcbc 100644 --- a/compiler/rustc_const_eval/src/interpret/stack.rs +++ b/compiler/rustc_const_eval/src/interpret/stack.rs @@ -21,7 +21,7 @@ use super::{ MemPlaceMeta, MemoryKind, Operand, PlaceTy, Pointer, Provenance, ReturnAction, Scalar, from_known_layout, interp_ok, throw_ub, throw_unsup, }; -use crate::{enter_trace_span, errors}; +use crate::{diagnostics, enter_trace_span}; // The Phantomdata exists to prevent this type from being `Send`. If it were sent across a thread // boundary and dropped in the other thread, it would exit the span in the other thread. @@ -223,10 +223,10 @@ impl<'tcx> fmt::Display for FrameInfo<'tcx> { } impl<'tcx> FrameInfo<'tcx> { - pub(crate) fn as_note(&self, tcx: TyCtxt<'tcx>) -> errors::FrameNote { + pub(crate) fn as_note(&self, tcx: TyCtxt<'tcx>) -> diagnostics::FrameNote { let span = self.span; if tcx.def_key(self.instance.def_id()).disambiguated_data.data == DefPathData::Closure { - errors::FrameNote { + diagnostics::FrameNote { where_: "closure", span, instance: String::new(), @@ -238,7 +238,13 @@ impl<'tcx> FrameInfo<'tcx> { // Note: this triggers a `must_produce_diag` state, which means that if we ever get // here we must emit a diagnostic. We should never display a `FrameInfo` unless we // actually want to emit a warning or error to the user. - errors::FrameNote { where_: "instance", span, instance, times: 0, has_label: false } + diagnostics::FrameNote { + where_: "instance", + span, + instance, + times: 0, + has_label: false, + } } } } diff --git a/compiler/rustc_const_eval/src/lib.rs b/compiler/rustc_const_eval/src/lib.rs index 9b4d7fa4cce7a..5b63379edd332 100644 --- a/compiler/rustc_const_eval/src/lib.rs +++ b/compiler/rustc_const_eval/src/lib.rs @@ -12,7 +12,7 @@ pub mod check_consts; pub mod const_eval; -mod errors; +mod diagnostics; pub mod interpret; pub mod util; From cba2097424e043c961e5f714f6baf97313861cda Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sun, 12 Jul 2026 00:19:21 +0200 Subject: [PATCH 2/2] Rename `rustc_parse/src/errors.rs` into `rustc_parse/src/diagnostics.rs` --- .../src/{errors.rs => diagnostics.rs} | 0 compiler/rustc_parse/src/lexer/diagnostics.rs | 2 +- compiler/rustc_parse/src/lexer/mod.rs | 108 ++++--- .../src/lexer/unescape_error_reporting.rs | 4 +- .../rustc_parse/src/lexer/unicode_chars.rs | 2 +- compiler/rustc_parse/src/lib.rs | 2 +- compiler/rustc_parse/src/parser/asm.rs | 24 +- compiler/rustc_parse/src/parser/attr.rs | 8 +- .../rustc_parse/src/parser/diagnostics.rs | 2 +- compiler/rustc_parse/src/parser/expr.rs | 288 +++++++++--------- compiler/rustc_parse/src/parser/generics.rs | 20 +- compiler/rustc_parse/src/parser/item.rs | 158 ++++++---- compiler/rustc_parse/src/parser/mod.rs | 14 +- .../rustc_parse/src/parser/nonterminal.rs | 2 +- compiler/rustc_parse/src/parser/pat.rs | 4 +- compiler/rustc_parse/src/parser/path.rs | 14 +- compiler/rustc_parse/src/parser/stmt.rs | 39 +-- compiler/rustc_parse/src/parser/ty.rs | 42 +-- 18 files changed, 403 insertions(+), 330 deletions(-) rename compiler/rustc_parse/src/{errors.rs => diagnostics.rs} (100%) diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/diagnostics.rs similarity index 100% rename from compiler/rustc_parse/src/errors.rs rename to compiler/rustc_parse/src/diagnostics.rs diff --git a/compiler/rustc_parse/src/lexer/diagnostics.rs b/compiler/rustc_parse/src/lexer/diagnostics.rs index 947f3df179ffa..5c66d2be7dfdd 100644 --- a/compiler/rustc_parse/src/lexer/diagnostics.rs +++ b/compiler/rustc_parse/src/lexer/diagnostics.rs @@ -5,7 +5,7 @@ use rustc_span::Span; use rustc_span::source_map::SourceMap; use super::UnmatchedDelim; -use crate::errors::MismatchedClosingDelimiter; +use crate::diagnostics::MismatchedClosingDelimiter; use crate::pprust; #[derive(Default)] diff --git a/compiler/rustc_parse/src/lexer/mod.rs b/compiler/rustc_parse/src/lexer/mod.rs index 173a92fdbf759..1a30d5f1e79a0 100644 --- a/compiler/rustc_parse/src/lexer/mod.rs +++ b/compiler/rustc_parse/src/lexer/mod.rs @@ -17,7 +17,6 @@ use rustc_session::parse::ParseSess; use rustc_span::{BytePos, Pos, Span, Symbol, sym}; use tracing::debug; -use crate::errors; use crate::lexer::diagnostics::TokenTreeDiagInfo; use crate::lexer::unicode_chars::UNICODE_ARRAY; @@ -235,7 +234,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { let span = self.mk_sp(start, self.pos); self.psess.symbol_gallery.insert(sym, span); if !sym.can_be_raw() { - self.dcx().emit_err(errors::CannotBeRawIdent { span, ident: sym }); + self.dcx().emit_err(crate::diagnostics::CannotBeRawIdent { span, ident: sym }); } self.psess.raw_identifier_spans.push(span); token::Ident(sym, IdentIsRaw::Yes) @@ -302,7 +301,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { let suffix = if suffix_start < self.pos { let string = self.str_from(suffix_start); if string == "_" { - self.dcx().emit_err(errors::UnderscoreLiteralSuffix { + self.dcx().emit_err(crate::diagnostics::UnderscoreLiteralSuffix { span: self.mk_sp(suffix_start, self.pos), }); None @@ -363,7 +362,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { Symbol::intern(&self.str_from(ident_start)); if !lifetime_name_without_tick.can_be_raw() { self.dcx().emit_err( - errors::CannotBeRawLifetime { + crate::diagnostics::CannotBeRawLifetime { span, ident: lifetime_name_without_tick } @@ -387,7 +386,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, prefix_span, ast::CRATE_NODE_ID, - errors::RawPrefix { + crate::diagnostics::RawPrefix { label: prefix_span, suggestion: prefix_span.shrink_to_hi() }, @@ -457,7 +456,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { // way. let (token, sugg) = unicode_chars::check_for_substitution(self, start, c, repeats + 1); - self.dcx().emit_err(errors::UnknownTokenStart { + self.dcx().emit_err(crate::diagnostics::UnknownTokenStart { span: self.mk_sp(start, self.pos + Pos::from_usize(repeats * c.len_utf8())), escaped: escaped_char(c), sugg, @@ -465,7 +464,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { invisible: INVISIBLE_CHARACTERS.contains(&c), repeat: if repeats > 0 { swallow_next_invalid = repeats; - Some(errors::UnknownTokenRepeat { repeats }) + Some(crate::diagnostics::UnknownTokenRepeat { repeats }) } else { None }, @@ -517,17 +516,18 @@ impl<'psess, 'src> Lexer<'psess, 'src> { .collect(); let characters = spans .iter() - .map(|&(c, span)| errors::UnicodeCharNoteSub { + .map(|&(c, span)| crate::diagnostics::UnicodeCharNoteSub { span, c_debug: format!("{c:?}"), }) .collect(); - let suggestions = - (!spans.is_empty()).then_some(errors::UnicodeTextFlowSuggestion { + let suggestions = (!spans.is_empty()).then_some( + crate::diagnostics::UnicodeTextFlowSuggestion { spans: spans.iter().map(|(_c, span)| *span).collect(), - }); + }, + ); - errors::UnicodeTextFlow { + crate::diagnostics::UnicodeTextFlow { comment_span: span, characters, suggestions, @@ -608,19 +608,27 @@ impl<'psess, 'src> Lexer<'psess, 'src> { let label = label.to_string(); let count = spans.len(); - let labels = point_at_inner_spans - .then_some(errors::HiddenUnicodeCodepointsDiagLabels { spans: spans.clone() }); + let labels = + point_at_inner_spans.then_some(crate::diagnostics::HiddenUnicodeCodepointsDiagLabels { + spans: spans.clone(), + }); let sub = if point_at_inner_spans && !spans.is_empty() { - errors::HiddenUnicodeCodepointsDiagSub::Escape { spans } + crate::diagnostics::HiddenUnicodeCodepointsDiagSub::Escape { spans } } else { - errors::HiddenUnicodeCodepointsDiagSub::NoEscape { spans, is_doc_comment } + crate::diagnostics::HiddenUnicodeCodepointsDiagSub::NoEscape { spans, is_doc_comment } }; self.psess.buffer_lint( TEXT_DIRECTION_CODEPOINT_IN_LITERAL, span, ast::CRATE_NODE_ID, - errors::HiddenUnicodeCodepointsDiag { label, count, span_label: span, labels, sub }, + crate::diagnostics::HiddenUnicodeCodepointsDiag { + label, + count, + span_label: span, + labels, + sub, + }, ); } @@ -643,7 +651,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { BytePos(s[..real_start].rfind("\n").map_or(0, |i| i as u32 + 1)) + start; let span = self.mk_sp(line_start, frontmatter_opening_end_pos); let label_span = self.mk_sp(line_start, frontmatter_opening_pos); - self.dcx().emit_err(errors::FrontmatterInvalidOpeningPrecedingWhitespace { + self.dcx().emit_err(crate::diagnostics::FrontmatterInvalidOpeningPrecedingWhitespace { span, note_span: label_span, }); @@ -655,7 +663,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { frontmatter_opening_end_pos, frontmatter_opening_pos + BytePos(line_end as u32), ); - self.dcx().emit_err(errors::FrontmatterInvalidInfostring { span }); + self.dcx().emit_err(crate::diagnostics::FrontmatterInvalidInfostring { span }); } let last_line_start = real_s.rfind('\n').map_or(line_end, |i| i + 1); @@ -664,7 +672,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { if let Some(cr_offset) = content.find('\r') { let cr_pos = start + BytePos((real_start + line_end + cr_offset) as u32); let span = self.mk_sp(cr_pos, cr_pos + BytePos(1 as u32)); - self.dcx().emit_err(errors::BareCrFrontmatter { span }); + self.dcx().emit_err(crate::diagnostics::BareCrFrontmatter { span }); } let last_line = &real_s[last_line_start..]; @@ -676,7 +684,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { if !last_line_trimmed.starts_with("---") { let label_span = self.mk_sp(frontmatter_opening_pos, frontmatter_opening_end_pos); - self.dcx().emit_err(errors::FrontmatterUnclosed { + self.dcx().emit_err(crate::diagnostics::FrontmatterUnclosed { span: frontmatter_span, note_span: label_span, }); @@ -689,7 +697,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { let whitespace_end = last_line_start_pos + BytePos((last_line.len() - last_line_trimmed.len()) as u32); let label_span = self.mk_sp(last_line_start_pos, whitespace_end); - self.dcx().emit_err(errors::FrontmatterInvalidClosingPrecedingWhitespace { + self.dcx().emit_err(crate::diagnostics::FrontmatterInvalidClosingPrecedingWhitespace { span, note_span: label_span, }); @@ -702,7 +710,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { let opening = self.mk_sp(frontmatter_opening_pos, frontmatter_opening_end_pos); let last_line_close_pos = last_line_start_pos + BytePos(len_close as u32); let close = self.mk_sp(last_line_start_pos, last_line_close_pos); - self.dcx().emit_err(errors::FrontmatterLengthMismatch { + self.dcx().emit_err(crate::diagnostics::FrontmatterLengthMismatch { span, opening, close, @@ -713,12 +721,12 @@ impl<'psess, 'src> Lexer<'psess, 'src> { // Only up to 255 `-`s are allowed in code fences if u8::try_from(len_opening).is_err() { - self.dcx().emit_err(errors::FrontmatterTooManyDashes { len_opening }); + self.dcx().emit_err(crate::diagnostics::FrontmatterTooManyDashes { len_opening }); } if !rest.trim_matches(is_horizontal_whitespace).is_empty() { let span = self.mk_sp(last_line_start_pos, self.pos); - self.dcx().emit_err(errors::FrontmatterExtraCharactersAfterClose { span }); + self.dcx().emit_err(crate::diagnostics::FrontmatterExtraCharactersAfterClose { span }); } } @@ -736,7 +744,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { content_start + BytePos(idx as u32 + 1), ); let block = matches!(comment_kind, CommentKind::Block); - self.dcx().emit_err(errors::CrDocComment { span, block }); + self.dcx().emit_err(crate::diagnostics::CrDocComment { span, block }); } } @@ -858,7 +866,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { let mut kind = token::Integer; if empty_int { let span = self.mk_sp(start, end); - let guar = self.dcx().emit_err(errors::NoDigitsLiteral { span }); + let guar = self.dcx().emit_err(crate::diagnostics::NoDigitsLiteral { span }); kind = token::Err(guar); } else if matches!(base, Base::Binary | Base::Octal) { let base = base as u32; @@ -869,8 +877,9 @@ impl<'psess, 'src> Lexer<'psess, 'src> { start + BytePos::from_usize(2 + idx + c.len_utf8()), ); if c != '_' && c.to_digit(base).is_none() { - let guar = - self.dcx().emit_err(errors::InvalidDigitLiteral { span, base }); + let guar = self + .dcx() + .emit_err(crate::diagnostics::InvalidDigitLiteral { span, base }); kind = token::Err(guar); } } @@ -881,7 +890,7 @@ impl<'psess, 'src> Lexer<'psess, 'src> { let mut kind = token::Float; if empty_exponent { let span = self.mk_sp(start, self.pos); - let guar = self.dcx().emit_err(errors::EmptyExponentFloat { span }); + let guar = self.dcx().emit_err(crate::diagnostics::EmptyExponentFloat { span }); kind = token::Err(guar); } let base = match base { @@ -892,8 +901,9 @@ impl<'psess, 'src> Lexer<'psess, 'src> { }; if let Some(base) = base { let span = self.mk_sp(start, end); - let guar = - self.dcx().emit_err(errors::FloatLiteralUnsupportedBase { span, base }); + let guar = self + .dcx() + .emit_err(crate::diagnostics::FloatLiteralUnsupportedBase { span, base }); kind = token::Err(guar) } (kind, self.symbol_from_to(start, end)) @@ -1046,9 +1056,9 @@ impl<'psess, 'src> Lexer<'psess, 'src> { if expn_data.edition.at_least_rust_2021() { // In Rust 2021, this is a hard error. let sugg = if prefix == "rb" { - Some(errors::UnknownPrefixSugg::UseBr(prefix_span)) + Some(crate::diagnostics::UnknownPrefixSugg::UseBr(prefix_span)) } else if prefix == "rc" { - Some(errors::UnknownPrefixSugg::UseCr(prefix_span)) + Some(crate::diagnostics::UnknownPrefixSugg::UseCr(prefix_span)) } else if expn_data.is_root() { if self.cursor.first() == '\'' && let Some(start) = self.last_lifetime @@ -1059,21 +1069,27 @@ impl<'psess, 'src> Lexer<'psess, 'src> { // FIXME: An "unclosed `char`" error will be emitted already in some cases, // but it's hard to silence this error while not also silencing important cases // too. We should use the error stashing machinery instead. - Some(errors::UnknownPrefixSugg::MeantStr { start, end }) + Some(crate::diagnostics::UnknownPrefixSugg::MeantStr { start, end }) } else { - Some(errors::UnknownPrefixSugg::Whitespace(prefix_span.shrink_to_hi())) + Some(crate::diagnostics::UnknownPrefixSugg::Whitespace( + prefix_span.shrink_to_hi(), + )) } } else { None }; - self.dcx().emit_err(errors::UnknownPrefix { span: prefix_span, prefix, sugg }); + self.dcx().emit_err(crate::diagnostics::UnknownPrefix { + span: prefix_span, + prefix, + sugg, + }); } else { // Before Rust 2021, only emit a lint for migration. self.psess.buffer_lint( RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, prefix_span, ast::CRATE_NODE_ID, - errors::ReservedPrefix { + crate::diagnostics::ReservedPrefix { label: prefix_span, suggestion: prefix_span.shrink_to_hi(), prefix: prefix.to_string(), @@ -1134,14 +1150,14 @@ impl<'psess, 'src> Lexer<'psess, 'src> { let sugg = if span.from_expansion() { None } else { - Some(errors::GuardedStringSugg(space_span)) + Some(crate::diagnostics::GuardedStringSugg(space_span)) }; // In Edition 2024 and later, emit a hard error. let err = if is_string { - self.dcx().emit_err(errors::ReservedString { span, sugg }) + self.dcx().emit_err(crate::diagnostics::ReservedString { span, sugg }) } else { - self.dcx().emit_err(errors::ReservedMultihash { span, sugg }) + self.dcx().emit_err(crate::diagnostics::ReservedMultihash { span, sugg }) }; token::Literal(token::Lit { @@ -1157,9 +1173,10 @@ impl<'psess, 'src> Lexer<'psess, 'src> { ast::CRATE_NODE_ID, move |dcx, level| { if is_string { - errors::ReservedStringLint { suggestion: space_span }.into_diag(dcx, level) + crate::diagnostics::ReservedStringLint { suggestion: space_span } + .into_diag(dcx, level) } else { - errors::ReservedMultihashLint { suggestion: space_span } + crate::diagnostics::ReservedMultihashLint { suggestion: space_span } .into_diag(dcx, level) } }, @@ -1174,7 +1191,10 @@ impl<'psess, 'src> Lexer<'psess, 'src> { } fn report_too_many_hashes(&self, start: BytePos, num: u32) -> ! { - self.dcx().emit_fatal(errors::TooManyHashes { span: self.mk_sp(start, self.pos), num }); + self.dcx().emit_fatal(crate::diagnostics::TooManyHashes { + span: self.mk_sp(start, self.pos), + num, + }); } fn cook_quoted( diff --git a/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs b/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs index 099bd44e9a065..54c8f3c09ec48 100644 --- a/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs +++ b/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs @@ -8,7 +8,9 @@ use rustc_literal_escaper::{EscapeError, Mode}; use rustc_span::{BytePos, Span}; use tracing::debug; -use crate::errors::{MoreThanOneCharNote, MoreThanOneCharSugg, NoBraceUnicodeSub, UnescapeError}; +use crate::diagnostics::{ + MoreThanOneCharNote, MoreThanOneCharSugg, NoBraceUnicodeSub, UnescapeError, +}; pub(crate) fn emit_unescape_error( dcx: DiagCtxtHandle<'_>, diff --git a/compiler/rustc_parse/src/lexer/unicode_chars.rs b/compiler/rustc_parse/src/lexer/unicode_chars.rs index 751d13af4331b..826d193634a45 100644 --- a/compiler/rustc_parse/src/lexer/unicode_chars.rs +++ b/compiler/rustc_parse/src/lexer/unicode_chars.rs @@ -4,7 +4,7 @@ use rustc_span::{BytePos, Pos, Span, kw}; use super::Lexer; -use crate::errors::TokenSubstitution; +use crate::diagnostics::TokenSubstitution; use crate::token; #[rustfmt::skip] // for line breaks diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs index 7805994b441b8..74f433f5bf2e9 100644 --- a/compiler/rustc_parse/src/lib.rs +++ b/compiler/rustc_parse/src/lib.rs @@ -33,7 +33,7 @@ use crate::lexer::StripTokens; pub mod lexer; -mod errors; +mod diagnostics; // Make sure that the Unicode version of the dependencies is the same. const _: () = { diff --git a/compiler/rustc_parse/src/parser/asm.rs b/compiler/rustc_parse/src/parser/asm.rs index 11460e775d36d..5c177af086565 100644 --- a/compiler/rustc_parse/src/parser/asm.rs +++ b/compiler/rustc_parse/src/parser/asm.rs @@ -2,7 +2,7 @@ use rustc_ast::{self as ast, AsmMacro}; use rustc_span::{Span, Symbol, kw}; use super::{ExpKeywordPair, ForceCollect, IdentIsRaw, Trailing, UsePreAttrPos}; -use crate::{PResult, Parser, errors, exp, token}; +use crate::{PResult, Parser, diagnostics, exp, token}; /// An argument to one of the `asm!` macros. The argument is syntactically valid, but is otherwise /// not validated at all. @@ -84,7 +84,7 @@ fn eat_operand_keyword<'a>( if p.eat_keyword_noexpect(exp.kw) { // in gets printed as `r#in` otherwise let symbol = if exp.kw == kw::In { "in" } else { exp.kw.as_str() }; - Err(p.dcx().create_err(errors::AsmUnsupportedOperand { + Err(p.dcx().create_err(diagnostics::AsmUnsupportedOperand { span, symbol, macro_name: asm_macro.macro_name(), @@ -104,7 +104,7 @@ fn parse_asm_operand<'a>( Ok(Some(if eat_operand_keyword(p, exp!(In), asm_macro)? { let reg = parse_reg(p)?; if p.eat_keyword(exp!(Underscore)) { - let err = dcx.create_err(errors::AsmUnderscoreInput { span: p.token.span }); + let err = dcx.create_err(diagnostics::AsmUnderscoreInput { span: p.token.span }); return Err(err); } let expr = p.parse_expr()?; @@ -120,7 +120,7 @@ fn parse_asm_operand<'a>( } else if eat_operand_keyword(p, exp!(Inout), asm_macro)? { let reg = parse_reg(p)?; if p.eat_keyword(exp!(Underscore)) { - let err = dcx.create_err(errors::AsmUnderscoreInput { span: p.token.span }); + let err = dcx.create_err(diagnostics::AsmUnderscoreInput { span: p.token.span }); return Err(err); } let expr = p.parse_expr()?; @@ -134,7 +134,7 @@ fn parse_asm_operand<'a>( } else if eat_operand_keyword(p, exp!(Inlateout), asm_macro)? { let reg = parse_reg(p)?; if p.eat_keyword(exp!(Underscore)) { - let err = dcx.create_err(errors::AsmUnderscoreInput { span: p.token.span }); + let err = dcx.create_err(diagnostics::AsmUnderscoreInput { span: p.token.span }); return Err(err); } let expr = p.parse_expr()?; @@ -154,7 +154,7 @@ fn parse_asm_operand<'a>( } else if p.eat_keyword(exp!(Sym)) { let expr = p.parse_expr()?; let ast::ExprKind::Path(qself, path) = &expr.kind else { - let err = dcx.create_err(errors::AsmSymNoPath { span: expr.span }); + let err = dcx.create_err(diagnostics::AsmSymNoPath { span: expr.span }); return Err(err); }; let sym = @@ -174,7 +174,7 @@ pub fn parse_asm_args<'a>( let dcx = p.dcx(); if p.token == token::Eof { - return Err(dcx.create_err(errors::AsmRequiresTemplate { span: sp })); + return Err(dcx.create_err(diagnostics::AsmRequiresTemplate { span: sp })); } let mut args = Vec::new(); @@ -193,7 +193,7 @@ pub fn parse_asm_args<'a>( if !p.eat(exp!(Comma)) { if allow_templates { // After a template string, we always expect *only* a comma... - return Err(dcx.create_err(errors::AsmExpectedComma { span: p.token.span })); + return Err(dcx.create_err(diagnostics::AsmExpectedComma { span: p.token.span })); } else { // ...after that delegate to `expect` to also include the other expected tokens. return Err(p.expect(exp!(Comma)).err().unwrap()); @@ -265,7 +265,7 @@ pub fn parse_asm_args<'a>( ) => {} ast::ExprKind::MacCall(..) => {} _ => { - let err = dcx.create_err(errors::AsmExpectedOther { + let err = dcx.create_err(diagnostics::AsmExpectedOther { span: template.span, is_inline_asm: matches!(asm_macro, AsmMacro::Asm), }); @@ -340,7 +340,7 @@ fn parse_clobber_abi<'a>(p: &mut Parser<'a>) -> PResult<'a, Vec<(Symbol, Span)>> p.expect(exp!(OpenParen))?; if p.eat(exp!(CloseParen)) { - return Err(p.dcx().create_err(errors::NonABI { span: p.token.span })); + return Err(p.dcx().create_err(diagnostics::NonABI { span: p.token.span })); } let mut new_abis = Vec::new(); @@ -351,7 +351,7 @@ fn parse_clobber_abi<'a>(p: &mut Parser<'a>) -> PResult<'a, Vec<(Symbol, Span)>> } Err(opt_lit) => { let span = opt_lit.map_or(p.token.span, |lit| lit.span); - return Err(p.dcx().create_err(errors::AsmExpectedStringLiteral { span })); + return Err(p.dcx().create_err(diagnostics::AsmExpectedStringLiteral { span })); } }; @@ -373,7 +373,7 @@ fn parse_reg<'a>(p: &mut Parser<'a>) -> PResult<'a, ast::InlineAsmRegOrRegClass> ast::InlineAsmRegOrRegClass::Reg(symbol) } _ => { - return Err(p.dcx().create_err(errors::ExpectedRegisterClassOrExplicitRegister { + return Err(p.dcx().create_err(diagnostics::ExpectedRegisterClassOrExplicitRegister { span: p.token.span, })); } diff --git a/compiler/rustc_parse/src/parser/attr.rs b/compiler/rustc_parse/src/parser/attr.rs index 4d92b8273d5c9..5b0d99242f440 100644 --- a/compiler/rustc_parse/src/parser/attr.rs +++ b/compiler/rustc_parse/src/parser/attr.rs @@ -13,7 +13,7 @@ use super::{ Trailing, UsePreAttrPos, }; use crate::parser::FnContext; -use crate::{errors, exp}; +use crate::{diagnostics, exp}; // Public for rustfmt usage #[derive(Debug)] @@ -412,7 +412,7 @@ impl<'a> Parser<'a> { debug!("checking if {:?} is unsuffixed", lit); if !lit.kind.is_unsuffixed() { - self.dcx().emit_err(errors::SuffixedLiteralInAttribute { span: lit.span }); + self.dcx().emit_err(diagnostics::SuffixedLiteralInAttribute { span: lit.span }); } Ok(lit) @@ -507,7 +507,7 @@ impl<'a> Parser<'a> { Err(err) => err.cancel(), // we provide a better error below } - let mut err = errors::InvalidMetaItem { + let mut err = diagnostics::InvalidMetaItem { span: self.token.span, descr: super::token_descr(&self.token), quote_ident_sugg: None, @@ -523,7 +523,7 @@ impl<'a> Parser<'a> { while let token::Ident(..) = self.token.kind { self.bump(); } - err.quote_ident_sugg = Some(errors::InvalidMetaItemQuoteIdentSugg { + err.quote_ident_sugg = Some(diagnostics::InvalidMetaItemQuoteIdentSugg { before, after: self.prev_token.span.shrink_to_hi(), }); diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 254e7e410f579..e0d30f84c7e82 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -26,7 +26,7 @@ use super::{ BlockMode, CommaRecoveryMode, ExpTokenPair, Parser, PathStyle, Restrictions, SemiColonMode, SeqSep, TokenType, }; -use crate::errors::{ +use crate::diagnostics::{ AddParen, AmbiguousPlus, AsyncMoveBlockIn2015, AsyncUseBlockIn2015, AttributeOnParamType, AwaitSuggestion, BadQPathStage2, BadTypePlus, BadTypePlusSub, ColonAsSemi, ComparisonOperatorsCannotBeChained, ComparisonOperatorsCannotBeChainedSugg, diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index e151899a57228..e899bf1627681 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -36,7 +36,7 @@ use super::{ AttrWrapper, BlockMode, ClosureSpans, ExpTokenPair, ForceCollect, Parser, PathStyle, Restrictions, SemiColonMode, SeqSep, TokenType, Trailing, UsePreAttrPos, }; -use crate::{errors, exp, maybe_recover_from_interpolated_ty_qpath}; +use crate::{diagnostics, exp, maybe_recover_from_interpolated_ty_qpath}; #[derive(Debug)] pub(super) enum DestructuredFloat { @@ -196,10 +196,10 @@ impl<'a> Parser<'a> { let sp = op.span.to(self.token.span); let sugg = bop.as_str().into(); let invalid = format!("{sugg}="); - self.dcx().emit_err(errors::InvalidComparisonOperator { + self.dcx().emit_err(diagnostics::InvalidComparisonOperator { span: sp, invalid: invalid.clone(), - sub: errors::InvalidComparisonOperatorSub::Correctable { + sub: diagnostics::InvalidComparisonOperatorSub::Correctable { span: sp, invalid, correct: sugg, @@ -214,10 +214,10 @@ impl<'a> Parser<'a> { && self.prev_token.span.hi() == self.token.span.lo() { let sp = op.span.to(self.token.span); - self.dcx().emit_err(errors::InvalidComparisonOperator { + self.dcx().emit_err(diagnostics::InvalidComparisonOperator { span: sp, invalid: "<>".into(), - sub: errors::InvalidComparisonOperatorSub::Correctable { + sub: diagnostics::InvalidComparisonOperatorSub::Correctable { span: sp, invalid: "<>".into(), correct: "!=".into(), @@ -232,10 +232,10 @@ impl<'a> Parser<'a> { && self.prev_token.span.hi() == self.token.span.lo() { let sp = op.span.to(self.token.span); - self.dcx().emit_err(errors::InvalidComparisonOperator { + self.dcx().emit_err(diagnostics::InvalidComparisonOperator { span: sp, invalid: "<=>".into(), - sub: errors::InvalidComparisonOperatorSub::Spaceship(sp), + sub: diagnostics::InvalidComparisonOperatorSub::Spaceship(sp), }); self.bump(); } @@ -344,7 +344,7 @@ impl<'a> Parser<'a> { /// but the next token implies this should be parsed as an expression. /// For example: `if let Some(x) = x { x } else { 0 } / 2`. fn error_found_expr_would_be_stmt(&self, lhs: &Expr) { - self.dcx().emit_err(errors::FoundExprWouldBeStmt { + self.dcx().emit_err(diagnostics::FoundExprWouldBeStmt { span: self.token.span, token: pprust::token_to_string(&self.token), suggestion: ExprParenthesesNeeded::surrounding(lhs.span), @@ -384,18 +384,18 @@ impl<'a> Parser<'a> { (None, Some((Ident { name: sym::and, span }, IdentIsRaw::No))) if self.may_recover() => { - self.dcx().emit_err(errors::InvalidLogicalOperator { + self.dcx().emit_err(diagnostics::InvalidLogicalOperator { span: self.token.span, incorrect: "and".into(), - sub: errors::InvalidLogicalOperatorSub::Conjunction(self.token.span), + sub: diagnostics::InvalidLogicalOperatorSub::Conjunction(self.token.span), }); (AssocOp::Binary(BinOpKind::And), span) } (None, Some((Ident { name: sym::or, span }, IdentIsRaw::No))) if self.may_recover() => { - self.dcx().emit_err(errors::InvalidLogicalOperator { + self.dcx().emit_err(diagnostics::InvalidLogicalOperator { span: self.token.span, incorrect: "or".into(), - sub: errors::InvalidLogicalOperatorSub::Disjunction(self.token.span), + sub: diagnostics::InvalidLogicalOperatorSub::Disjunction(self.token.span), }); (AssocOp::Binary(BinOpKind::Or), span) } @@ -450,7 +450,7 @@ impl<'a> Parser<'a> { /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`. fn parse_expr_prefix_range(&mut self, attrs: AttrWrapper) -> PResult<'a, Box> { if !attrs.is_empty() { - let err = errors::DotDotRangeAttribute { span: self.token.span }; + let err = diagnostics::DotDotRangeAttribute { span: self.token.span }; self.dcx().emit_err(err); } @@ -524,7 +524,7 @@ impl<'a> Parser<'a> { } // `+lit` token::Plus if this.look_ahead(1, |tok| tok.is_numeric_lit()) => { - let mut err = errors::LeadingPlusNotSupported { + let mut err = diagnostics::LeadingPlusNotSupported { span: lo, remove_plus: None, add_parentheses: None, @@ -589,7 +589,7 @@ impl<'a> Parser<'a> { /// Recover on `~expr` in favor of `!expr`. fn recover_tilde_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> { - self.dcx().emit_err(errors::TildeAsUnaryOperator(lo)); + self.dcx().emit_err(diagnostics::TildeAsUnaryOperator(lo)); self.parse_expr_unary(lo, UnOp::Not) } @@ -601,8 +601,8 @@ impl<'a> Parser<'a> { // Make a multipart suggestion instead of `span_to_snippet` in case source isn't available let box_kw_and_lo = box_kw.until(self.interpolated_or_expr_span(&expr)); let hi = span.shrink_to_hi(); - let sugg = errors::AddBoxNew { box_kw_and_lo, hi }; - let guar = self.dcx().emit_err(errors::BoxSyntaxRemoved { span, sugg }); + let sugg = diagnostics::AddBoxNew { box_kw_and_lo, hi }; + let guar = self.dcx().emit_err(diagnostics::BoxSyntaxRemoved { span, sugg }); Ok((span, ExprKind::Err(guar))) } @@ -632,14 +632,14 @@ impl<'a> Parser<'a> { let negated_token = self.look_ahead(1, |t| *t); let sub_diag = if negated_token.is_numeric_lit() { - errors::NotAsNegationOperatorSub::SuggestNotBitwise + diagnostics::NotAsNegationOperatorSub::SuggestNotBitwise } else if negated_token.is_bool_lit() { - errors::NotAsNegationOperatorSub::SuggestNotLogical + diagnostics::NotAsNegationOperatorSub::SuggestNotLogical } else { - errors::NotAsNegationOperatorSub::SuggestNotDefault + diagnostics::NotAsNegationOperatorSub::SuggestNotDefault }; - self.dcx().emit_err(errors::NotAsNegationOperator { + self.dcx().emit_err(diagnostics::NotAsNegationOperator { negated: negated_token.span, negated_desc: super::token_descr(&negated_token), // Span the `not` plus trailing whitespace to avoid @@ -710,7 +710,7 @@ impl<'a> Parser<'a> { match self.parse_expr_labeled(label, false) { Ok(expr) => { type_err.cancel(); - self.dcx().emit_err(errors::MalformedLoopLabel { + self.dcx().emit_err(diagnostics::MalformedLoopLabel { span: label.ident.span, suggestion: label.ident.span.shrink_to_lo(), }); @@ -737,25 +737,27 @@ impl<'a> Parser<'a> { let args_span = self.look_ahead(1, |t| t.span).to(span_after_type); match self.token.kind { token::Lt => { - self.dcx().emit_err(errors::ComparisonInterpretedAsGeneric { + self.dcx().emit_err(diagnostics::ComparisonInterpretedAsGeneric { comparison: self.token.span, r#type: pprust::path_to_string(&path), args: args_span, - suggestion: errors::ComparisonInterpretedAsGenericSugg { + suggestion: diagnostics::ComparisonInterpretedAsGenericSugg { + left: expr.span.shrink_to_lo(), + right: expr.span.shrink_to_hi(), + }, + }) + } + token::Shl => { + self.dcx().emit_err(diagnostics::ShiftInterpretedAsGeneric { + shift: self.token.span, + r#type: pprust::path_to_string(&path), + args: args_span, + suggestion: diagnostics::ShiftInterpretedAsGenericSugg { left: expr.span.shrink_to_lo(), right: expr.span.shrink_to_hi(), }, }) } - token::Shl => self.dcx().emit_err(errors::ShiftInterpretedAsGeneric { - shift: self.token.span, - r#type: pprust::path_to_string(&path), - args: args_span, - suggestion: errors::ShiftInterpretedAsGenericSugg { - left: expr.span.shrink_to_lo(), - right: expr.span.shrink_to_hi(), - }, - }), _ => { // We can end up here even without `<` being the next token, for // example because `parse_ty_no_plus` returns `Err` on keywords, @@ -867,7 +869,8 @@ impl<'a> Parser<'a> { } fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) { - self.dcx().emit_err(errors::LifetimeInBorrowExpression { span, lifetime_span: lt_span }); + self.dcx() + .emit_err(diagnostics::LifetimeInBorrowExpression { span, lifetime_span: lt_span }); } /// Parse `mut?` or `[ raw | pin ] [ const | mut ]`. @@ -928,7 +931,7 @@ impl<'a> Parser<'a> { // Recovery for `expr->suffix`. self.bump(); let span = self.prev_token.span; - self.dcx().emit_err(errors::ExprRArrowCall { span }); + self.dcx().emit_err(diagnostics::ExprRArrowCall { span }); true } else { self.eat(exp!(Dot)) @@ -1052,7 +1055,7 @@ impl<'a> Parser<'a> { } _ => (span, actual), }; - self.dcx().emit_err(errors::UnexpectedTokenAfterDot { span, actual }); + self.dcx().emit_err(diagnostics::UnexpectedTokenAfterDot { span, actual }); } /// We need an identifier or integer, but the next token is a float. @@ -1169,7 +1172,7 @@ impl<'a> Parser<'a> { // Parse this both to give helpful error messages and to // verify it can be done with this parser setup. ExprKind::Index(ref left, ref _right, span) => { - self.dcx().emit_err(errors::ArrayIndexInOffsetOf(span)); + self.dcx().emit_err(diagnostics::ArrayIndexInOffsetOf(span)); current = left; } ExprKind::Lit(token::Lit { @@ -1178,7 +1181,7 @@ impl<'a> Parser<'a> { suffix, }) => { if let Some(suffix) = suffix { - self.dcx().emit_err(errors::InvalidLiteralSuffixOnTupleIndex { + self.dcx().emit_err(diagnostics::InvalidLiteralSuffixOnTupleIndex { span: current.span, suffix, }); @@ -1221,14 +1224,14 @@ impl<'a> Parser<'a> { fields.insert(start_idx, *ident) } _ => { - self.dcx().emit_err(errors::InvalidOffsetOf(current.span)); + self.dcx().emit_err(diagnostics::InvalidOffsetOf(current.span)); break; } } break; } _ => { - self.dcx().emit_err(errors::InvalidOffsetOf(current.span)); + self.dcx().emit_err(diagnostics::InvalidOffsetOf(current.span)); break; } } @@ -1238,12 +1241,12 @@ impl<'a> Parser<'a> { break; } else if trailing_dot.is_none() { // This loop should only repeat if there is a trailing dot. - self.dcx().emit_err(errors::InvalidOffsetOf(self.token.span)); + self.dcx().emit_err(diagnostics::InvalidOffsetOf(self.token.span)); break; } } if let Some(dot) = trailing_dot { - self.dcx().emit_err(errors::InvalidOffsetOf(dot)); + self.dcx().emit_err(diagnostics::InvalidOffsetOf(dot)); } Ok(fields.into_iter().collect()) } @@ -1257,8 +1260,10 @@ impl<'a> Parser<'a> { suffix: Option, ) -> Box { if let Some(suffix) = suffix { - self.dcx() - .emit_err(errors::InvalidLiteralSuffixOnTupleIndex { span: ident_span, suffix }); + self.dcx().emit_err(diagnostics::InvalidLiteralSuffixOnTupleIndex { + span: ident_span, + suffix, + }); } self.mk_expr(lo.to(ident_span), ExprKind::Field(base, Ident::new(field, ident_span))) } @@ -1343,14 +1348,14 @@ impl<'a> Parser<'a> { err.cancel(); let type_str = pprust::path_to_string(&path); self.dcx() - .create_err(errors::ParenthesesWithStructFields { + .create_err(diagnostics::ParenthesesWithStructFields { span, - braces_for_struct: errors::BracesForStructLiteral { + braces_for_struct: diagnostics::BracesForStructLiteral { first: open_paren, second: close_paren, r#type: type_str.clone(), }, - no_fields_for_fn: errors::NoFieldsForFnCall { + no_fields_for_fn: diagnostics::NoFieldsForFnCall { r#type: type_str, fields: fields .into_iter() @@ -1442,7 +1447,7 @@ impl<'a> Parser<'a> { if let Some(args) = seg.args { // See `StashKey::GenericInFieldExpr` for more info on why we stash this. self.dcx() - .create_err(errors::FieldExpressionWithGeneric(args.span())) + .create_err(diagnostics::FieldExpressionWithGeneric(args.span())) .stash(seg.ident.span, StashKey::GenericInFieldExpr); } @@ -1707,7 +1712,7 @@ impl<'a> Parser<'a> { let (span, kind) = if self.eat(exp!(Bang)) { // MACRO INVOCATION expression if qself.is_some() { - self.dcx().emit_err(errors::MacroInvocationWithQualifiedPath(path.span)); + self.dcx().emit_err(diagnostics::MacroInvocationWithQualifiedPath(path.span)); } let lo = path.span; let mac = Box::new(MacCall { path, args: self.parse_delim_args()? }); @@ -1752,7 +1757,7 @@ impl<'a> Parser<'a> { { let (lit, _) = self.recover_unclosed_char(label_.ident, Parser::mk_token_lit_char, |self_| { - self_.dcx().create_err(errors::UnexpectedTokenAfterLabel { + self_.dcx().create_err(diagnostics::UnexpectedTokenAfterLabel { span: self_.token.span, remove_label: None, enclose_in_block: None, @@ -1764,7 +1769,7 @@ impl<'a> Parser<'a> { && (self.check_noexpect(&TokenKind::Comma) || self.check_noexpect(&TokenKind::Gt)) { // We're probably inside of a `Path<'a>` that needs a turbofish - let guar = self.dcx().emit_err(errors::UnexpectedTokenAfterLabel { + let guar = self.dcx().emit_err(diagnostics::UnexpectedTokenAfterLabel { span: self.token.span, remove_label: None, enclose_in_block: None, @@ -1772,7 +1777,7 @@ impl<'a> Parser<'a> { consume_colon = false; Ok(self.mk_expr_err(lo, guar)) } else { - let mut err = errors::UnexpectedTokenAfterLabel { + let mut err = diagnostics::UnexpectedTokenAfterLabel { span: self.token.span, remove_label: None, enclose_in_block: None, @@ -1809,7 +1814,7 @@ impl<'a> Parser<'a> { return expr; } - err.enclose_in_block = Some(errors::UnexpectedTokenAfterLabelSugg { + err.enclose_in_block = Some(diagnostics::UnexpectedTokenAfterLabelSugg { left: span.shrink_to_lo(), right: span.shrink_to_hi(), }); @@ -1825,7 +1830,7 @@ impl<'a> Parser<'a> { }?; if !ate_colon && consume_colon { - self.dcx().emit_err(errors::RequireColonAfterLabeledExpression { + self.dcx().emit_err(diagnostics::RequireColonAfterLabeledExpression { span: expr.span, label: lo, label_end: lo.between(tok_sp), @@ -1874,7 +1879,7 @@ impl<'a> Parser<'a> { self.bump(); // `catch` let span = lo.to(self.prev_token.span); - self.dcx().emit_err(errors::DoCatchSyntaxRemoved { span }); + self.dcx().emit_err(diagnostics::DoCatchSyntaxRemoved { span }); self.parse_try_block(lo) } @@ -1934,9 +1939,9 @@ impl<'a> Parser<'a> { // The value expression can be a labeled loop, see issue #86948, e.g.: // `loop { break 'label: loop { break 'label 42; }; }` let lexpr = self.parse_expr_labeled(label, true)?; - self.dcx().emit_err(errors::LabeledLoopInBreak { + self.dcx().emit_err(diagnostics::LabeledLoopInBreak { span: lexpr.span, - sub: errors::WrapInParentheses::Expression { + sub: diagnostics::WrapInParentheses::Expression { left: lexpr.span.shrink_to_lo(), right: lexpr.span.shrink_to_hi(), }, @@ -1963,8 +1968,8 @@ impl<'a> Parser<'a> { BREAK_WITH_LABEL_AND_LOOP, lo.to(expr.span), ast::CRATE_NODE_ID, - errors::BreakWithLabelAndLoop { - sub: errors::BreakWithLabelAndLoopSub { + diagnostics::BreakWithLabelAndLoop { + sub: diagnostics::BreakWithLabelAndLoopSub { left: span.shrink_to_lo(), right: span.shrink_to_hi(), }, @@ -2046,7 +2051,8 @@ impl<'a> Parser<'a> { self.bump(); // `#` let Some((ident, IdentIsRaw::No)) = self.token.ident() else { - let err = self.dcx().create_err(errors::ExpectedBuiltinIdent { span: self.token.span }); + let err = + self.dcx().create_err(diagnostics::ExpectedBuiltinIdent { span: self.token.span }); return Err(err); }; self.psess.gated_spans.gate(sym::builtin_syntax, ident.span); @@ -2056,7 +2062,7 @@ impl<'a> Parser<'a> { let ret = if let Some(res) = parse(self, lo, ident)? { Ok(res) } else { - let err = self.dcx().create_err(errors::UnknownBuiltinConstruct { + let err = self.dcx().create_err(diagnostics::UnknownBuiltinConstruct { span: lo.to(ident.span), name: ident, }); @@ -2205,7 +2211,7 @@ impl<'a> Parser<'a> { } }); if let Some(recovered) = recovered { - self.dcx().emit_err(errors::FloatLiteralRequiresIntegerPart { + self.dcx().emit_err(diagnostics::FloatLiteralRequiresIntegerPart { span: recovered.span, suggestion: recovered.span.shrink_to_lo(), }); @@ -2339,9 +2345,9 @@ impl<'a> Parser<'a> { let mut snapshot = self.create_snapshot_for_diagnostic(); match snapshot.parse_expr_array_or_repeat(exp!(CloseBrace)) { Ok(arr) => { - let guar = self.dcx().emit_err(errors::ArrayBracketsInsteadOfBraces { + let guar = self.dcx().emit_err(diagnostics::ArrayBracketsInsteadOfBraces { span: arr.span, - sub: errors::ArrayBracketsInsteadOfBracesSugg { + sub: diagnostics::ArrayBracketsInsteadOfBracesSugg { left: lo, right: snapshot.prev_token.span, }, @@ -2387,7 +2393,7 @@ impl<'a> Parser<'a> { .span_to_snippet(snapshot.token.span) .is_ok_and(|snippet| snippet == "]") => { - return Err(self.dcx().create_err(errors::MissingSemicolonBeforeArray { + return Err(self.dcx().create_err(diagnostics::MissingSemicolonBeforeArray { open_delim: open_delim_span, semicolon: prev_span.shrink_to_hi(), })); @@ -2413,10 +2419,10 @@ impl<'a> Parser<'a> { } if self.token.is_metavar_block() { - self.dcx().emit_err(errors::InvalidBlockMacroSegment { + self.dcx().emit_err(diagnostics::InvalidBlockMacroSegment { span: self.token.span, context: lo.to(self.token.span), - wrap: errors::WrapInExplicitBlock { + wrap: diagnostics::WrapInExplicitBlock { lo: self.token.span.shrink_to_lo(), hi: self.token.span.shrink_to_hi(), }, @@ -2594,7 +2600,7 @@ impl<'a> Parser<'a> { let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo); Err(self .dcx() - .create_err(errors::AsyncMoveOrderIncorrect { span: move_async_span })) + .create_err(diagnostics::AsyncMoveOrderIncorrect { span: move_async_span })) } else { Ok(CaptureBy::Value { move_kw: move_kw_span }) } @@ -2604,7 +2610,9 @@ impl<'a> Parser<'a> { // Check for `use async` and recover if self.check_keyword(exp!(Async)) { let use_async_span = self.token.span.with_lo(self.prev_token.span.data().lo); - Err(self.dcx().create_err(errors::AsyncUseOrderIncorrect { span: use_async_span })) + Err(self + .dcx() + .create_err(diagnostics::AsyncUseOrderIncorrect { span: use_async_span })) } else { Ok(CaptureBy::Use { use_kw: use_kw_span }) } @@ -2686,10 +2694,10 @@ impl<'a> Parser<'a> { ExprKind::Binary(Spanned { span: binop_span, .. }, _, right) if let ExprKind::Block(_, None) = right.kind => { - let guar = this.dcx().emit_err(errors::IfExpressionMissingThenBlock { + let guar = this.dcx().emit_err(diagnostics::IfExpressionMissingThenBlock { if_span: lo, missing_then_block_sub: - errors::IfExpressionMissingThenBlockSub::UnfinishedCondition( + diagnostics::IfExpressionMissingThenBlockSub::UnfinishedCondition( cond_span.shrink_to_lo().to(*binop_span), ), let_else_sub: None, @@ -2697,7 +2705,7 @@ impl<'a> Parser<'a> { std::mem::replace(right, this.mk_expr_err(binop_span.shrink_to_hi(), guar)) } ExprKind::Block(_, None) => { - let guar = this.dcx().emit_err(errors::IfExpressionMissingCondition { + let guar = this.dcx().emit_err(diagnostics::IfExpressionMissingCondition { if_span: lo.with_neighbor(cond.span).shrink_to_hi(), block_span: self.psess.source_map().start_point(cond_span), }); @@ -2719,13 +2727,14 @@ impl<'a> Parser<'a> { block } else { let let_else_sub = matches!(cond.kind, ExprKind::Let(..)) - .then(|| errors::IfExpressionLetSomeSub { if_span: lo.until(cond_span) }); + .then(|| diagnostics::IfExpressionLetSomeSub { if_span: lo.until(cond_span) }); - let guar = self.dcx().emit_err(errors::IfExpressionMissingThenBlock { + let guar = self.dcx().emit_err(diagnostics::IfExpressionMissingThenBlock { if_span: lo, - missing_then_block_sub: errors::IfExpressionMissingThenBlockSub::AddThenBlock( - cond_span.shrink_to_hi(), - ), + missing_then_block_sub: + diagnostics::IfExpressionMissingThenBlockSub::AddThenBlock( + cond_span.shrink_to_hi(), + ), let_else_sub, }); self.mk_block_err(cond_span.shrink_to_hi(), guar) @@ -2806,9 +2815,9 @@ impl<'a> Parser<'a> { /// Parses a `let $pat = $expr` pseudo-expression. fn parse_expr_let(&mut self, restrictions: Restrictions) -> PResult<'a, Box> { let recovered: Recovered = if !restrictions.contains(Restrictions::ALLOW_LET) { - let err = errors::ExpectedExpressionFoundLet { + let err = diagnostics::ExpectedExpressionFoundLet { span: self.token.span, - reason: errors::ForbiddenLetReason::OtherForbidden, + reason: diagnostics::ForbiddenLetReason::OtherForbidden, missing_let: None, comparison: None, }; @@ -2830,7 +2839,7 @@ impl<'a> Parser<'a> { CommaRecoveryMode::LikelyTuple, )?; if self.token == token::EqEq { - self.dcx().emit_err(errors::ExpectedEqForLetExpr { + self.dcx().emit_err(diagnostics::ExpectedEqForLetExpr { span: self.token.span, sugg_span: self.token.span, }); @@ -2898,7 +2907,7 @@ impl<'a> Parser<'a> { || matches!(cond.kind, ExprKind::MacCall(..))) => { - self.dcx().emit_err(errors::ExpectedElseBlock { + self.dcx().emit_err(diagnostics::ExpectedElseBlock { first_tok_span, first_tok, else_span, @@ -2934,7 +2943,7 @@ impl<'a> Parser<'a> { let attributes = x0.span.until(branch_span); let last = xn.span; let ctx = if is_ctx_else { "else" } else { "if" }; - self.dcx().emit_err(errors::OuterAttributeNotAllowedOnIfElse { + self.dcx().emit_err(diagnostics::OuterAttributeNotAllowedOnIfElse { last, branch_span, ctx_span, @@ -2949,7 +2958,7 @@ impl<'a> Parser<'a> { && let BinOpKind::And = binop && let ExprKind::If(cond, ..) = &right.kind { - Err(self.dcx().create_err(errors::UnexpectedIfWithIf( + Err(self.dcx().create_err(diagnostics::UnexpectedIfWithIf( binop_span.shrink_to_hi().to(cond.span.shrink_to_lo()), ))) } else { @@ -3000,12 +3009,12 @@ impl<'a> Parser<'a> { let right = self.prev_token.span.between(self.look_ahead(1, |t| t.span)); self.bump(); // ) err.cancel(); - self.dcx().emit_err(errors::ParenthesesInForHead { + self.dcx().emit_err(diagnostics::ParenthesesInForHead { span, // With e.g. `for (x) in y)` this would replace `(x) in y)` // with `x) in y)` which is syntactically invalid. // However, this is prevented before we get here. - sugg: errors::ParenthesesInForHeadSugg { left, right }, + sugg: diagnostics::ParenthesesInForHeadSugg { left, right }, }); Ok((self.mk_pat(start_span.to(right), ast::PatKind::Wild), expr)) } else { @@ -3041,9 +3050,9 @@ impl<'a> Parser<'a> { && self.token.kind != token::OpenBrace && self.may_recover() { - let guar = self - .dcx() - .emit_err(errors::MissingExpressionInForLoop { span: expr.span.shrink_to_lo() }); + let guar = self.dcx().emit_err(diagnostics::MissingExpressionInForLoop { + span: expr.span.shrink_to_lo(), + }); let err_expr = self.mk_expr(expr.span, ExprKind::Err(guar)); let block = self.mk_block(thin_vec![], BlockCheckMode::Default, self.prev_token.span); return Ok(self.mk_expr( @@ -3071,7 +3080,7 @@ impl<'a> Parser<'a> { let else_span = self.token.span; self.bump(); let else_clause = self.parse_expr_else()?; - self.dcx().emit_err(errors::LoopElseNotSupported { + self.dcx().emit_err(diagnostics::LoopElseNotSupported { span: else_span.to(else_clause.span), loop_kind, loop_kw, @@ -3085,18 +3094,18 @@ impl<'a> Parser<'a> { // Possibly using JS syntax (#75311). let span = self.token.span; self.bump(); - (span, Some(errors::MissingInInForLoopSub::InNotOf(span))) + (span, Some(diagnostics::MissingInInForLoopSub::InNotOf(span))) } else if self.eat(exp!(Eq)) { let span = self.prev_token.span; - (span, Some(errors::MissingInInForLoopSub::InNotEq(span))) + (span, Some(diagnostics::MissingInInForLoopSub::InNotEq(span))) } else { let span = self.prev_token.span.between(self.token.span); let sub = (!self.for_loop_head_has_in()) - .then_some(errors::MissingInInForLoopSub::AddIn(span)); + .then_some(diagnostics::MissingInInForLoopSub::AddIn(span)); (span, sub) }; - self.dcx().emit_err(errors::MissingInInForLoop { span, sub }); + self.dcx().emit_err(diagnostics::MissingInInForLoop { span, sub }); } /// Whether the `for` loop header already contains an `in` before its body. @@ -3166,7 +3175,7 @@ impl<'a> Parser<'a> { if let Some((ident, is_raw)) = self.token.lifetime() { // Disallow `'fn`, but with a better error message than `expect_lifetime`. if is_raw == IdentIsRaw::No && ident.without_first_quote().is_reserved() { - self.dcx().emit_err(errors::KeywordLabel { span: ident.span }); + self.dcx().emit_err(diagnostics::KeywordLabel { span: ident.span }); } self.bump(); @@ -3264,18 +3273,18 @@ impl<'a> Parser<'a> { let err = |this: &Parser<'_>, stmts: Vec| { let span = stmts[0].span.to(stmts[stmts.len() - 1].span); - let guar = this.dcx().emit_err(errors::MatchArmBodyWithoutBraces { + let guar = this.dcx().emit_err(diagnostics::MatchArmBodyWithoutBraces { statements: span, arrow: arrow_span, num_statements: stmts.len(), sub: if stmts.len() > 1 { - errors::MatchArmBodyWithoutBracesSugg::AddBraces { + diagnostics::MatchArmBodyWithoutBracesSugg::AddBraces { left: span.shrink_to_lo(), right: span.shrink_to_hi(), num_statements: stmts.len(), } } else { - errors::MatchArmBodyWithoutBracesSugg::UseComma { semicolon: semi_sp } + diagnostics::MatchArmBodyWithoutBracesSugg::UseComma { semicolon: semi_sp } }, }); (span, guar) @@ -3498,7 +3507,7 @@ impl<'a> Parser<'a> { .is_ok(); if pattern_follows && snapshot.check(exp!(FatArrow)) { err.cancel(); - let guar = this.dcx().emit_err(errors::MissingCommaAfterMatchArm { + let guar = this.dcx().emit_err(diagnostics::MissingCommaAfterMatchArm { span: arm_span.shrink_to_hi(), }); return Ok(Recovered::Yes(guar)); @@ -3591,9 +3600,9 @@ impl<'a> Parser<'a> { checker.visit_expr(&mut guard.cond); let right = self.prev_token.span; - self.dcx().emit_err(errors::ParenthesesInMatchPat { + self.dcx().emit_err(diagnostics::ParenthesesInMatchPat { span: vec![left, right], - sugg: errors::ParenthesesInMatchPatSugg { left, right }, + sugg: diagnostics::ParenthesesInMatchPatSugg { left, right }, }); if let Some(guar) = checker.found_incorrect_let_chain { @@ -3669,7 +3678,7 @@ impl<'a> Parser<'a> { let (attrs, body) = self.parse_inner_attrs_and_block(None)?; if self.eat_keyword(exp!(Catch)) { - Err(self.dcx().create_err(errors::CatchAfterTry { span: self.prev_token.span })) + Err(self.dcx().create_err(diagnostics::CatchAfterTry { span: self.prev_token.span })) } else { let span = span_lo.to(body.span); let gate_sym = @@ -3779,9 +3788,9 @@ impl<'a> Parser<'a> { match self.parse_expr_struct(qself.clone(), path.clone(), false) { Ok(expr) => { // This is a struct literal, but we don't accept them here. - self.dcx().emit_err(errors::StructLiteralNotAllowedHere { + self.dcx().emit_err(diagnostics::StructLiteralNotAllowedHere { span: expr.span, - sub: errors::StructLiteralNotAllowedHereSugg { + sub: diagnostics::StructLiteralNotAllowedHereSugg { left: path.span.shrink_to_lo(), right: expr.span.shrink_to_hi(), }, @@ -3823,10 +3832,10 @@ impl<'a> Parser<'a> { )?; let guar = if is_underscore_entry_point { - self.dcx().create_err(errors::StructLiteralPlaceholderPath { span }).emit() + self.dcx().create_err(diagnostics::StructLiteralPlaceholderPath { span }).emit() } else { self.dcx() - .create_err(errors::StructLiteralWithoutPathLate { + .create_err(diagnostics::StructLiteralWithoutPathLate { span: expr.span, suggestion_span: expr.span.shrink_to_lo(), }) @@ -3858,8 +3867,8 @@ impl<'a> Parser<'a> { let in_if_guard = self.restrictions.contains(Restrictions::IN_IF_GUARD); let async_block_err = |e: &mut Diag<'_>, span: Span| { - errors::AsyncBlockIn2015 { span }.add_to_diag(e); - errors::HelpUseLatestEdition::new().add_to_diag(e); + diagnostics::AsyncBlockIn2015 { span }.add_to_diag(e); + diagnostics::HelpUseLatestEdition::new().add_to_diag(e); }; while self.token != close.tok { @@ -4045,7 +4054,7 @@ impl<'a> Parser<'a> { if self.token != token::Comma { return; } - self.dcx().emit_err(errors::CommaAfterBaseStruct { + self.dcx().emit_err(diagnostics::CommaAfterBaseStruct { span: span.to(self.prev_token.span), comma: self.token.span, }); @@ -4056,7 +4065,7 @@ impl<'a> Parser<'a> { if !self.look_ahead(1, |t| t == close) && self.eat(exp!(DotDotDot)) { // recover from typo of `...`, suggest `..` let span = self.prev_token.span; - self.dcx().emit_err(errors::MissingDotDot { token_span: span, sugg_span: span }); + self.dcx().emit_err(diagnostics::MissingDotDot { token_span: span, sugg_span: span }); return true; } false @@ -4069,7 +4078,7 @@ impl<'a> Parser<'a> { let label = format!("'{}", ident.name); let ident = Ident::new(Symbol::intern(&label), ident.span); - self.dcx().emit_err(errors::ExpectedLabelFoundIdent { + self.dcx().emit_err(diagnostics::ExpectedLabelFoundIdent { span: ident.span, start: ident.span.shrink_to_lo(), }); @@ -4096,7 +4105,7 @@ impl<'a> Parser<'a> { || t == &token::CloseParen }); if is_wrong { - return Err(this.dcx().create_err(errors::ExpectedStructField { + return Err(this.dcx().create_err(diagnostics::ExpectedStructField { span: this.look_ahead(1, |t| t.span), ident_span: this.token.span, token: pprust::token_to_string(&this.look_ahead(1, |t| *t)), @@ -4137,18 +4146,18 @@ impl<'a> Parser<'a> { return; } - self.dcx().emit_err(errors::EqFieldInit { + self.dcx().emit_err(diagnostics::EqFieldInit { span: self.token.span, eq: field_name.span.shrink_to_hi().to(self.token.span), }); } fn err_dotdotdot_syntax(&self, span: Span) { - self.dcx().emit_err(errors::DotDotDot { span }); + self.dcx().emit_err(diagnostics::DotDotDot { span }); } fn err_larrow_operator(&self, span: Span) { - self.dcx().emit_err(errors::LeftArrowOperator { span }); + self.dcx().emit_err(diagnostics::LeftArrowOperator { span }); } fn mk_assign_op(&self, assign_op: AssignOp, lhs: Box, rhs: Box) -> ExprKind { @@ -4298,9 +4307,9 @@ struct CondChecker<'a> { parser: &'a Parser<'a>, let_chains_policy: LetChainsPolicy, depth: u32, - forbid_let_reason: Option, - missing_let: Option, - comparison: Option, + forbid_let_reason: Option, + missing_let: Option, + comparison: Option, found_incorrect_let_chain: Option, } @@ -4327,17 +4336,18 @@ impl MutVisitor for CondChecker<'_> { ExprKind::Let(_, _, _, ref mut recovered @ Recovered::No) => { if let Some(reason) = self.forbid_let_reason { let error = match reason { - errors::ForbiddenLetReason::NotSupportedOr(or_span) => { - self.parser.dcx().emit_err(errors::OrInLetChain { span: or_span }) + diagnostics::ForbiddenLetReason::NotSupportedOr(or_span) => { + self.parser.dcx().emit_err(diagnostics::OrInLetChain { span: or_span }) } _ => { - let guar = - self.parser.dcx().emit_err(errors::ExpectedExpressionFoundLet { + let guar = self.parser.dcx().emit_err( + diagnostics::ExpectedExpressionFoundLet { span, reason, missing_let: self.missing_let, comparison: self.comparison, - }); + }, + ); if let Some(_) = self.missing_let { self.found_incorrect_let_chain = Some(guar); } @@ -4351,7 +4361,7 @@ impl MutVisitor for CondChecker<'_> { LetChainsPolicy::AlwaysAllowed => (), LetChainsPolicy::EditionDependent { current_edition } => { if !current_edition.at_least_rust_2024() || !span.at_least_rust_2024() { - self.parser.dcx().emit_err(errors::LetChainPre2024 { span }); + self.parser.dcx().emit_err(diagnostics::LetChainPre2024 { span }); } } } @@ -4361,21 +4371,22 @@ impl MutVisitor for CondChecker<'_> { mut_visit::walk_expr(self, e); } ExprKind::Binary(Spanned { node: BinOpKind::Or, span: or_span }, _, _) - if let None | Some(errors::ForbiddenLetReason::NotSupportedOr(_)) = + if let None | Some(diagnostics::ForbiddenLetReason::NotSupportedOr(_)) = self.forbid_let_reason => { let forbid_let_reason = self.forbid_let_reason; - self.forbid_let_reason = Some(errors::ForbiddenLetReason::NotSupportedOr(or_span)); + self.forbid_let_reason = + Some(diagnostics::ForbiddenLetReason::NotSupportedOr(or_span)); mut_visit::walk_expr(self, e); self.forbid_let_reason = forbid_let_reason; } ExprKind::Paren(ref inner) - if let None | Some(errors::ForbiddenLetReason::NotSupportedParentheses(_)) = + if let None | Some(diagnostics::ForbiddenLetReason::NotSupportedParentheses(_)) = self.forbid_let_reason => { let forbid_let_reason = self.forbid_let_reason; self.forbid_let_reason = - Some(errors::ForbiddenLetReason::NotSupportedParentheses(inner.span)); + Some(diagnostics::ForbiddenLetReason::NotSupportedParentheses(inner.span)); mut_visit::walk_expr(self, e); self.forbid_let_reason = forbid_let_reason; } @@ -4413,12 +4424,13 @@ impl MutVisitor for CondChecker<'_> { if let Some(later_rhs) = find_let_some(rhs) && depth > 0 { - let guar = self.parser.dcx().emit_err(errors::LetChainMissingLet { - span: lhs.span, - label_span: expr_span, - rhs_span: later_rhs.span, - sug_span: lhs.span.shrink_to_lo(), - }); + let guar = + self.parser.dcx().emit_err(diagnostics::LetChainMissingLet { + span: lhs.span, + label_span: expr_span, + rhs_span: later_rhs.span, + sug_span: lhs.span.shrink_to_lo(), + }); self.found_incorrect_let_chain = Some(guar); } @@ -4426,7 +4438,7 @@ impl MutVisitor for CondChecker<'_> { } let forbid_let_reason = self.forbid_let_reason; - self.forbid_let_reason = Some(errors::ForbiddenLetReason::OtherForbidden); + self.forbid_let_reason = Some(diagnostics::ForbiddenLetReason::OtherForbidden); let missing_let = self.missing_let; if let ExprKind::Binary(_, _, rhs) = &lhs.kind && let ExprKind::Path(_, _) @@ -4435,10 +4447,10 @@ impl MutVisitor for CondChecker<'_> { | ExprKind::Array(_) = rhs.kind { self.missing_let = - Some(errors::MaybeMissingLet { span: rhs.span.shrink_to_lo() }); + Some(diagnostics::MaybeMissingLet { span: rhs.span.shrink_to_lo() }); } let comparison = self.comparison; - self.comparison = Some(errors::MaybeComparison { span: span.shrink_to_hi() }); + self.comparison = Some(diagnostics::MaybeComparison { span: span.shrink_to_hi() }); mut_visit::walk_expr(self, e); self.forbid_let_reason = forbid_let_reason; self.missing_let = missing_let; @@ -4460,7 +4472,7 @@ impl MutVisitor for CondChecker<'_> { | ExprKind::Tup(_) | ExprKind::Paren(_) => { let forbid_let_reason = self.forbid_let_reason; - self.forbid_let_reason = Some(errors::ForbiddenLetReason::OtherForbidden); + self.forbid_let_reason = Some(diagnostics::ForbiddenLetReason::OtherForbidden); mut_visit::walk_expr(self, e); self.forbid_let_reason = forbid_let_reason; } @@ -4468,7 +4480,7 @@ impl MutVisitor for CondChecker<'_> { | ExprKind::Type(ref mut op, _) | ExprKind::UnsafeBinderCast(_, ref mut op, _) => { let forbid_let_reason = self.forbid_let_reason; - self.forbid_let_reason = Some(errors::ForbiddenLetReason::OtherForbidden); + self.forbid_let_reason = Some(diagnostics::ForbiddenLetReason::OtherForbidden); self.visit_expr(op); self.forbid_let_reason = forbid_let_reason; } diff --git a/compiler/rustc_parse/src/parser/generics.rs b/compiler/rustc_parse/src/parser/generics.rs index 506607f57191d..ec9860c0f35bf 100644 --- a/compiler/rustc_parse/src/parser/generics.rs +++ b/compiler/rustc_parse/src/parser/generics.rs @@ -7,7 +7,7 @@ use rustc_span::{Ident, Span, kw, sym}; use thin_vec::ThinVec; use super::{ForceCollect, Parser, Trailing, UsePreAttrPos}; -use crate::errors::{ +use crate::diagnostics::{ self, MultipleWhereClauses, UnexpectedDefaultValueForLifetimeInGenericParameters, UnexpectedSelfInGenericParameters, WhereClauseBeforeTupleStructBody, WhereClauseBeforeTupleStructBodySugg, @@ -260,7 +260,7 @@ impl<'a> Parser<'a> { let lo = this.token.span; match this.parse_ty_where_predicate_kind() { Ok(_) => { - this.dcx().emit_err(errors::BadAssocTypeBounds { + this.dcx().emit_err(diagnostics::BadAssocTypeBounds { span: lo.to(this.prev_token.span), }); // FIXME - try to continue parsing other generics? @@ -276,10 +276,11 @@ impl<'a> Parser<'a> { // Check for trailing attributes and stop parsing. if !attrs.is_empty() { if !params.is_empty() { - this.dcx().emit_err(errors::AttrAfterGeneric { span: attrs[0].span }); + this.dcx() + .emit_err(diagnostics::AttrAfterGeneric { span: attrs[0].span }); } else { this.dcx() - .emit_err(errors::AttrWithoutGenerics { span: attrs[0].span }); + .emit_err(diagnostics::AttrWithoutGenerics { span: attrs[0].span }); } } return Ok((None, Trailing::No, UsePreAttrPos::No)); @@ -320,7 +321,7 @@ impl<'a> Parser<'a> { // for example `fn invalid_path_separator::() {}` if self.eat_noexpect(&token::PathSep) { self.dcx() - .emit_err(errors::InvalidPathSepInFnDefinition { span: self.prev_token.span }); + .emit_err(diagnostics::InvalidPathSepInFnDefinition { span: self.prev_token.span }); } let span_lo = self.token.span; @@ -442,7 +443,7 @@ impl<'a> Parser<'a> { // change we parse those generics now, but report an error. if self.choose_generics_over_qpath(0) { let generics = self.parse_generics()?; - self.dcx().emit_err(errors::WhereOnGenerics { span: generics.span }); + self.dcx().emit_err(diagnostics::WhereOnGenerics { span: generics.span }); } loop { @@ -475,13 +476,14 @@ impl<'a> Parser<'a> { } else { if let [.., last] = &attrs[..] { if last.is_doc_comment() { - this.dcx().emit_err(errors::DocCommentDoesNotDocumentAnything { + this.dcx().emit_err(diagnostics::DocCommentDoesNotDocumentAnything { span: last.span, missing_comma: None, }); } else { - this.dcx() - .emit_err(errors::AttrWithoutWherePredicates { span: last.span }); + this.dcx().emit_err(diagnostics::AttrWithoutWherePredicates { + span: last.span, + }); } } None diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 8a861b169803d..192cd7668f518 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -23,7 +23,7 @@ use super::{ AllowConstBlockItems, AttrWrapper, ExpKeywordPair, ExpTokenPair, FollowedByType, ForceCollect, Parser, PathStyle, Recovered, Trailing, UsePreAttrPos, }; -use crate::errors::{ +use crate::diagnostics::{ self, FnPointerCannotBeAsync, FnPointerCannotBeConst, MacroExpandsToAdtField, UseDoubleColonSuggestion, UseRegularStructSuggestion, }; @@ -196,7 +196,7 @@ impl<'a> Parser<'a> { // At this point, we have failed to parse an item. if !matches!(vis.kind, VisibilityKind::Inherited) { let vis_str = pprust::vis_to_string(&vis).trim_end().to_string(); - let mut err = this.dcx().create_err(errors::VisibilityNotFollowedByItem { + let mut err = this.dcx().create_err(diagnostics::VisibilityNotFollowedByItem { span: vis.span, vis: vis_str, }); @@ -206,7 +206,7 @@ impl<'a> Parser<'a> { .name .find_similar(&rustc_span::symbol::used_keywords(|| ident.span.edition())) { - err.subdiagnostic(errors::MisspelledKw { + err.subdiagnostic(diagnostics::MisspelledKw { similar_kw: similar_kw.to_string(), span: ident.span, is_incorrect_case, @@ -216,9 +216,9 @@ impl<'a> Parser<'a> { } if let Defaultness::Default(span) = def { - this.dcx().emit_err(errors::DefaultNotFollowedByItem { span }); + this.dcx().emit_err(diagnostics::DefaultNotFollowedByItem { span }); } else if let Defaultness::Final(span) = def { - this.dcx().emit_err(errors::FinalNotFollowedByItem { span }); + this.dcx().emit_err(diagnostics::FinalNotFollowedByItem { span }); } if !attrs_allowed { @@ -232,14 +232,14 @@ impl<'a> Parser<'a> { fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) { match def { Defaultness::Default(span) => { - self.dcx().emit_err(errors::InappropriateDefault { + self.dcx().emit_err(diagnostics::InappropriateDefault { span, article: kind.article(), descr: kind.descr(), }); } Defaultness::Final(span) => { - self.dcx().emit_err(errors::InappropriateFinal { + self.dcx().emit_err(diagnostics::InappropriateFinal { span, article: kind.article(), descr: kind.descr(), @@ -423,7 +423,7 @@ impl<'a> Parser<'a> { self.bump(); match self.parse_use_item() { Ok(u) => { - self.dcx().emit_err(errors::RecoverImportAsUse { span, token_name }); + self.dcx().emit_err(diagnostics::RecoverImportAsUse { span, token_name }); Ok(Some(u)) } Err(e) => { @@ -510,14 +510,22 @@ impl<'a> Parser<'a> { // possible struct or enum definition where `struct` or `enum` was forgotten if self.look_ahead(1, |t| *t == token::CloseBrace) { // `S {}` could be unit enum or struct - Some(errors::MissingKeywordForItemDefinition::EnumOrStruct { span }) + Some(diagnostics::MissingKeywordForItemDefinition::EnumOrStruct { span }) } else if self.look_ahead(2, |t| *t == token::Colon) || self.look_ahead(3, |t| *t == token::Colon) { // `S { f:` or `S { pub f:` - Some(errors::MissingKeywordForItemDefinition::Struct { span, insert_span, ident }) + Some(diagnostics::MissingKeywordForItemDefinition::Struct { + span, + insert_span, + ident, + }) } else { - Some(errors::MissingKeywordForItemDefinition::Enum { span, insert_span, ident }) + Some(diagnostics::MissingKeywordForItemDefinition::Enum { + span, + insert_span, + ident, + }) } } else if self.check(exp!(OpenParen)) { // possible function or tuple struct definition where `fn` or `struct` was forgotten @@ -531,30 +539,38 @@ impl<'a> Parser<'a> { self.bump(); // `{` self.consume_block(exp!(OpenBrace), exp!(CloseBrace), ConsumeClosingDelim::Yes); if is_method { - errors::MissingKeywordForItemDefinition::Method { span, insert_span, ident } + diagnostics::MissingKeywordForItemDefinition::Method { + span, + insert_span, + ident, + } } else { - errors::MissingKeywordForItemDefinition::Function { span, insert_span, ident } + diagnostics::MissingKeywordForItemDefinition::Function { + span, + insert_span, + ident, + } } } else if is_pub && self.check(exp!(Semi)) { - errors::MissingKeywordForItemDefinition::Struct { span, insert_span, ident } + diagnostics::MissingKeywordForItemDefinition::Struct { span, insert_span, ident } } else { - errors::MissingKeywordForItemDefinition::Ambiguous { + diagnostics::MissingKeywordForItemDefinition::Ambiguous { span, subdiag: if found_generics { None } else if let Ok(snippet) = self.span_to_snippet(ident_span) { - Some(errors::AmbiguousMissingKwForItemSub::SuggestMacro { + Some(diagnostics::AmbiguousMissingKwForItemSub::SuggestMacro { span: ident_span, snippet, }) } else { - Some(errors::AmbiguousMissingKwForItemSub::HelpMacro) + Some(diagnostics::AmbiguousMissingKwForItemSub::HelpMacro) }, } }; Some(err) } else if found_generics { - Some(errors::MissingKeywordForItemDefinition::Ambiguous { span, subdiag: None }) + Some(diagnostics::MissingKeywordForItemDefinition::Ambiguous { span, subdiag: None }) } else { None }; @@ -693,7 +709,7 @@ impl<'a> Parser<'a> { || self.is_kw_followed_by_ident(kw::Async) { self.bump(); - self.dcx().emit_err(errors::AsyncImpl { span: self.prev_token.span }); + self.dcx().emit_err(diagnostics::AsyncImpl { span: self.prev_token.span }); } let polarity = self.parse_polarity(); @@ -702,7 +718,7 @@ impl<'a> Parser<'a> { let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt) { let span = self.prev_token.span.between(self.token.span); - return Err(self.dcx().create_err(errors::MissingTraitInTraitImpl { + return Err(self.dcx().create_err(diagnostics::MissingTraitInTraitImpl { span, for_span: span.to(self.token.span), })); @@ -744,7 +760,8 @@ impl<'a> Parser<'a> { Some(ty_second) => { // impl Trait for Type if !has_for { - self.dcx().emit_err(errors::MissingForInTraitImpl { span: missing_for_span }); + self.dcx() + .emit_err(diagnostics::MissingForInTraitImpl { span: missing_for_span }); } let ty_first = *ty_first; @@ -760,14 +777,16 @@ impl<'a> Parser<'a> { // `impl impl Default for Wrapper` // ^^^^^ let extra_impl_kw = ty_first.span.until(bound.span()); - self.dcx().emit_err(errors::ExtraImplKeywordInTraitImpl { + self.dcx().emit_err(diagnostics::ExtraImplKeywordInTraitImpl { extra_impl_kw, impl_trait_span: ty_first.span, }); poly_trait_ref.trait_ref.path.clone() } else { return Err(self.dcx().create_err( - errors::ExpectedTraitInTraitImplFoundType { span: ty_first.span }, + diagnostics::ExpectedTraitInTraitImplFoundType { + span: ty_first.span, + }, )); } } @@ -781,7 +800,7 @@ impl<'a> Parser<'a> { None => { let self_ty = ty_first; let error = |modifier, modifier_name, modifier_span| { - self.dcx().create_err(errors::TraitImplModifierInInherentImpl { + self.dcx().create_err(diagnostics::TraitImplModifierInInherentImpl { span: self_ty.span, modifier, modifier_name, @@ -851,7 +870,7 @@ impl<'a> Parser<'a> { let Some(of_trait) = of_trait else { return Err(self .dcx() - .create_err(errors::ImplReuseInherentImpl { span: until_expr_span })); + .create_err(diagnostics::ImplReuseInherentImpl { span: until_expr_span })); }; let body = self.parse_delegation_body()?; @@ -927,7 +946,7 @@ impl<'a> Parser<'a> { // Recover `impl Ty;` instead of `impl Ty {}` if self.token == TokenKind::Semi { - self.dcx().emit_err(errors::UseEmptyBlockNotSemi { span: self.token.span }); + self.dcx().emit_err(diagnostics::UseEmptyBlockNotSemi { span: self.token.span }); self.bump(); return Ok(ThinVec::new()); } @@ -1151,7 +1170,7 @@ impl<'a> Parser<'a> { // It's a trait alias. if had_colon { let span = span_at_colon.to(span_before_eq); - self.dcx().emit_err(errors::BoundsNotAllowedOnTraitAliases { span }); + self.dcx().emit_err(diagnostics::BoundsNotAllowedOnTraitAliases { span }); } let bounds = self.parse_generic_bounds()?; @@ -1160,13 +1179,14 @@ impl<'a> Parser<'a> { let whole_span = lo.to(self.prev_token.span); if is_auto == IsAuto::Yes { - self.dcx().emit_err(errors::TraitAliasCannotBeAuto { span: whole_span }); + self.dcx().emit_err(diagnostics::TraitAliasCannotBeAuto { span: whole_span }); } if let Safety::Unsafe(_) = safety { - self.dcx().emit_err(errors::TraitAliasCannotBeUnsafe { span: whole_span }); + self.dcx().emit_err(diagnostics::TraitAliasCannotBeUnsafe { span: whole_span }); } if let RestrictionKind::Restricted { .. } = impl_restriction.kind { - self.dcx().emit_err(errors::TraitAliasCannotBeImplRestricted { span: whole_span }); + self.dcx() + .emit_err(diagnostics::TraitAliasCannotBeImplRestricted { span: whole_span }); } self.psess.gated_spans.gate(sym::trait_alias, whole_span); @@ -1235,7 +1255,8 @@ impl<'a> Parser<'a> { define_opaque, eii_impls: _, }) => { - self.dcx().emit_err(errors::AssociatedStaticItemNotAllowed { span }); + self.dcx() + .emit_err(diagnostics::AssociatedStaticItemNotAllowed { span }); AssocItemKind::Const(Box::new(ConstItem { defaultness: Defaultness::Implicit, ident, @@ -1315,8 +1336,9 @@ impl<'a> Parser<'a> { } else { // Recover from using a colon as path separator. while self.eat_noexpect(&token::Colon) { - self.dcx() - .emit_err(errors::SingleColonImportPath { span: self.prev_token.span }); + self.dcx().emit_err(diagnostics::SingleColonImportPath { + span: self.prev_token.span, + }); // We parse the rest of the path and append it to the original prefix. self.parse_path_segments(&mut prefix.segments, PathStyle::Mod, None)?; @@ -1420,9 +1442,9 @@ impl<'a> Parser<'a> { write!(fixed_name, "_{}", part.name).unwrap(); } - self.dcx().emit_err(errors::ExternCrateNameWithDashes { + self.dcx().emit_err(diagnostics::ExternCrateNameWithDashes { span: fixed_name_sp, - sugg: errors::ExternCrateNameWithDashesSugg { dashes }, + sugg: diagnostics::ExternCrateNameWithDashesSugg { dashes }, }); Ok(Ident::from_str_and_span(&fixed_name, fixed_name_sp)) @@ -1485,7 +1507,7 @@ impl<'a> Parser<'a> { ItemKind::Const(ConstItem { ident, ty, rhs_kind, .. }) => { let const_span = Some(span.with_hi(ident.span.lo())) .filter(|span| span.can_be_used_for_suggestions()); - self.dcx().emit_err(errors::ExternItemCannotBeConst { + self.dcx().emit_err(diagnostics::ExternItemCannotBeConst { ident_span: ident.span, const_span, }); @@ -1523,7 +1545,7 @@ impl<'a> Parser<'a> { }) => false, _ => true, }; - self.dcx().emit_err(errors::BadItemKind { span, descr, ctx, help }); + self.dcx().emit_err(diagnostics::BadItemKind { span, descr, ctx, help }); None } @@ -1593,10 +1615,11 @@ impl<'a> Parser<'a> { if self.eat_keyword(exp!(Mut)) { let span = self.prev_token.span; self.dcx() - .emit_err(errors::ConstGlobalCannotBeMutable { ident_span: span, const_span }); + .emit_err(diagnostics::ConstGlobalCannotBeMutable { ident_span: span, const_span }); } else if self.eat_keyword(exp!(Let)) { let span = self.prev_token.span; - self.dcx().emit_err(errors::ConstLetMutuallyExclusive { span: const_span.to(span) }); + self.dcx() + .emit_err(diagnostics::ConstLetMutuallyExclusive { span: const_span.to(span) }); } } @@ -1623,7 +1646,7 @@ impl<'a> Parser<'a> { if self.token == TokenKind::Lt && self.may_recover() { let generics = self.parse_generics()?; - self.dcx().emit_err(errors::StaticWithGenerics { span: generics.span }); + self.dcx().emit_err(diagnostics::StaticWithGenerics { span: generics.span }); } // Parse the type of a static item. That is, the `":" $ty` fragment. @@ -1707,13 +1730,13 @@ impl<'a> Parser<'a> { if before_where_clause.has_where_token && let Some(rhs_span) = rhs.span() { - self.dcx().emit_err(errors::WhereClauseBeforeConstBody { + self.dcx().emit_err(diagnostics::WhereClauseBeforeConstBody { span: before_where_clause.span, name: ident.span, body: rhs_span, sugg: if !after_where_clause.has_where_token { self.psess.source_map().span_to_snippet(rhs_span).ok().map(|body_s| { - errors::WhereClauseBeforeConstBodySugg { + diagnostics::WhereClauseBeforeConstBodySugg { left: before_where_clause.span.shrink_to_lo(), snippet: body_s, right: before_where_clause.span.shrink_to_hi().to(rhs_span), @@ -1781,7 +1804,7 @@ impl<'a> Parser<'a> { }; let span = self.prev_token.span.shrink_to_hi(); - let err = self.dcx().create_err(errors::MissingConstType { span, colon, kind }); + let err = self.dcx().create_err(diagnostics::MissingConstType { span, colon, kind }); err.stash(span, StashKey::ItemNoType); // The user intended that the type be inferred, @@ -1793,7 +1816,7 @@ impl<'a> Parser<'a> { fn parse_item_enum(&mut self) -> PResult<'a, ItemKind> { if self.token.is_keyword(kw::Struct) { let span = self.prev_token.span.to(self.token.span); - let err = errors::EnumStructMutuallyExclusive { span }; + let err = diagnostics::EnumStructMutuallyExclusive { span }; if self.look_ahead(1, |t| t.is_ident()) { self.bump(); self.dcx().emit_err(err); @@ -1809,7 +1832,7 @@ impl<'a> Parser<'a> { // Possibly recover `enum Foo;` instead of `enum Foo {}` let (variants, _) = if self.token == TokenKind::Semi { - self.dcx().emit_err(errors::UseEmptyBlockNotSemi { span: self.token.span }); + self.dcx().emit_err(diagnostics::UseEmptyBlockNotSemi { span: self.token.span }); self.bump(); (thin_vec![], Trailing::No) } else { @@ -1999,7 +2022,7 @@ impl<'a> Parser<'a> { self.expect_semi()?; body } else { - let err = errors::UnexpectedTokenAfterStructName::new(self.token.span, self.token); + let err = diagnostics::UnexpectedTokenAfterStructName::new(self.token.span, self.token); return Err(self.dcx().create_err(err)); }; @@ -2240,7 +2263,7 @@ impl<'a> Parser<'a> { token::CloseBrace => {} token::DocComment(..) => { let previous_span = self.prev_token.span; - let mut err = errors::DocCommentDoesNotDocumentAnything { + let mut err = diagnostics::DocCommentDoesNotDocumentAnything { span: self.token.span, missing_comma: None, }; @@ -2516,7 +2539,7 @@ impl<'a> Parser<'a> { return IsMacroRulesItem::Yes { has_bang: true }; } else if self.look_ahead(1, |t| t.is_ident()) { // macro_rules foo - self.dcx().emit_err(errors::MacroRulesMissingBang { + self.dcx().emit_err(diagnostics::MacroRulesMissingBang { span: macro_rules_span, hi: macro_rules_span.shrink_to_hi(), }); @@ -2544,7 +2567,7 @@ impl<'a> Parser<'a> { if self.eat(exp!(Bang)) { // Handle macro_rules! foo! let span = self.prev_token.span; - self.dcx().emit_err(errors::MacroNameRemoveBang { span }); + self.dcx().emit_err(diagnostics::MacroNameRemoveBang { span }); } let body = self.parse_delim_args()?; @@ -2567,9 +2590,10 @@ impl<'a> Parser<'a> { let vstr = pprust::vis_to_string(vis); let vstr = vstr.trim_end(); if macro_rules { - self.dcx().emit_err(errors::MacroRulesVisibility { span: vis.span, vis: vstr }); + self.dcx().emit_err(diagnostics::MacroRulesVisibility { span: vis.span, vis: vstr }); } else { - self.dcx().emit_err(errors::MacroInvocationVisibility { span: vis.span, vis: vstr }); + self.dcx() + .emit_err(diagnostics::MacroInvocationVisibility { span: vis.span, vis: vstr }); } } @@ -2637,7 +2661,7 @@ impl<'a> Parser<'a> { if self.token == token::Comma { item = item.to(self.token.span); } - self.dcx().emit_err(errors::NestedAdt { + self.dcx().emit_err(diagnostics::NestedAdt { span: kw_token.span, item, kw_str, @@ -2759,7 +2783,7 @@ impl<'a> Parser<'a> { // If we see `for Ty ...` then user probably meant `impl` item. if self.token.is_keyword(kw::For) { old_err.cancel(); - return Err(self.dcx().create_err(errors::FnTypoWithImpl { fn_span })); + return Err(self.dcx().create_err(diagnostics::FnTypoWithImpl { fn_span })); } else { return Err(old_err); } @@ -2841,7 +2865,7 @@ impl<'a> Parser<'a> { if let Some(fn_trait_span) = fn_trait_span { // Typo'd Fn* trait bounds such as // fn foo() where F: FnOnce -> () {} - err.subdiagnostic(errors::FnTraitMissingParen { span: fn_trait_span }); + err.subdiagnostic(diagnostics::FnTraitMissingParen { span: fn_trait_span }); } else if let Ok(snippet) = self.psess.source_map().span_to_snippet(ret_ty_span) { // If token behind right arrow is not a Fn* trait, the programmer @@ -2850,7 +2874,7 @@ impl<'a> Parser<'a> { err.primary_message( "return type should be specified after the function parameters", ); - err.subdiagnostic(errors::MisplacedReturnType { + err.subdiagnostic(diagnostics::MisplacedReturnType { fn_params_end, snippet, ret_ty_span, @@ -2909,9 +2933,12 @@ impl<'a> Parser<'a> { let _ = self.parse_expr()?; self.expect_semi()?; // `;` let span = eq_sp.to(self.prev_token.span); - let guar = self.dcx().emit_err(errors::FunctionBodyEqualsExpr { + let guar = self.dcx().emit_err(diagnostics::FunctionBodyEqualsExpr { span, - sugg: errors::FunctionBodyEqualsExprSugg { eq: eq_sp, semi: self.prev_token.span }, + sugg: diagnostics::FunctionBodyEqualsExprSugg { + eq: eq_sp, + semi: self.prev_token.span, + }, }); (AttrVec::new(), Some(self.mk_block_err(span, guar))) } else { @@ -3086,9 +3113,9 @@ impl<'a> Parser<'a> { if let Some(CoroutineKind::Async { span, .. }) = coroutine_kind { if span.is_rust_2015() { - self.dcx().emit_err(errors::AsyncFnIn2015 { + self.dcx().emit_err(diagnostics::AsyncFnIn2015 { span, - help: errors::HelpUseLatestEdition::new(), + help: diagnostics::HelpUseLatestEdition::new(), }); } } @@ -3337,8 +3364,9 @@ impl<'a> Parser<'a> { && !self.token.is_keyword(kw::For) { // recover from missing argument list, e.g. `fn main -> () {}` - self.dcx() - .emit_err(errors::MissingFnParams { span: self.prev_token.span.shrink_to_hi() }); + self.dcx().emit_err(diagnostics::MissingFnParams { + span: self.prev_token.span.shrink_to_hi(), + }); return Ok(ThinVec::new()); } @@ -3404,7 +3432,7 @@ impl<'a> Parser<'a> { VARARGS_WITHOUT_PATTERN, this.token.span, ast::CRATE_NODE_ID, - errors::VarargsWithoutPattern { span: this.token.span }, + diagnostics::VarargsWithoutPattern { span: this.token.span }, ); false } else { @@ -3539,9 +3567,9 @@ impl<'a> Parser<'a> { let snap = this.create_snapshot_for_diagnostic(); match this.parse_ty() { Ok(ty) => { - this.dcx().emit_err(errors::IncorrectTypeOnSelf { + this.dcx().emit_err(diagnostics::IncorrectTypeOnSelf { span: ty.span, - move_self_modifier: errors::MoveSelfModifier { + move_self_modifier: diagnostics::MoveSelfModifier { removal_span: modifier_span, insertion_span: ty.span.shrink_to_lo(), modifier: modifier.to_ref_suggestion(), @@ -3558,7 +3586,7 @@ impl<'a> Parser<'a> { }; // Recover for the grammar `*self`, `*const self`, and `*mut self`. let recover_self_ptr = |this: &mut Self| { - this.dcx().emit_err(errors::SelfArgumentPointer { span: this.token.span }); + this.dcx().emit_err(diagnostics::SelfArgumentPointer { span: this.token.span }); Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_token.span)) }; diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index 8a8d1bd2c2e3f..ecd78fef6e142 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -51,8 +51,8 @@ use token_type::TokenTypeSet; pub use token_type::{ExpKeywordPair, ExpTokenPair, TokenType}; use tracing::debug; -use crate::errors::{ - self, IncorrectImplRestriction, IncorrectMutRestriction, IncorrectVisibilityRestriction, +use crate::diagnostics::{ + IncorrectImplRestriction, IncorrectMutRestriction, IncorrectVisibilityRestriction, NonStringAbiLiteral, TokenDescription, }; use crate::exp; @@ -598,12 +598,12 @@ impl<'a> Parser<'a> { (true, true) => { unreachable!("keyword that is both fully upper- and fully lowercase") } - (true, false) => errors::Case::Upper, - (false, true) => errors::Case::Lower, - (false, false) => errors::Case::Mixed, + (true, false) => crate::diagnostics::Case::Upper, + (false, true) => crate::diagnostics::Case::Lower, + (false, false) => crate::diagnostics::Case::Mixed, }; - self.dcx().emit_err(errors::KwBadCase { span: ident.span, kw, case }); + self.dcx().emit_err(crate::diagnostics::KwBadCase { span: ident.span, kw, case }); self.bump(); true } else { @@ -1359,7 +1359,7 @@ impl<'a> Parser<'a> { if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind { if let Some(suffix) = suffix { - self.dcx().emit_err(errors::InvalidLiteralSuffixOnTupleIndex { + self.dcx().emit_err(crate::diagnostics::InvalidLiteralSuffixOnTupleIndex { span: self.token.span, suffix, }); diff --git a/compiler/rustc_parse/src/parser/nonterminal.rs b/compiler/rustc_parse/src/parser/nonterminal.rs index 19b4dd1d0af7a..fc916317f1c8d 100644 --- a/compiler/rustc_parse/src/parser/nonterminal.rs +++ b/compiler/rustc_parse/src/parser/nonterminal.rs @@ -6,7 +6,7 @@ use rustc_ast_pretty::pprust; use rustc_errors::PResult; use rustc_span::{Ident, kw}; -use crate::errors::UnexpectedNonterminal; +use crate::diagnostics::UnexpectedNonterminal; use crate::parser::pat::{CommaRecoveryMode, RecoverColon, RecoverComma}; use crate::parser::{ AllowConstBlockItems, FollowedByType, ForceCollect, ParseNtResult, Parser, PathStyle, diff --git a/compiler/rustc_parse/src/parser/pat.rs b/compiler/rustc_parse/src/parser/pat.rs index e06ed3a75b2e4..3563dca21c2ef 100644 --- a/compiler/rustc_parse/src/parser/pat.rs +++ b/compiler/rustc_parse/src/parser/pat.rs @@ -17,7 +17,7 @@ use rustc_span::{BytePos, ErrorGuaranteed, Ident, Span, Spanned, kw, respan, sym use thin_vec::{ThinVec, thin_vec}; use super::{ForceCollect, Parser, PathStyle, Restrictions, Trailing, UsePreAttrPos}; -use crate::errors::{ +use crate::diagnostics::{ self, AmbiguousRangePattern, AtDotDotInStructPattern, AtInStructPattern, DotDotDotForRemainingFields, DotDotDotRangeToPatternNotAllowed, DotDotDotRestPattern, EnumPatternInsteadOfIdentifier, ExpectedBindingLeftOfAt, ExpectedCommaAfterPatternField, @@ -1474,7 +1474,7 @@ impl<'a> Parser<'a> { if self.isnt_pattern_start() { let descr = super::token_descr(&self.token); - self.dcx().emit_err(errors::BoxNotPat { + self.dcx().emit_err(diagnostics::BoxNotPat { span: self.token.span, kw: box_span, lo: box_span.shrink_to_lo(), diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index af13f1512e808..2dfcbccfe60ec 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -15,7 +15,7 @@ use tracing::debug; use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign}; use super::{Parser, Restrictions, TokenType}; use crate::ast::{PatKind, TyKind}; -use crate::errors::{ +use crate::diagnostics::{ self, AttributeOnEmptyType, AttributeOnGenericArg, ConstGenericWithoutBraces, ConstGenericWithoutBracesSugg, FnPathFoundNamedParams, PathFoundAttributeInParams, PathFoundCVariadicParams, PathSingleColon, PathTripleColon, @@ -184,7 +184,7 @@ impl<'a> Parser<'a> { .filter_map(|segment| segment.args.as_ref()) .map(|arg| arg.span()) .collect::>(); - parser.dcx().emit_err(errors::GenericsInPath { span }); + parser.dcx().emit_err(diagnostics::GenericsInPath { span }); // Ignore these arguments to prevent unexpected behaviors. let segments = path .segments @@ -375,8 +375,10 @@ impl<'a> Parser<'a> { let ty = self.parse_ty()?; let span = lo.to(ty.span); let suggestion = prev_lo.to(ty.span); - self.dcx() - .emit_err(errors::BadReturnTypeNotationOutput { span, suggestion }); + self.dcx().emit_err(diagnostics::BadReturnTypeNotationOutput { + span, + suggestion, + }); } Box::new(ast::GenericArgs::ParenthesizedElided(span)) @@ -665,7 +667,7 @@ impl<'a> Parser<'a> { // i.e. no multibyte characters, in this range. let span = lo .with_hi(lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count.into())); - self.dcx().emit_err(errors::UnmatchedAngle { + self.dcx().emit_err(diagnostics::UnmatchedAngle { span, plural: snapshot.unmatched_angle_bracket_count > 1, }); @@ -798,7 +800,7 @@ impl<'a> Parser<'a> { c.into() } Some(GenericArg::Lifetime(lt)) => { - let guar = self.dcx().emit_err(errors::LifetimeInEqConstraint { + let guar = self.dcx().emit_err(diagnostics::LifetimeInEqConstraint { span: lt.ident.span, lifetime: lt.ident, binding_label: span, diff --git a/compiler/rustc_parse/src/parser/stmt.rs b/compiler/rustc_parse/src/parser/stmt.rs index a0412c4a7f3df..27a047f598513 100644 --- a/compiler/rustc_parse/src/parser/stmt.rs +++ b/compiler/rustc_parse/src/parser/stmt.rs @@ -23,7 +23,7 @@ use super::{ AllowConstBlockItems, AttrWrapper, BlockMode, FnContext, FnParseMode, ForceCollect, Parser, Restrictions, SemiColonMode, Trailing, UsePreAttrPos, }; -use crate::errors::{self, MalformedLoopLabel}; +use crate::diagnostics::{self, MalformedLoopLabel}; use crate::exp; impl<'a> Parser<'a> { @@ -67,9 +67,9 @@ impl<'a> Parser<'a> { if self.token.is_keyword(kw::Mut) && self.is_keyword_ahead(1, &[kw::Let]) { self.bump(); let mut_let_span = lo.to(self.token.span); - self.dcx().emit_err(errors::InvalidVariableDeclaration { + self.dcx().emit_err(diagnostics::InvalidVariableDeclaration { span: mut_let_span, - sub: errors::InvalidVariableDeclarationSub::SwitchMutLetOrder(mut_let_span), + sub: diagnostics::InvalidVariableDeclarationSub::SwitchMutLetOrder(mut_let_span), }); } @@ -102,7 +102,7 @@ impl<'a> Parser<'a> { self.recover_stmt_local_after_let( lo, attrs, - errors::InvalidVariableDeclarationSub::MissingLet, + diagnostics::InvalidVariableDeclarationSub::MissingLet, force_collect, )? } else if self.is_kw_followed_by_ident(kw::Auto) && self.may_recover() { @@ -110,7 +110,7 @@ impl<'a> Parser<'a> { self.recover_stmt_local_after_let( lo, attrs, - errors::InvalidVariableDeclarationSub::UseLetNotAuto, + diagnostics::InvalidVariableDeclarationSub::UseLetNotAuto, force_collect, )? } else if self.is_kw_followed_by_ident(sym::var) && self.may_recover() { @@ -118,7 +118,7 @@ impl<'a> Parser<'a> { self.recover_stmt_local_after_let( lo, attrs, - errors::InvalidVariableDeclarationSub::UseLetNotVar, + diagnostics::InvalidVariableDeclarationSub::UseLetNotVar, force_collect, )? } else if self.check_path() @@ -181,7 +181,8 @@ impl<'a> Parser<'a> { let bl = self.parse_block()?; // Destructuring assignment ... else. // This is not allowed, but point it out in a nice way. - self.dcx().emit_err(errors::AssignmentElseNotAllowed { span: e.span.to(bl.span) }); + self.dcx() + .emit_err(diagnostics::AssignmentElseNotAllowed { span: e.span.to(bl.span) }); } self.mk_stmt(lo.to(e.span), StmtKind::Expr(e)) } else { @@ -276,12 +277,13 @@ impl<'a> Parser<'a> { && let attrs @ [.., last] = &*attrs.take_for_recovery(self.psess) { if last.is_doc_comment() { - self.dcx().emit_err(errors::DocCommentDoesNotDocumentAnything { + self.dcx().emit_err(diagnostics::DocCommentDoesNotDocumentAnything { span: last.span, missing_comma: None, }); } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) { - self.dcx().emit_err(errors::ExpectedStatementAfterOuterAttr { span: last.span }); + self.dcx() + .emit_err(diagnostics::ExpectedStatementAfterOuterAttr { span: last.span }); } } } @@ -290,7 +292,7 @@ impl<'a> Parser<'a> { &mut self, lo: Span, attrs: AttrWrapper, - subdiagnostic: fn(Span) -> errors::InvalidVariableDeclarationSub, + subdiagnostic: fn(Span) -> diagnostics::InvalidVariableDeclarationSub, force_collect: ForceCollect, ) -> PResult<'a, Stmt> { let stmt = self.collect_tokens(None, attrs, force_collect, |this, attrs| { @@ -303,7 +305,7 @@ impl<'a> Parser<'a> { )) })?; self.dcx() - .emit_err(errors::InvalidVariableDeclaration { span: lo, sub: subdiagnostic(lo) }); + .emit_err(diagnostics::InvalidVariableDeclaration { span: lo, sub: subdiagnostic(lo) }); Ok(stmt) } @@ -312,7 +314,8 @@ impl<'a> Parser<'a> { let lo = super_.unwrap_or(self.prev_token.span); if self.token.is_keyword(kw::Const) && self.look_ahead(1, |t| t.is_ident()) { - self.dcx().emit_err(errors::ConstLetMutuallyExclusive { span: lo.to(self.token.span) }); + self.dcx() + .emit_err(diagnostics::ConstLetMutuallyExclusive { span: lo.to(self.token.span) }); self.bump(); } @@ -426,10 +429,10 @@ impl<'a> Parser<'a> { fn check_let_else_init_bool_expr(&self, init: &ast::Expr) { if let ast::ExprKind::Binary(op, ..) = init.kind { if op.node.is_lazy() { - self.dcx().emit_err(errors::InvalidExpressionInLetElse { + self.dcx().emit_err(diagnostics::InvalidExpressionInLetElse { span: init.span, operator: op.node.as_str(), - sugg: errors::WrapInParentheses::Expression { + sugg: diagnostics::WrapInParentheses::Expression { left: init.span.shrink_to_lo(), right: init.span.shrink_to_hi(), }, @@ -443,20 +446,20 @@ impl<'a> Parser<'a> { let (span, sugg) = match trailing { TrailingBrace::MacCall(mac) => ( mac.span(), - errors::WrapInParentheses::MacroArgs { + diagnostics::WrapInParentheses::MacroArgs { left: mac.args.dspan.open, right: mac.args.dspan.close, }, ), TrailingBrace::Expr(expr) => ( expr.span, - errors::WrapInParentheses::Expression { + diagnostics::WrapInParentheses::Expression { left: expr.span.shrink_to_lo(), right: expr.span.shrink_to_hi(), }, ), }; - self.dcx().emit_err(errors::InvalidCurlyInLetElse { + self.dcx().emit_err(diagnostics::InvalidCurlyInLetElse { span: span.with_lo(span.hi() - BytePos(1)), sugg, }); @@ -481,7 +484,7 @@ impl<'a> Parser<'a> { // `➖` is a U+2796 Heavy Minus Sign Unicode Character) that was recovered as a // `-=`. let extra_op_span = self.psess.source_map().start_point(self.token.span); - self.dcx().emit_err(errors::CompoundAssignmentExpressionInLet { + self.dcx().emit_err(diagnostics::CompoundAssignmentExpressionInLet { span: self.token.span, suggestion: extra_op_span, }); diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index 9b145b757d289..2b12ee68d6497 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -12,7 +12,7 @@ use rustc_span::{ErrorGuaranteed, Ident, Span, kw, sym}; use thin_vec::{ThinVec, thin_vec}; use super::{Parser, PathStyle, SeqSep, TokenType, Trailing}; -use crate::errors::{ +use crate::diagnostics::{ self, AttributeOnEmptyType, AttributeOnType, DynAfterMut, ExpectedFnPathFoundFnKeyword, ExpectedMutOrConstInRawPointerType, FnPtrWithGenerics, FnPtrWithGenericsSugg, HelpUseLatestEdition, InvalidCVariadicType, InvalidDynKeyword, LifetimeAfterMut, @@ -365,10 +365,10 @@ impl<'a> Parser<'a> { parse_plus, ast::Parens::No, )?; - let err = self.dcx().create_err(errors::TransposeDynOrImpl { + let err = self.dcx().create_err(diagnostics::TransposeDynOrImpl { span: kw.span, kw: kw.name.as_str(), - sugg: errors::TransposeDynOrImplSugg { + sugg: diagnostics::TransposeDynOrImplSugg { removal_span, insertion_span: lo.shrink_to_lo(), kw: kw.name.as_str(), @@ -947,7 +947,7 @@ impl<'a> Parser<'a> { if let token::Ident(sym, _) = t.kind { // parse pattern with "'a Sized" we're supposed to give suggestion like // "'a + Sized" - self.dcx().emit_err(errors::MissingPlusBounds { + self.dcx().emit_err(diagnostics::MissingPlusBounds { span: self.token.span, hi: self.token.span.shrink_to_hi(), sym, @@ -1173,9 +1173,10 @@ impl<'a> Parser<'a> { match constness { BoundConstness::Never => {} BoundConstness::Always(span) | BoundConstness::Maybe(span) => { - return self - .dcx() - .emit_err(errors::ModifierLifetime { span, modifier: constness.as_str() }); + return self.dcx().emit_err(diagnostics::ModifierLifetime { + span, + modifier: constness.as_str(), + }); } } @@ -1184,21 +1185,24 @@ impl<'a> Parser<'a> { BoundPolarity::Negative(span) | BoundPolarity::Maybe(span) => { return self .dcx() - .emit_err(errors::ModifierLifetime { span, modifier: polarity.as_str() }); + .emit_err(diagnostics::ModifierLifetime { span, modifier: polarity.as_str() }); } } match asyncness { BoundAsyncness::Normal => {} BoundAsyncness::Async(span) => { - return self - .dcx() - .emit_err(errors::ModifierLifetime { span, modifier: asyncness.as_str() }); + return self.dcx().emit_err(diagnostics::ModifierLifetime { + span, + modifier: asyncness.as_str(), + }); } } if let Some(span) = binder_span { - return self.dcx().emit_err(errors::ModifierLifetime { span, modifier: "for<...>" }); + return self + .dcx() + .emit_err(diagnostics::ModifierLifetime { span, modifier: "for<...>" }); } unreachable!("lifetime bound intercepted in `parse_generic_ty_bound` but no modifiers?") @@ -1229,7 +1233,7 @@ impl<'a> Parser<'a> { && self.is_kw_followed_by_ident(kw::Async) { self.bump(); // eat `async` - self.dcx().emit_err(errors::AsyncBoundModifierIn2015 { + self.dcx().emit_err(diagnostics::AsyncBoundModifierIn2015 { span: self.prev_token.span, help: HelpUseLatestEdition::new(), }); @@ -1265,7 +1269,7 @@ impl<'a> Parser<'a> { let glue = if !constness.is_empty() && !asyncness.is_empty() { " " } else { "" }; let modifiers_concatenated = format!("{constness}{glue}{asyncness}"); - self.dcx().emit_err(errors::PolarityAndModifiers { + self.dcx().emit_err(diagnostics::PolarityAndModifiers { polarity_span, polarity: polarity.as_str(), modifiers_span: modifier_lo.to(modifier_hi), @@ -1327,7 +1331,7 @@ impl<'a> Parser<'a> { if let Some(binder_span) = binder_span { match modifiers.polarity { BoundPolarity::Negative(polarity_span) | BoundPolarity::Maybe(polarity_span) => { - self.dcx().emit_err(errors::BinderAndPolarity { + self.dcx().emit_err(diagnostics::BinderAndPolarity { binder_span, polarity_span, polarity: modifiers.polarity.as_str(), @@ -1346,7 +1350,7 @@ impl<'a> Parser<'a> { if let (more_bound_vars, Some(binder_span)) = self.parse_higher_ranked_binder()? { bound_vars.extend(more_bound_vars); - self.dcx().emit_err(errors::BinderBeforeModifiers { binder_span, modifiers_span }); + self.dcx().emit_err(diagnostics::BinderBeforeModifiers { binder_span, modifiers_span }); } let mut path = if self.token.is_keyword(kw::Fn) @@ -1415,9 +1419,9 @@ impl<'a> Parser<'a> { let bounds = thin_vec![]; self.parse_remaining_bounds(bounds, true)?; self.expect(exp!(CloseParen))?; - self.dcx().emit_err(errors::IncorrectParensTraitBounds { + self.dcx().emit_err(diagnostics::IncorrectParensTraitBounds { span: vec![lo, self.prev_token.span], - sugg: errors::IncorrectParensTraitBoundsSugg { + sugg: diagnostics::IncorrectParensTraitBoundsSugg { wrong_span: leading_token.span.shrink_to_hi().to(lo), new_span: leading_token.span.shrink_to_lo(), }, @@ -1630,7 +1634,7 @@ impl<'a> Parser<'a> { pub(super) fn expect_lifetime(&mut self) -> Lifetime { if let Some((ident, is_raw)) = self.token.lifetime() { if is_raw == IdentIsRaw::No && ident.without_first_quote().is_reserved_lifetime() { - self.dcx().emit_err(errors::KeywordLifetime { span: ident.span }); + self.dcx().emit_err(diagnostics::KeywordLifetime { span: ident.span }); } self.bump();