From 60e82aef64ed62a40ec06357a9946196909ce953 Mon Sep 17 00:00:00 2001 From: est31 Date: Sun, 5 Feb 2023 01:07:25 +0100 Subject: [PATCH 1/7] rustc_expand: remove huge error imports --- compiler/rustc_expand/src/base.rs | 48 ++++++++++++++++--------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 5a48473d5b07c..cf7cff739b340 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -1,11 +1,6 @@ #![deny(rustc::untranslatable_diagnostic)] -use crate::errors::{ - ArgumentNotAttributes, AttrNoArguments, AttributeMetaItem, AttributeSingleWord, - AttributesWrongForm, CannotBeNameOfMacro, ExpectedCommaInList, HelperAttributeNameInvalid, - MacroBodyStability, MacroConstStability, NotAMetaItem, OnlyOneArgument, OnlyOneWord, - ResolveRelativePath, TakesNoArguments, TraceMacro, -}; +use crate::errors; use crate::expand::{self, AstFragment, Invocation}; use crate::module::DirOwnership; @@ -796,13 +791,13 @@ impl SyntaxExtension { .unwrap_or_else(|| (None, helper_attrs)); let (stability, const_stability, body_stability) = attr::find_stability(&sess, attrs, span); if let Some((_, sp)) = const_stability { - sess.emit_err(MacroConstStability { + sess.emit_err(errors::MacroConstStability { span: sp, head_span: sess.source_map().guess_head_span(span), }); } if let Some((_, sp)) = body_stability { - sess.emit_err(MacroBodyStability { + sess.emit_err(errors::MacroBodyStability { span: sp, head_span: sess.source_map().guess_head_span(span), }); @@ -1143,7 +1138,7 @@ impl<'a> ExtCtxt<'a> { } pub fn trace_macros_diag(&mut self) { for (span, notes) in self.expansions.iter() { - let mut db = self.sess.parse_sess.create_note(TraceMacro { span: *span }); + let mut db = self.sess.parse_sess.create_note(errors::TraceMacro { span: *span }); for note in notes { db.note(note); } @@ -1197,7 +1192,7 @@ pub fn resolve_path( .expect("attempting to resolve a file path in an external file"), FileName::DocTest(path, _) => path, other => { - return Err(ResolveRelativePath { + return Err(errors::ResolveRelativePath { span, path: parse_sess.source_map().filename_for_diagnostics(&other).to_string(), } @@ -1279,7 +1274,7 @@ pub fn expr_to_string( /// done as rarely as possible). pub fn check_zero_tts(cx: &ExtCtxt<'_>, span: Span, tts: TokenStream, name: &str) { if !tts.is_empty() { - cx.emit_err(TakesNoArguments { span, name }); + cx.emit_err(errors::TakesNoArguments { span, name }); } } @@ -1307,14 +1302,14 @@ pub fn get_single_str_from_tts( ) -> Option { let mut p = cx.new_parser_from_tts(tts); if p.token == token::Eof { - cx.emit_err(OnlyOneArgument { span, name }); + cx.emit_err(errors::OnlyOneArgument { span, name }); return None; } let ret = parse_expr(&mut p)?; let _ = p.eat(&token::Comma); if p.token != token::Eof { - cx.emit_err(OnlyOneArgument { span, name }); + cx.emit_err(errors::OnlyOneArgument { span, name }); } expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s) } @@ -1336,7 +1331,7 @@ pub fn get_exprs_from_tts(cx: &mut ExtCtxt<'_>, tts: TokenStream) -> Option trait_ident, _ => { - diag.emit_err(OnlyOneWord { span: trait_attr.span }); + diag.emit_err(errors::OnlyOneWord { span: trait_attr.span }); return None; } }; if !trait_ident.name.can_be_raw() { - diag.emit_err(CannotBeNameOfMacro { span: trait_attr.span, trait_ident, macro_type }); + diag.emit_err(errors::CannotBeNameOfMacro { + span: trait_attr.span, + trait_ident, + macro_type, + }); } let attributes_attr = list.get(1); let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr { if !attr.has_name(sym::attributes) { - diag.emit_err(ArgumentNotAttributes { span: attr.span() }); + diag.emit_err(errors::ArgumentNotAttributes { span: attr.span() }); } attr.meta_item_list() .unwrap_or_else(|| { - diag.emit_err(AttributesWrongForm { span: attr.span() }); + diag.emit_err(errors::AttributesWrongForm { span: attr.span() }); &[] }) .iter() .filter_map(|attr| { let Some(attr) = attr.meta_item() else { - diag.emit_err(AttributeMetaItem { span: attr.span() }); + diag.emit_err(errors::AttributeMetaItem { span: attr.span() }); return None; }; let ident = match attr.ident() { Some(ident) if attr.is_word() => ident, _ => { - diag.emit_err(AttributeSingleWord { span: attr.span }); + diag.emit_err(errors::AttributeSingleWord { span: attr.span }); return None; } }; if !ident.name.can_be_raw() { - diag.emit_err(HelperAttributeNameInvalid { span: attr.span, name: ident }); + diag.emit_err(errors::HelperAttributeNameInvalid { + span: attr.span, + name: ident, + }); } Some(ident.name) From 4442f13b030162319cfe53335d4abc369f75214b Mon Sep 17 00:00:00 2001 From: est31 Date: Sun, 5 Feb 2023 01:58:22 +0100 Subject: [PATCH 2/7] rustc_metadata: remove huge error imports --- compiler/rustc_metadata/src/creader.rs | 28 +++--- compiler/rustc_metadata/src/locator.rs | 50 +++++----- compiler/rustc_metadata/src/native_libs.rs | 103 ++++++++++----------- 3 files changed, 89 insertions(+), 92 deletions(-) diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index 44d6c587da3df..21652063b4716 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -1,10 +1,6 @@ //! Validates all used crates and extern libraries and loads their metadata -use crate::errors::{ - ConflictingAllocErrorHandler, ConflictingGlobalAlloc, CrateNotPanicRuntime, - GlobalAllocRequired, NoMultipleAllocErrorHandler, NoMultipleGlobalAlloc, NoPanicStrategy, - NoTransitiveNeedsDep, NotProfilerRuntime, ProfilerBuiltinsNeedsCore, -}; +use crate::errors; use crate::locator::{CrateError, CrateLocator, CratePaths}; use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob}; @@ -768,10 +764,11 @@ impl<'a> CrateLoader<'a> { // Sanity check the loaded crate to ensure it is indeed a panic runtime // and the panic strategy is indeed what we thought it was. if !data.is_panic_runtime() { - self.sess.emit_err(CrateNotPanicRuntime { crate_name: name }); + self.sess.emit_err(errors::CrateNotPanicRuntime { crate_name: name }); } if data.required_panic_strategy() != Some(desired_strategy) { - self.sess.emit_err(NoPanicStrategy { crate_name: name, strategy: desired_strategy }); + self.sess + .emit_err(errors::NoPanicStrategy { crate_name: name, strategy: desired_strategy }); } self.cstore.injected_panic_runtime = Some(cnum); @@ -791,7 +788,7 @@ impl<'a> CrateLoader<'a> { let name = Symbol::intern(&self.sess.opts.unstable_opts.profiler_runtime); if name == sym::profiler_builtins && self.sess.contains_name(&krate.attrs, sym::no_core) { - self.sess.emit_err(ProfilerBuiltinsNeedsCore); + self.sess.emit_err(errors::ProfilerBuiltinsNeedsCore); } let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; }; @@ -799,21 +796,22 @@ impl<'a> CrateLoader<'a> { // Sanity check the loaded crate to ensure it is indeed a profiler runtime if !data.is_profiler_runtime() { - self.sess.emit_err(NotProfilerRuntime { crate_name: name }); + self.sess.emit_err(errors::NotProfilerRuntime { crate_name: name }); } } fn inject_allocator_crate(&mut self, krate: &ast::Crate) { self.cstore.has_global_allocator = match &*global_allocator_spans(&self.sess, krate) { [span1, span2, ..] => { - self.sess.emit_err(NoMultipleGlobalAlloc { span2: *span2, span1: *span1 }); + self.sess.emit_err(errors::NoMultipleGlobalAlloc { span2: *span2, span1: *span1 }); true } spans => !spans.is_empty(), }; self.cstore.has_alloc_error_handler = match &*alloc_error_handler_spans(&self.sess, krate) { [span1, span2, ..] => { - self.sess.emit_err(NoMultipleAllocErrorHandler { span2: *span2, span1: *span1 }); + self.sess + .emit_err(errors::NoMultipleAllocErrorHandler { span2: *span2, span1: *span1 }); true } spans => !spans.is_empty(), @@ -849,7 +847,7 @@ impl<'a> CrateLoader<'a> { if data.has_global_allocator() { match global_allocator { Some(other_crate) => { - self.sess.emit_err(ConflictingGlobalAlloc { + self.sess.emit_err(errors::ConflictingGlobalAlloc { crate_name: data.name(), other_crate_name: other_crate, }); @@ -864,7 +862,7 @@ impl<'a> CrateLoader<'a> { if data.has_alloc_error_handler() { match alloc_error_handler { Some(other_crate) => { - self.sess.emit_err(ConflictingAllocErrorHandler { + self.sess.emit_err(errors::ConflictingAllocErrorHandler { crate_name: data.name(), other_crate_name: other_crate, }); @@ -884,7 +882,7 @@ impl<'a> CrateLoader<'a> { if !self.sess.contains_name(&krate.attrs, sym::default_lib_allocator) && !self.cstore.iter_crate_data().any(|(_, data)| data.has_default_lib_allocator()) { - self.sess.emit_err(GlobalAllocRequired); + self.sess.emit_err(errors::GlobalAllocRequired); } self.cstore.allocator_kind = Some(AllocatorKind::Default); } @@ -917,7 +915,7 @@ impl<'a> CrateLoader<'a> { for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) { let data = self.cstore.get_crate_data(dep); if needs_dep(&data) { - self.sess.emit_err(NoTransitiveNeedsDep { + self.sess.emit_err(errors::NoTransitiveNeedsDep { crate_name: self.cstore.get_crate_data(krate).name(), needs_crate_name: what, deps_crate_name: data.name(), diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index 0f5f74007c106..74f91a14ea9ae 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -213,12 +213,7 @@ //! metadata::locator or metadata::creader for all the juicy details! use crate::creader::Library; -use crate::errors::{ - CannotFindCrate, CrateLocationUnknownType, DlError, ExternLocationNotExist, - ExternLocationNotFile, FoundStaticlib, IncompatibleRustc, InvalidMetadataFiles, - LibFilenameForm, MultipleCandidates, NewerCrateVersion, NoCrateWithTriple, NoDylibPlugin, - NonAsciiName, StableCrateIdCollision, SymbolConflictsCurrent, SymbolConflictsOthers, -}; +use crate::errors; use crate::rmeta::{rustc_version, MetadataBlob, METADATA_HEADER}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; @@ -980,28 +975,28 @@ impl CrateError { pub(crate) fn report(self, sess: &Session, span: Span, missing_core: bool) { match self { CrateError::NonAsciiName(crate_name) => { - sess.emit_err(NonAsciiName { span, crate_name }); + sess.emit_err(errors::NonAsciiName { span, crate_name }); } CrateError::ExternLocationNotExist(crate_name, loc) => { - sess.emit_err(ExternLocationNotExist { span, crate_name, location: &loc }); + sess.emit_err(errors::ExternLocationNotExist { span, crate_name, location: &loc }); } CrateError::ExternLocationNotFile(crate_name, loc) => { - sess.emit_err(ExternLocationNotFile { span, crate_name, location: &loc }); + sess.emit_err(errors::ExternLocationNotFile { span, crate_name, location: &loc }); } CrateError::MultipleCandidates(crate_name, flavor, candidates) => { - sess.emit_err(MultipleCandidates { span, crate_name, flavor, candidates }); + sess.emit_err(errors::MultipleCandidates { span, crate_name, flavor, candidates }); } CrateError::SymbolConflictsCurrent(root_name) => { - sess.emit_err(SymbolConflictsCurrent { span, crate_name: root_name }); + sess.emit_err(errors::SymbolConflictsCurrent { span, crate_name: root_name }); } CrateError::SymbolConflictsOthers(root_name) => { - sess.emit_err(SymbolConflictsOthers { span, crate_name: root_name }); + sess.emit_err(errors::SymbolConflictsOthers { span, crate_name: root_name }); } CrateError::StableCrateIdCollision(crate_name0, crate_name1) => { - sess.emit_err(StableCrateIdCollision { span, crate_name0, crate_name1 }); + sess.emit_err(errors::StableCrateIdCollision { span, crate_name0, crate_name1 }); } CrateError::DlOpen(s) | CrateError::DlSym(s) => { - sess.emit_err(DlError { span, err: s }); + sess.emit_err(errors::DlError { span, err: s }); } CrateError::LocatorCombined(locator) => { let crate_name = locator.crate_name; @@ -1012,8 +1007,12 @@ impl CrateError { if !locator.crate_rejections.via_filename.is_empty() { let mismatches = locator.crate_rejections.via_filename.iter(); for CrateMismatch { path, .. } in mismatches { - sess.emit_err(CrateLocationUnknownType { span, path: &path, crate_name }); - sess.emit_err(LibFilenameForm { + sess.emit_err(errors::CrateLocationUnknownType { + span, + path: &path, + crate_name, + }); + sess.emit_err(errors::LibFilenameForm { span, dll_prefix: &locator.dll_prefix, dll_suffix: &locator.dll_suffix, @@ -1039,7 +1038,7 @@ impl CrateError { )); } } - sess.emit_err(NewerCrateVersion { + sess.emit_err(errors::NewerCrateVersion { span, crate_name: crate_name, add_info, @@ -1055,7 +1054,7 @@ impl CrateError { path.display(), )); } - sess.emit_err(NoCrateWithTriple { + sess.emit_err(errors::NoCrateWithTriple { span, crate_name, locator_triple: locator.triple.triple(), @@ -1071,7 +1070,12 @@ impl CrateError { path.display() )); } - sess.emit_err(FoundStaticlib { span, crate_name, add_info, found_crates }); + sess.emit_err(errors::FoundStaticlib { + span, + crate_name, + add_info, + found_crates, + }); } else if !locator.crate_rejections.via_version.is_empty() { let mismatches = locator.crate_rejections.via_version.iter(); for CrateMismatch { path, got } in mismatches { @@ -1082,7 +1086,7 @@ impl CrateError { path.display(), )); } - sess.emit_err(IncompatibleRustc { + sess.emit_err(errors::IncompatibleRustc { span, crate_name, add_info, @@ -1094,14 +1098,14 @@ impl CrateError { for CrateMismatch { path: _, got } in locator.crate_rejections.via_invalid { crate_rejections.push(got); } - sess.emit_err(InvalidMetadataFiles { + sess.emit_err(errors::InvalidMetadataFiles { span, crate_name, add_info, crate_rejections, }); } else { - sess.emit_err(CannotFindCrate { + sess.emit_err(errors::CannotFindCrate { span, crate_name, add_info, @@ -1118,7 +1122,7 @@ impl CrateError { } } CrateError::NonDylibPlugin(crate_name) => { - sess.emit_err(NoDylibPlugin { span, crate_name }); + sess.emit_err(errors::NoDylibPlugin { span, crate_name }); } } } diff --git a/compiler/rustc_metadata/src/native_libs.rs b/compiler/rustc_metadata/src/native_libs.rs index a5910100786ec..e263fc7483537 100644 --- a/compiler/rustc_metadata/src/native_libs.rs +++ b/compiler/rustc_metadata/src/native_libs.rs @@ -13,17 +13,7 @@ use rustc_session::Session; use rustc_span::symbol::{sym, Symbol}; use rustc_target::spec::abi::Abi; -use crate::errors::{ - AsNeededCompatibility, BundleNeedsStatic, EmptyLinkName, EmptyRenamingTarget, - FrameworkOnlyWindows, ImportNameTypeForm, ImportNameTypeRaw, ImportNameTypeX86, - IncompatibleWasmLink, InvalidLinkModifier, LibFrameworkApple, LinkCfgForm, - LinkCfgSinglePredicate, LinkFrameworkApple, LinkKindForm, LinkModifiersForm, LinkNameForm, - LinkOrdinalRawDylib, LinkRequiresName, MissingNativeLibrary, MultipleCfgs, - MultipleImportNameType, MultipleKindsInLink, MultipleLinkModifiers, MultipleModifiers, - MultipleNamesInLink, MultipleRenamings, MultipleWasmImport, NoLinkModOverride, RawDylibNoNul, - RenamingNoLink, UnexpectedLinkArg, UnknownImportNameType, UnknownLinkKind, UnknownLinkModifier, - UnsupportedAbi, UnsupportedAbiI686, WasmImportForm, WholeArchiveNeedsStatic, -}; +use crate::errors; use std::path::PathBuf; @@ -52,7 +42,7 @@ pub fn find_native_static_library( } } - sess.emit_fatal(MissingNativeLibrary::new(name, verbatim)); + sess.emit_fatal(errors::MissingNativeLibrary::new(name, verbatim)); } fn find_bundled_library( @@ -129,26 +119,26 @@ impl<'tcx> Collector<'tcx> { match item.name_or_empty() { sym::name => { if name.is_some() { - sess.emit_err(MultipleNamesInLink { span: item.span() }); + sess.emit_err(errors::MultipleNamesInLink { span: item.span() }); continue; } let Some(link_name) = item.value_str() else { - sess.emit_err(LinkNameForm { span: item.span() }); + sess.emit_err(errors::LinkNameForm { span: item.span() }); continue; }; let span = item.name_value_literal_span().unwrap(); if link_name.is_empty() { - sess.emit_err(EmptyLinkName { span }); + sess.emit_err(errors::EmptyLinkName { span }); } name = Some((link_name, span)); } sym::kind => { if kind.is_some() { - sess.emit_err(MultipleKindsInLink { span: item.span() }); + sess.emit_err(errors::MultipleKindsInLink { span: item.span() }); continue; } let Some(link_kind) = item.value_str() else { - sess.emit_err(LinkKindForm { span: item.span() }); + sess.emit_err(errors::LinkKindForm { span: item.span() }); continue; }; @@ -158,13 +148,13 @@ impl<'tcx> Collector<'tcx> { "dylib" => NativeLibKind::Dylib { as_needed: None }, "framework" => { if !sess.target.is_like_osx { - sess.emit_err(LinkFrameworkApple { span }); + sess.emit_err(errors::LinkFrameworkApple { span }); } NativeLibKind::Framework { as_needed: None } } "raw-dylib" => { if !sess.target.is_like_windows { - sess.emit_err(FrameworkOnlyWindows { span }); + sess.emit_err(errors::FrameworkOnlyWindows { span }); } else if !features.raw_dylib && sess.target.arch == "x86" { feature_err( &sess.parse_sess, @@ -177,7 +167,7 @@ impl<'tcx> Collector<'tcx> { NativeLibKind::RawDylib } kind => { - sess.emit_err(UnknownLinkKind { span, kind }); + sess.emit_err(errors::UnknownLinkKind { span, kind }); continue; } }; @@ -185,26 +175,26 @@ impl<'tcx> Collector<'tcx> { } sym::modifiers => { if modifiers.is_some() { - sess.emit_err(MultipleLinkModifiers { span: item.span() }); + sess.emit_err(errors::MultipleLinkModifiers { span: item.span() }); continue; } let Some(link_modifiers) = item.value_str() else { - sess.emit_err(LinkModifiersForm { span: item.span() }); + sess.emit_err(errors::LinkModifiersForm { span: item.span() }); continue; }; modifiers = Some((link_modifiers, item.name_value_literal_span().unwrap())); } sym::cfg => { if cfg.is_some() { - sess.emit_err(MultipleCfgs { span: item.span() }); + sess.emit_err(errors::MultipleCfgs { span: item.span() }); continue; } let Some(link_cfg) = item.meta_item_list() else { - sess.emit_err(LinkCfgForm { span: item.span() }); + sess.emit_err(errors::LinkCfgForm { span: item.span() }); continue; }; let [NestedMetaItem::MetaItem(link_cfg)] = link_cfg else { - sess.emit_err(LinkCfgSinglePredicate { span: item.span() }); + sess.emit_err(errors::LinkCfgSinglePredicate { span: item.span() }); continue; }; if !features.link_cfg { @@ -220,26 +210,26 @@ impl<'tcx> Collector<'tcx> { } sym::wasm_import_module => { if wasm_import_module.is_some() { - sess.emit_err(MultipleWasmImport { span: item.span() }); + sess.emit_err(errors::MultipleWasmImport { span: item.span() }); continue; } let Some(link_wasm_import_module) = item.value_str() else { - sess.emit_err(WasmImportForm { span: item.span() }); + sess.emit_err(errors::WasmImportForm { span: item.span() }); continue; }; wasm_import_module = Some((link_wasm_import_module, item.span())); } sym::import_name_type => { if import_name_type.is_some() { - sess.emit_err(MultipleImportNameType { span: item.span() }); + sess.emit_err(errors::MultipleImportNameType { span: item.span() }); continue; } let Some(link_import_name_type) = item.value_str() else { - sess.emit_err(ImportNameTypeForm { span: item.span() }); + sess.emit_err(errors::ImportNameTypeForm { span: item.span() }); continue; }; if self.tcx.sess.target.arch != "x86" { - sess.emit_err(ImportNameTypeX86 { span: item.span() }); + sess.emit_err(errors::ImportNameTypeX86 { span: item.span() }); continue; } @@ -248,7 +238,7 @@ impl<'tcx> Collector<'tcx> { "noprefix" => PeImportNameType::NoPrefix, "undecorated" => PeImportNameType::Undecorated, import_name_type => { - sess.emit_err(UnknownImportNameType { + sess.emit_err(errors::UnknownImportNameType { span: item.span(), import_name_type, }); @@ -268,7 +258,7 @@ impl<'tcx> Collector<'tcx> { import_name_type = Some((link_import_name_type, item.span())); } _ => { - sess.emit_err(UnexpectedLinkArg { span: item.span() }); + sess.emit_err(errors::UnexpectedLinkArg { span: item.span() }); } } } @@ -280,7 +270,7 @@ impl<'tcx> Collector<'tcx> { let (modifier, value) = match modifier.strip_prefix(&['+', '-']) { Some(m) => (m, modifier.starts_with('+')), None => { - sess.emit_err(InvalidLinkModifier { span }); + sess.emit_err(errors::InvalidLinkModifier { span }); continue; } }; @@ -298,7 +288,7 @@ impl<'tcx> Collector<'tcx> { } let assign_modifier = |dst: &mut Option| { if dst.is_some() { - sess.emit_err(MultipleModifiers { span, modifier }); + sess.emit_err(errors::MultipleModifiers { span, modifier }); } else { *dst = Some(value); } @@ -308,7 +298,7 @@ impl<'tcx> Collector<'tcx> { assign_modifier(bundle) } ("bundle", _) => { - sess.emit_err(BundleNeedsStatic { span }); + sess.emit_err(errors::BundleNeedsStatic { span }); } ("verbatim", _) => assign_modifier(&mut verbatim), @@ -317,7 +307,7 @@ impl<'tcx> Collector<'tcx> { assign_modifier(whole_archive) } ("whole-archive", _) => { - sess.emit_err(WholeArchiveNeedsStatic { span }); + sess.emit_err(errors::WholeArchiveNeedsStatic { span }); } ("as-needed", Some(NativeLibKind::Dylib { as_needed })) @@ -326,11 +316,11 @@ impl<'tcx> Collector<'tcx> { assign_modifier(as_needed) } ("as-needed", _) => { - sess.emit_err(AsNeededCompatibility { span }); + sess.emit_err(errors::AsNeededCompatibility { span }); } _ => { - sess.emit_err(UnknownLinkModifier { span, modifier }); + sess.emit_err(errors::UnknownLinkModifier { span, modifier }); } } } @@ -338,23 +328,23 @@ impl<'tcx> Collector<'tcx> { if let Some((_, span)) = wasm_import_module { if name.is_some() || kind.is_some() || modifiers.is_some() || cfg.is_some() { - sess.emit_err(IncompatibleWasmLink { span }); + sess.emit_err(errors::IncompatibleWasmLink { span }); } } else if name.is_none() { - sess.emit_err(LinkRequiresName { span: m.span }); + sess.emit_err(errors::LinkRequiresName { span: m.span }); } // Do this outside of the loop so that `import_name_type` can be specified before `kind`. if let Some((_, span)) = import_name_type { if kind != Some(NativeLibKind::RawDylib) { - sess.emit_err(ImportNameTypeRaw { span }); + sess.emit_err(errors::ImportNameTypeRaw { span }); } } let dll_imports = match kind { Some(NativeLibKind::RawDylib) => { if let Some((name, span)) = name && name.as_str().contains('\0') { - sess.emit_err(RawDylibNoNul { span }); + sess.emit_err(errors::RawDylibNoNul { span }); } foreign_mod_items .iter() @@ -383,7 +373,9 @@ impl<'tcx> Collector<'tcx> { .iter() .find(|a| a.has_name(sym::link_ordinal)) .unwrap(); - sess.emit_err(LinkOrdinalRawDylib { span: link_ordinal_attr.span }); + sess.emit_err(errors::LinkOrdinalRawDylib { + span: link_ordinal_attr.span, + }); } } @@ -414,7 +406,7 @@ impl<'tcx> Collector<'tcx> { for lib in &self.tcx.sess.opts.libs { if let NativeLibKind::Framework { .. } = lib.kind && !self.tcx.sess.target.is_like_osx { // Cannot check this when parsing options because the target is not yet available. - self.tcx.sess.emit_err(LibFrameworkApple); + self.tcx.sess.emit_err(errors::LibFrameworkApple); } if let Some(ref new_name) = lib.new_name { let any_duplicate = self @@ -423,11 +415,11 @@ impl<'tcx> Collector<'tcx> { .filter_map(|lib| lib.name.as_ref()) .any(|n| n.as_str() == lib.name); if new_name.is_empty() { - self.tcx.sess.emit_err(EmptyRenamingTarget { lib_name: &lib.name }); + self.tcx.sess.emit_err(errors::EmptyRenamingTarget { lib_name: &lib.name }); } else if !any_duplicate { - self.tcx.sess.emit_err(RenamingNoLink { lib_name: &lib.name }); + self.tcx.sess.emit_err(errors::RenamingNoLink { lib_name: &lib.name }); } else if !renames.insert(&lib.name) { - self.tcx.sess.emit_err(MultipleRenamings { lib_name: &lib.name }); + self.tcx.sess.emit_err(errors::MultipleRenamings { lib_name: &lib.name }); } } } @@ -453,12 +445,15 @@ impl<'tcx> Collector<'tcx> { // explicit `:rename` in particular. if lib.has_modifiers() || passed_lib.has_modifiers() { match lib.foreign_module { - Some(def_id) => self.tcx.sess.emit_err(NoLinkModOverride { - span: Some(self.tcx.def_span(def_id)), - }), - None => { - self.tcx.sess.emit_err(NoLinkModOverride { span: None }) + Some(def_id) => { + self.tcx.sess.emit_err(errors::NoLinkModOverride { + span: Some(self.tcx.def_span(def_id)), + }) } + None => self + .tcx + .sess + .emit_err(errors::NoLinkModOverride { span: None }), }; } if passed_lib.kind != NativeLibKind::Unspecified { @@ -542,14 +537,14 @@ impl<'tcx> Collector<'tcx> { DllCallingConvention::Vectorcall(self.i686_arg_list_size(item)) } _ => { - self.tcx.sess.emit_fatal(UnsupportedAbiI686 { span: item.span }); + self.tcx.sess.emit_fatal(errors::UnsupportedAbiI686 { span: item.span }); } } } else { match abi { Abi::C { .. } | Abi::Win64 { .. } | Abi::System { .. } => DllCallingConvention::C, _ => { - self.tcx.sess.emit_fatal(UnsupportedAbi { span: item.span }); + self.tcx.sess.emit_fatal(errors::UnsupportedAbi { span: item.span }); } } }; From 3478b162f35650acc009cd6ce9919a6251e81a33 Mon Sep 17 00:00:00 2001 From: est31 Date: Sun, 5 Feb 2023 02:09:56 +0100 Subject: [PATCH 3/7] rustc_const_eval: remove huge error imports --- .../src/transform/check_consts/ops.rs | 72 +++++++++---------- 1 file changed, 35 insertions(+), 37 deletions(-) diff --git a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs index 0cb5d2ff8c719..782a62accad9e 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs @@ -22,13 +22,7 @@ use rustc_span::{BytePos, Pos, Span, Symbol}; use rustc_trait_selection::traits::SelectionContext; use super::ConstCx; -use crate::errors::{ - InteriorMutabilityBorrow, InteriorMutableDataRefer, MutDerefErr, NonConstFmtMacroCall, - NonConstFnCall, NonConstOpErr, PanicNonStrErr, RawPtrToIntErr, StaticAccessErr, - TransientMutBorrowErr, TransientMutBorrowErrRaw, UnallowedFnPointerCall, - UnallowedHeapAllocations, UnallowedInlineAsm, UnallowedMutableRefs, UnallowedMutableRefsRaw, - UnallowedOpInConstContext, UnstableConstFn, -}; +use crate::errors; use crate::util::{call_kind, CallDesugaringKind, CallKind}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -99,7 +93,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallIndirect { ccx: &ConstCx<'_, 'tcx>, span: Span, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { - ccx.tcx.sess.create_err(UnallowedFnPointerCall { span, kind: ccx.const_kind() }) + ccx.tcx.sess.create_err(errors::UnallowedFnPointerCall { span, kind: ccx.const_kind() }) } } @@ -303,10 +297,11 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { diag_trait(&mut err, self_ty, tcx.require_lang_item(LangItem::Deref, Some(span))); err } - _ if tcx.opt_parent(callee) == tcx.get_diagnostic_item(sym::ArgumentV1Methods) => { - ccx.tcx.sess.create_err(NonConstFmtMacroCall { span, kind: ccx.const_kind() }) - } - _ => ccx.tcx.sess.create_err(NonConstFnCall { + _ if tcx.opt_parent(callee) == tcx.get_diagnostic_item(sym::ArgumentV1Methods) => ccx + .tcx + .sess + .create_err(errors::NonConstFmtMacroCall { span, kind: ccx.const_kind() }), + _ => ccx.tcx.sess.create_err(errors::NonConstFnCall { span, def_path_str: ccx.tcx.def_path_str_with_substs(callee, substs), kind: ccx.const_kind(), @@ -351,7 +346,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallUnstable { let mut err = ccx .tcx .sess - .create_err(UnstableConstFn { span, def_path: ccx.tcx.def_path_str(def_id) }); + .create_err(errors::UnstableConstFn { span, def_path: ccx.tcx.def_path_str(def_id) }); if ccx.is_const_stable_const_fn() { err.help("const-stable functions can only call other const-stable functions"); @@ -387,11 +382,11 @@ impl<'tcx> NonConstOp<'tcx> for Generator { let msg = format!("{}s are not allowed in {}s", self.0.descr(), ccx.const_kind()); if let hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) = self.0 { ccx.tcx.sess.create_feature_err( - UnallowedOpInConstContext { span, msg }, + errors::UnallowedOpInConstContext { span, msg }, sym::const_async_blocks, ) } else { - ccx.tcx.sess.create_err(UnallowedOpInConstContext { span, msg }) + ccx.tcx.sess.create_err(errors::UnallowedOpInConstContext { span, msg }) } } } @@ -404,7 +399,7 @@ impl<'tcx> NonConstOp<'tcx> for HeapAllocation { ccx: &ConstCx<'_, 'tcx>, span: Span, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { - ccx.tcx.sess.create_err(UnallowedHeapAllocations { + ccx.tcx.sess.create_err(errors::UnallowedHeapAllocations { span, kind: ccx.const_kind(), teach: ccx.tcx.sess.teach(&error_code!(E0010)).then_some(()), @@ -420,7 +415,7 @@ impl<'tcx> NonConstOp<'tcx> for InlineAsm { ccx: &ConstCx<'_, 'tcx>, span: Span, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { - ccx.tcx.sess.create_err(UnallowedInlineAsm { span, kind: ccx.const_kind() }) + ccx.tcx.sess.create_err(errors::UnallowedInlineAsm { span, kind: ccx.const_kind() }) } } @@ -471,7 +466,9 @@ impl<'tcx> NonConstOp<'tcx> for TransientCellBorrow { ccx: &ConstCx<'_, 'tcx>, span: Span, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { - ccx.tcx.sess.create_feature_err(InteriorMutabilityBorrow { span }, sym::const_refs_to_cell) + ccx.tcx + .sess + .create_feature_err(errors::InteriorMutabilityBorrow { span }, sym::const_refs_to_cell) } } @@ -488,14 +485,14 @@ impl<'tcx> NonConstOp<'tcx> for CellBorrow { ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { // FIXME: Maybe a more elegant solution to this if else case if let hir::ConstContext::Static(_) = ccx.const_kind() { - ccx.tcx.sess.create_err(InteriorMutableDataRefer { + ccx.tcx.sess.create_err(errors::InteriorMutableDataRefer { span, opt_help: Some(()), kind: ccx.const_kind(), teach: ccx.tcx.sess.teach(&error_code!(E0492)).then_some(()), }) } else { - ccx.tcx.sess.create_err(InteriorMutableDataRefer { + ccx.tcx.sess.create_err(errors::InteriorMutableDataRefer { span, opt_help: None, kind: ccx.const_kind(), @@ -528,12 +525,12 @@ impl<'tcx> NonConstOp<'tcx> for MutBorrow { span: Span, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { match self.0 { - hir::BorrowKind::Raw => ccx.tcx.sess.create_err(UnallowedMutableRefsRaw { + hir::BorrowKind::Raw => ccx.tcx.sess.create_err(errors::UnallowedMutableRefsRaw { span, kind: ccx.const_kind(), teach: ccx.tcx.sess.teach(&error_code!(E0764)).then_some(()), }), - hir::BorrowKind::Ref => ccx.tcx.sess.create_err(UnallowedMutableRefs { + hir::BorrowKind::Ref => ccx.tcx.sess.create_err(errors::UnallowedMutableRefs { span, kind: ccx.const_kind(), teach: ccx.tcx.sess.teach(&error_code!(E0764)).then_some(()), @@ -557,14 +554,14 @@ impl<'tcx> NonConstOp<'tcx> for TransientMutBorrow { ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { let kind = ccx.const_kind(); match self.0 { - hir::BorrowKind::Raw => ccx - .tcx - .sess - .create_feature_err(TransientMutBorrowErrRaw { span, kind }, sym::const_mut_refs), - hir::BorrowKind::Ref => ccx - .tcx - .sess - .create_feature_err(TransientMutBorrowErr { span, kind }, sym::const_mut_refs), + hir::BorrowKind::Raw => ccx.tcx.sess.create_feature_err( + errors::TransientMutBorrowErrRaw { span, kind }, + sym::const_mut_refs, + ), + hir::BorrowKind::Ref => ccx.tcx.sess.create_feature_err( + errors::TransientMutBorrowErr { span, kind }, + sym::const_mut_refs, + ), } } } @@ -586,9 +583,10 @@ impl<'tcx> NonConstOp<'tcx> for MutDeref { ccx: &ConstCx<'_, 'tcx>, span: Span, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { - ccx.tcx - .sess - .create_feature_err(MutDerefErr { span, kind: ccx.const_kind() }, sym::const_mut_refs) + ccx.tcx.sess.create_feature_err( + errors::MutDerefErr { span, kind: ccx.const_kind() }, + sym::const_mut_refs, + ) } } @@ -601,7 +599,7 @@ impl<'tcx> NonConstOp<'tcx> for PanicNonStr { ccx: &ConstCx<'_, 'tcx>, span: Span, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { - ccx.tcx.sess.create_err(PanicNonStrErr { span }) + ccx.tcx.sess.create_err(errors::PanicNonStrErr { span }) } } @@ -652,7 +650,7 @@ impl<'tcx> NonConstOp<'tcx> for RawPtrToIntCast { ccx: &ConstCx<'_, 'tcx>, span: Span, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { - ccx.tcx.sess.create_err(RawPtrToIntErr { span }) + ccx.tcx.sess.create_err(errors::RawPtrToIntErr { span }) } } @@ -673,7 +671,7 @@ impl<'tcx> NonConstOp<'tcx> for StaticAccess { ccx: &ConstCx<'_, 'tcx>, span: Span, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { - ccx.tcx.sess.create_err(StaticAccessErr { + ccx.tcx.sess.create_err(errors::StaticAccessErr { span, kind: ccx.const_kind(), teach: ccx.tcx.sess.teach(&error_code!(E0013)).then_some(()), @@ -690,7 +688,7 @@ impl<'tcx> NonConstOp<'tcx> for ThreadLocalAccess { ccx: &ConstCx<'_, 'tcx>, span: Span, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { - ccx.tcx.sess.create_err(NonConstOpErr { span }) + ccx.tcx.sess.create_err(errors::NonConstOpErr { span }) } } From a399f0ca8429db2399f007cdb12dad687b8973d9 Mon Sep 17 00:00:00 2001 From: est31 Date: Sun, 5 Feb 2023 02:49:50 +0100 Subject: [PATCH 4/7] rustc_passes: remove huge error imports --- compiler/rustc_passes/src/check_attr.rs | 68 +++++++++++++------------ compiler/rustc_passes/src/stability.rs | 45 ++++++++-------- 2 files changed, 57 insertions(+), 56 deletions(-) diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 644d701be0caa..238ec9ca30f70 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -4,11 +4,7 @@ //! conflicts between multiple such attributes attached to the same //! item. -use crate::errors::{ - self, AttrApplication, DebugVisualizerUnreadable, InvalidAttrAtCrateLevel, ObjectLifetimeErr, - OnlyHasEffectOn, ProcMacroDiffArguments, ProcMacroInvalidAbi, ProcMacroMissingArguments, - ProcMacroTypeError, ProcMacroUnsafe, TransparentIncompatible, UnrecognizedReprHint, -}; +use crate::errors; use rustc_ast::{ast, AttrStyle, Attribute, LitKind, MetaItemKind, MetaItemLit, NestedMetaItem}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{fluent, Applicability, IntoDiagnosticArg, MultiSpan}; @@ -399,7 +395,7 @@ impl CheckAttrVisitor<'_> { UNUSED_ATTRIBUTES, hir_id, attr.span, - OnlyHasEffectOn { + errors::OnlyHasEffectOn { attr_name: attr.name_or_empty(), target_name: allowed_target.name().replace(' ', "_"), }, @@ -468,7 +464,7 @@ impl CheckAttrVisitor<'_> { ObjectLifetimeDefault::Param(def_id) => tcx.item_name(def_id).to_string(), ObjectLifetimeDefault::Ambiguous => "Ambiguous".to_owned(), }; - tcx.sess.emit_err(ObjectLifetimeErr { span: p.span, repr }); + tcx.sess.emit_err(errors::ObjectLifetimeErr { span: p.span, repr }); } } } @@ -1715,7 +1711,7 @@ impl CheckAttrVisitor<'_> { match target { Target::Struct | Target::Union | Target::Enum => continue, _ => { - self.tcx.sess.emit_err(AttrApplication::StructEnumUnion { + self.tcx.sess.emit_err(errors::AttrApplication::StructEnumUnion { hint_span: hint.span(), span, }); @@ -1736,16 +1732,18 @@ impl CheckAttrVisitor<'_> { match target { Target::Struct | Target::Union | Target::Enum | Target::Fn => continue, _ => { - self.tcx.sess.emit_err(AttrApplication::StructEnumFunctionUnion { - hint_span: hint.span(), - span, - }); + self.tcx.sess.emit_err( + errors::AttrApplication::StructEnumFunctionUnion { + hint_span: hint.span(), + span, + }, + ); } } } sym::packed => { if target != Target::Struct && target != Target::Union { - self.tcx.sess.emit_err(AttrApplication::StructUnion { + self.tcx.sess.emit_err(errors::AttrApplication::StructUnion { hint_span: hint.span(), span, }); @@ -1756,9 +1754,10 @@ impl CheckAttrVisitor<'_> { sym::simd => { is_simd = true; if target != Target::Struct { - self.tcx - .sess - .emit_err(AttrApplication::Struct { hint_span: hint.span(), span }); + self.tcx.sess.emit_err(errors::AttrApplication::Struct { + hint_span: hint.span(), + span, + }); } else { continue; } @@ -1768,7 +1767,7 @@ impl CheckAttrVisitor<'_> { match target { Target::Struct | Target::Union | Target::Enum => continue, _ => { - self.tcx.sess.emit_err(AttrApplication::StructEnumUnion { + self.tcx.sess.emit_err(errors::AttrApplication::StructEnumUnion { hint_span: hint.span(), span, }); @@ -1789,15 +1788,16 @@ impl CheckAttrVisitor<'_> { | sym::usize => { int_reprs += 1; if target != Target::Enum { - self.tcx - .sess - .emit_err(AttrApplication::Enum { hint_span: hint.span(), span }); + self.tcx.sess.emit_err(errors::AttrApplication::Enum { + hint_span: hint.span(), + span, + }); } else { continue; } } _ => { - self.tcx.sess.emit_err(UnrecognizedReprHint { span: hint.span() }); + self.tcx.sess.emit_err(errors::UnrecognizedReprHint { span: hint.span() }); continue; } }; @@ -1810,9 +1810,10 @@ impl CheckAttrVisitor<'_> { // Error on repr(transparent, ). if is_transparent && hints.len() > 1 { let hint_spans: Vec<_> = hint_spans.clone().collect(); - self.tcx - .sess - .emit_err(TransparentIncompatible { hint_spans, target: target.to_string() }); + self.tcx.sess.emit_err(errors::TransparentIncompatible { + hint_spans, + target: target.to_string(), + }); } // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8) if (int_reprs > 1) @@ -1965,7 +1966,7 @@ impl CheckAttrVisitor<'_> { match std::fs::File::open(&file) { Ok(_) => true, Err(error) => { - self.tcx.sess.emit_err(DebugVisualizerUnreadable { + self.tcx.sess.emit_err(errors::DebugVisualizerUnreadable { span: meta_item.span, file: &file, error, @@ -2175,12 +2176,15 @@ impl CheckAttrVisitor<'_> { let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsInfer }; if sig.abi != Abi::Rust { - tcx.sess.emit_err(ProcMacroInvalidAbi { span: hir_sig.span, abi: sig.abi.name() }); + tcx.sess.emit_err(errors::ProcMacroInvalidAbi { + span: hir_sig.span, + abi: sig.abi.name(), + }); self.abort.set(true); } if sig.unsafety == Unsafety::Unsafe { - tcx.sess.emit_err(ProcMacroUnsafe { span: hir_sig.span }); + tcx.sess.emit_err(errors::ProcMacroUnsafe { span: hir_sig.span }); self.abort.set(true); } @@ -2188,7 +2192,7 @@ impl CheckAttrVisitor<'_> { // Typecheck the output if !drcx.types_may_unify(output, tokenstream) { - tcx.sess.emit_err(ProcMacroTypeError { + tcx.sess.emit_err(errors::ProcMacroTypeError { span: hir_sig.decl.output.span(), found: output, kind, @@ -2198,7 +2202,7 @@ impl CheckAttrVisitor<'_> { } if sig.inputs().len() < expected_input_count { - tcx.sess.emit_err(ProcMacroMissingArguments { + tcx.sess.emit_err(errors::ProcMacroMissingArguments { expected_input_count, span: hir_sig.span, kind, @@ -2213,7 +2217,7 @@ impl CheckAttrVisitor<'_> { sig.inputs().iter().zip(hir_sig.decl.inputs).take(expected_input_count) { if !drcx.types_may_unify(*arg, tokenstream) { - tcx.sess.emit_err(ProcMacroTypeError { + tcx.sess.emit_err(errors::ProcMacroTypeError { span: input.span, found: *arg, kind, @@ -2228,7 +2232,7 @@ impl CheckAttrVisitor<'_> { let body_id = tcx.hir().body_owned_by(id.def_id); let excess = tcx.hir().body(body_id).params.get(expected_input_count..); if let Some(excess @ [begin @ end] | excess @ [begin, .., end]) = excess { - tcx.sess.emit_err(ProcMacroDiffArguments { + tcx.sess.emit_err(errors::ProcMacroDiffArguments { span: begin.span.to(end.span), count: excess.len(), kind, @@ -2378,7 +2382,7 @@ fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) { if attr.style == AttrStyle::Inner { for attr_to_check in ATTRS_TO_CHECK { if attr.has_name(*attr_to_check) { - tcx.sess.emit_err(InvalidAttrAtCrateLevel { + tcx.sess.emit_err(errors::InvalidAttrAtCrateLevel { span: attr.span, snippet: tcx.sess.source_map().span_to_snippet(attr.span).ok(), name: *attr_to_check, diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index 47911aef25d4f..7299fc9705cc6 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -1,12 +1,7 @@ //! A pass that annotates every item and method with its stability level, //! propagating default levels lexically from parent to children ast nodes. -use crate::errors::{ - self, CannotStabilizeDeprecated, DeprecatedAttribute, DuplicateFeatureErr, - FeatureOnlyOnNightly, ImpliedFeatureNotExist, InvalidDeprecationVersion, InvalidStability, - MissingConstErr, MissingConstStabAttr, MissingStabilityAttr, TraitImplConstStable, - UnknownFeature, UselessStability, -}; +use crate::errors; use rustc_attr::{ self as attr, rust_version_symbol, ConstStability, Stability, StabilityLevel, Unstable, UnstableReason, VERSION_PLACEHOLDER, @@ -185,7 +180,7 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { { self.tcx .sess - .emit_err(MissingConstErr { fn_sig_span: fn_sig.span, const_span }); + .emit_err(errors::MissingConstErr { fn_sig_span: fn_sig.span, const_span }); } } } @@ -203,7 +198,7 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { if let Some((rustc_attr::Deprecation { is_since_rustc_version: true, .. }, span)) = &depr { if stab.is_none() { - self.tcx.sess.emit_err(DeprecatedAttribute { span: *span }); + self.tcx.sess.emit_err(errors::DeprecatedAttribute { span: *span }); } } @@ -219,7 +214,7 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { if kind == AnnotationKind::Prohibited || (kind == AnnotationKind::Container && stab.level.is_stable() && is_deprecated) { - self.tcx.sess.emit_err(UselessStability { span, item_sp }); + self.tcx.sess.emit_err(errors::UselessStability { span, item_sp }); } debug!("annotate: found {:?}", stab); @@ -235,15 +230,16 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { { match stab_v.parse::() { Err(_) => { - self.tcx.sess.emit_err(InvalidStability { span, item_sp }); + self.tcx.sess.emit_err(errors::InvalidStability { span, item_sp }); break; } Ok(stab_vp) => match dep_v.parse::() { Ok(dep_vp) => match dep_vp.cmp(&stab_vp) { Ordering::Less => { - self.tcx - .sess - .emit_err(CannotStabilizeDeprecated { span, item_sp }); + self.tcx.sess.emit_err(errors::CannotStabilizeDeprecated { + span, + item_sp, + }); break; } Ordering::Equal => continue, @@ -251,9 +247,10 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { }, Err(_) => { if dep_v != "TBD" { - self.tcx - .sess - .emit_err(InvalidDeprecationVersion { span, item_sp }); + self.tcx.sess.emit_err(errors::InvalidDeprecationVersion { + span, + item_sp, + }); } break; } @@ -527,7 +524,7 @@ impl<'tcx> MissingStabilityAnnotations<'tcx> { && self.effective_visibilities.is_reachable(def_id) { let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id()); - self.tcx.sess.emit_err(MissingStabilityAttr { span, descr }); + self.tcx.sess.emit_err(errors::MissingStabilityAttr { span, descr }); } } @@ -555,7 +552,7 @@ impl<'tcx> MissingStabilityAnnotations<'tcx> { if is_const && is_stable && missing_const_stability_attribute && is_reachable { let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id()); - self.tcx.sess.emit_err(MissingConstStabAttr { span, descr }); + self.tcx.sess.emit_err(errors::MissingConstStabAttr { span, descr }); } } } @@ -768,7 +765,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> { && *constness == hir::Constness::Const && const_stab.map_or(false, |(stab, _)| stab.is_const_stable()) { - self.tcx.sess.emit_err(TraitImplConstStable { span: item.span }); + self.tcx.sess.emit_err(errors::TraitImplConstStable { span: item.span }); } } @@ -947,7 +944,7 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { } if !lang_features.insert(feature) { // Warn if the user enables a lang feature multiple times. - tcx.sess.emit_err(DuplicateFeatureErr { span, feature }); + tcx.sess.emit_err(errors::DuplicateFeatureErr { span, feature }); } } @@ -955,14 +952,14 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { let mut remaining_lib_features = FxIndexMap::default(); for (feature, span) in declared_lib_features { if !tcx.sess.opts.unstable_features.is_nightly_build() { - tcx.sess.emit_err(FeatureOnlyOnNightly { + tcx.sess.emit_err(errors::FeatureOnlyOnNightly { span: *span, release_channel: env!("CFG_RELEASE_CHANNEL"), }); } if remaining_lib_features.contains_key(&feature) { // Warn if the user enables a lib feature multiple times. - tcx.sess.emit_err(DuplicateFeatureErr { span: *span, feature: *feature }); + tcx.sess.emit_err(errors::DuplicateFeatureErr { span: *span, feature: *feature }); } remaining_lib_features.insert(feature, *span); } @@ -1063,7 +1060,7 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { } for (feature, span) in remaining_lib_features { - tcx.sess.emit_err(UnknownFeature { span, feature: *feature }); + tcx.sess.emit_err(errors::UnknownFeature { span, feature: *feature }); } for (implied_by, feature) in remaining_implications { @@ -1074,7 +1071,7 @@ pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { .map(|(_, span)| span) .or_else(|| local_defined_features.unstable.get(&feature)) .expect("feature that implied another does not exist"); - tcx.sess.emit_err(ImpliedFeatureNotExist { span, feature, implied_by }); + tcx.sess.emit_err(errors::ImpliedFeatureNotExist { span, feature, implied_by }); } // FIXME(#44232): the `used_features` table no longer exists, so we From b4a20abc489f5aa45b3aef17deec8e518d94153d Mon Sep 17 00:00:00 2001 From: est31 Date: Sun, 5 Feb 2023 03:20:06 +0100 Subject: [PATCH 5/7] rustc_interface: remove huge error imports --- compiler/rustc_interface/src/passes.rs | 34 ++++++++++++-------------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 60b60edd2c811..2a373ebc1324d 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -1,9 +1,4 @@ -use crate::errors::{ - CantEmitMIR, EmojiIdentifier, ErrorWritingDependencies, FerrisIdentifier, - GeneratedFileConflictsWithDirectory, InputFileWouldBeOverWritten, MixedBinCrate, - MixedProcMacroCrate, OutDirError, ProcMacroCratePanicAbort, ProcMacroDocWithoutArg, - TempsDirError, -}; +use crate::errors; use crate::interface::{Compiler, Result}; use crate::proc_macro_decls; use crate::util; @@ -374,15 +369,15 @@ pub fn configure_and_expand( if crate_types.len() > 1 { if is_executable_crate { - sess.emit_err(MixedBinCrate); + sess.emit_err(errors::MixedBinCrate); } if is_proc_macro_crate { - sess.emit_err(MixedProcMacroCrate); + sess.emit_err(errors::MixedProcMacroCrate); } } if is_proc_macro_crate && sess.panic_strategy() == PanicStrategy::Abort { - sess.emit_warning(ProcMacroCratePanicAbort); + sess.emit_warning(errors::ProcMacroCratePanicAbort); } // For backwards compatibility, we don't try to run proc macro injection @@ -392,7 +387,7 @@ pub fn configure_and_expand( // However, we do emit a warning, to let such users know that they should // start passing '--crate-type proc-macro' if has_proc_macro_decls && sess.opts.actually_rustdoc && !is_proc_macro_crate { - sess.emit_warning(ProcMacroDocWithoutArg); + sess.emit_warning(errors::ProcMacroDocWithoutArg); } else { krate = sess.time("maybe_create_a_macro_crate", || { let is_test_crate = sess.opts.test; @@ -441,9 +436,9 @@ pub fn configure_and_expand( spans.sort(); if ident == sym::ferris { let first_span = spans[0]; - sess.emit_err(FerrisIdentifier { spans, first_span }); + sess.emit_err(errors::FerrisIdentifier { spans, first_span }); } else { - sess.emit_err(EmojiIdentifier { spans, ident }); + sess.emit_err(errors::EmojiIdentifier { spans, ident }); } } }); @@ -655,7 +650,7 @@ fn write_out_deps( } } Err(error) => { - sess.emit_fatal(ErrorWritingDependencies { path: &deps_filename, error }); + sess.emit_fatal(errors::ErrorWritingDependencies { path: &deps_filename, error }); } } } @@ -676,17 +671,20 @@ fn output_filenames(tcx: TyCtxt<'_>, (): ()) -> Arc { if let Some(ref input_path) = sess.io.input.opt_path() { if sess.opts.will_create_output_file() { if output_contains_path(&output_paths, input_path) { - sess.emit_fatal(InputFileWouldBeOverWritten { path: input_path }); + sess.emit_fatal(errors::InputFileWouldBeOverWritten { path: input_path }); } if let Some(ref dir_path) = output_conflicts_with_dir(&output_paths) { - sess.emit_fatal(GeneratedFileConflictsWithDirectory { input_path, dir_path }); + sess.emit_fatal(errors::GeneratedFileConflictsWithDirectory { + input_path, + dir_path, + }); } } } if let Some(ref dir) = sess.io.temps_dir { if fs::create_dir_all(dir).is_err() { - sess.emit_fatal(TempsDirError); + sess.emit_fatal(errors::TempsDirError); } } @@ -698,7 +696,7 @@ fn output_filenames(tcx: TyCtxt<'_>, (): ()) -> Arc { if !only_dep_info { if let Some(ref dir) = sess.io.output_dir { if fs::create_dir_all(dir).is_err() { - sess.emit_fatal(OutDirError); + sess.emit_fatal(errors::OutDirError); } } } @@ -977,7 +975,7 @@ pub fn start_codegen<'tcx>( if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) { if let Err(error) = rustc_mir_transform::dump_mir::emit_mir(tcx) { - tcx.sess.emit_err(CantEmitMIR { error }); + tcx.sess.emit_err(errors::CantEmitMIR { error }); tcx.sess.abort_if_errors(); } } From 394fa192a94bf6fed793ac3f8ceacc7d35b55319 Mon Sep 17 00:00:00 2001 From: est31 Date: Sun, 5 Feb 2023 03:26:33 +0100 Subject: [PATCH 6/7] rustc_parse: remove huge error imports --- compiler/rustc_parse/src/parser/expr.rs | 186 +++++++++++------------- compiler/rustc_parse/src/parser/stmt.rs | 46 +++--- 2 files changed, 111 insertions(+), 121 deletions(-) diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 28347b137f37c..473a5bb8cb8c1 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -5,26 +5,7 @@ use super::{ AttrWrapper, BlockMode, ClosureSpans, ForceCollect, Parser, PathStyle, Restrictions, SemiColonMode, SeqSep, TokenExpectType, TokenType, TrailingToken, }; -use crate::errors::{ - ArrayBracketsInsteadOfSpaces, ArrayBracketsInsteadOfSpacesSugg, AsyncBlockIn2015, - AsyncMoveOrderIncorrect, BracesForStructLiteral, CatchAfterTry, CommaAfterBaseStruct, - ComparisonInterpretedAsGeneric, ComparisonOrShiftInterpretedAsGenericSugg, - DoCatchSyntaxRemoved, DotDotDot, EqFieldInit, ExpectedElseBlock, ExpectedEqForLetExpr, - ExpectedExpressionFoundLet, FieldExpressionWithGeneric, FloatLiteralRequiresIntegerPart, - FoundExprWouldBeStmt, HelpUseLatestEdition, IfExpressionLetSomeSub, - IfExpressionMissingCondition, IfExpressionMissingThenBlock, IfExpressionMissingThenBlockSub, - InvalidBlockMacroSegment, InvalidComparisonOperator, InvalidComparisonOperatorSub, - InvalidInterpolatedExpression, InvalidLiteralSuffixOnTupleIndex, InvalidLogicalOperator, - InvalidLogicalOperatorSub, LabeledLoopInBreak, LeadingPlusNotSupported, LeftArrowOperator, - LifetimeInBorrowExpression, MacroInvocationWithQualifiedPath, MalformedLoopLabel, - MatchArmBodyWithoutBraces, MatchArmBodyWithoutBracesSugg, MissingCommaAfterMatchArm, - MissingDotDot, MissingInInForLoop, MissingInInForLoopSub, MissingSemicolonBeforeArray, - NoFieldsForFnCall, NotAsNegationOperator, NotAsNegationOperatorSub, - OuterAttributeNotAllowedOnIfElse, ParenthesesWithStructFields, - RequireColonAfterLabeledExpression, ShiftInterpretedAsGeneric, StructLiteralNotAllowedHere, - StructLiteralNotAllowedHereSugg, TildeAsUnaryOperator, UnexpectedIfWithIf, - UnexpectedTokenAfterLabel, UnexpectedTokenAfterLabelSugg, WrapExpressionInParentheses, -}; +use crate::errors; use crate::maybe_recover_from_interpolated_ty_qpath; use core::mem; use rustc_ast::ptr::P; @@ -244,10 +225,10 @@ impl<'a> Parser<'a> { } .into(); let invalid = format!("{}=", &sugg); - self.sess.emit_err(InvalidComparisonOperator { + self.sess.emit_err(errors::InvalidComparisonOperator { span: sp, invalid: invalid.clone(), - sub: InvalidComparisonOperatorSub::Correctable { + sub: errors::InvalidComparisonOperatorSub::Correctable { span: sp, invalid, correct: sugg, @@ -262,10 +243,10 @@ impl<'a> Parser<'a> { && self.prev_token.span.hi() == self.token.span.lo() { let sp = op.span.to(self.token.span); - self.sess.emit_err(InvalidComparisonOperator { + self.sess.emit_err(errors::InvalidComparisonOperator { span: sp, invalid: "<>".into(), - sub: InvalidComparisonOperatorSub::Correctable { + sub: errors::InvalidComparisonOperatorSub::Correctable { span: sp, invalid: "<>".into(), correct: "!=".into(), @@ -280,10 +261,10 @@ impl<'a> Parser<'a> { && self.prev_token.span.hi() == self.token.span.lo() { let sp = op.span.to(self.token.span); - self.sess.emit_err(InvalidComparisonOperator { + self.sess.emit_err(errors::InvalidComparisonOperator { span: sp, invalid: "<=>".into(), - sub: InvalidComparisonOperatorSub::Spaceship(sp), + sub: errors::InvalidComparisonOperatorSub::Spaceship(sp), }); self.bump(); } @@ -420,7 +401,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.sess.emit_err(FoundExprWouldBeStmt { + self.sess.emit_err(errors::FoundExprWouldBeStmt { span: self.token.span, token: self.token.clone(), suggestion: ExprParenthesesNeeded::surrounding(lhs.span), @@ -447,18 +428,18 @@ impl<'a> Parser<'a> { } (Some(op), _) => (op, self.token.span), (None, Some((Ident { name: sym::and, span }, false))) if self.may_recover() => { - self.sess.emit_err(InvalidLogicalOperator { + self.sess.emit_err(errors::InvalidLogicalOperator { span: self.token.span, incorrect: "and".into(), - sub: InvalidLogicalOperatorSub::Conjunction(self.token.span), + sub: errors::InvalidLogicalOperatorSub::Conjunction(self.token.span), }); (AssocOp::LAnd, span) } (None, Some((Ident { name: sym::or, span }, false))) if self.may_recover() => { - self.sess.emit_err(InvalidLogicalOperator { + self.sess.emit_err(errors::InvalidLogicalOperator { span: self.token.span, incorrect: "or".into(), - sub: InvalidLogicalOperatorSub::Disjunction(self.token.span), + sub: errors::InvalidLogicalOperatorSub::Disjunction(self.token.span), }); (AssocOp::LOr, span) } @@ -581,8 +562,11 @@ impl<'a> Parser<'a> { } // `+lit` token::BinOp(token::Plus) if this.look_ahead(1, |tok| tok.is_numeric_lit()) => { - let mut err = - LeadingPlusNotSupported { span: lo, remove_plus: None, add_parentheses: None }; + let mut err = errors::LeadingPlusNotSupported { + span: lo, + remove_plus: None, + add_parentheses: None, + }; // a block on the LHS might have been intended to be an expression instead if let Some(sp) = this.sess.ambiguous_block_expr_parse.borrow().get(&lo) { @@ -633,7 +617,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.sess.emit_err(TildeAsUnaryOperator(lo)); + self.sess.emit_err(errors::TildeAsUnaryOperator(lo)); self.parse_unary_expr(lo, UnOp::Not) } @@ -661,14 +645,14 @@ impl<'a> Parser<'a> { let negated_token = self.look_ahead(1, |t| t.clone()); let sub_diag = if negated_token.is_numeric_lit() { - NotAsNegationOperatorSub::SuggestNotBitwise + errors::NotAsNegationOperatorSub::SuggestNotBitwise } else if negated_token.is_bool_lit() { - NotAsNegationOperatorSub::SuggestNotLogical + errors::NotAsNegationOperatorSub::SuggestNotLogical } else { - NotAsNegationOperatorSub::SuggestNotDefault + errors::NotAsNegationOperatorSub::SuggestNotDefault }; - self.sess.emit_err(NotAsNegationOperator { + self.sess.emit_err(errors::NotAsNegationOperator { negated: negated_token.span, negated_desc: super::token_descr(&negated_token), // Span the `not` plus trailing whitespace to avoid @@ -739,7 +723,7 @@ impl<'a> Parser<'a> { match self.parse_labeled_expr(label, false) { Ok(expr) => { type_err.cancel(); - self.sess.emit_err(MalformedLoopLabel { + self.sess.emit_err(errors::MalformedLoopLabel { span: label.ident.span, correct_label: label.ident, }); @@ -764,20 +748,22 @@ impl<'a> Parser<'a> { ); let args_span = self.look_ahead(1, |t| t.span).to(span_after_type); - let suggestion = ComparisonOrShiftInterpretedAsGenericSugg { + let suggestion = errors::ComparisonOrShiftInterpretedAsGenericSugg { left: expr.span.shrink_to_lo(), right: expr.span.shrink_to_hi(), }; match self.token.kind { - token::Lt => self.sess.emit_err(ComparisonInterpretedAsGeneric { - comparison: self.token.span, - r#type: path, - args: args_span, - suggestion, - }), + token::Lt => { + self.sess.emit_err(errors::ComparisonInterpretedAsGeneric { + comparison: self.token.span, + r#type: path, + args: args_span, + suggestion, + }) + } token::BinOp(token::Shl) => { - self.sess.emit_err(ShiftInterpretedAsGeneric { + self.sess.emit_err(errors::ShiftInterpretedAsGeneric { shift: self.token.span, r#type: path, args: args_span, @@ -918,7 +904,7 @@ impl<'a> Parser<'a> { } fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) { - self.sess.emit_err(LifetimeInBorrowExpression { span, lifetime_span: lt_span }); + self.sess.emit_err(errors::LifetimeInBorrowExpression { span, lifetime_span: lt_span }); } /// Parse `mut?` or `raw [ const | mut ]`. @@ -1212,14 +1198,14 @@ impl<'a> Parser<'a> { let close_paren = self.prev_token.span; let span = lo.to(self.prev_token.span); if !fields.is_empty() { - let mut replacement_err = ParenthesesWithStructFields { + let mut replacement_err = errors::ParenthesesWithStructFields { span, r#type: path, - braces_for_struct: BracesForStructLiteral { + braces_for_struct: errors::BracesForStructLiteral { first: open_paren, second: close_paren, }, - no_fields_for_fn: NoFieldsForFnCall { + no_fields_for_fn: errors::NoFieldsForFnCall { fields: fields .into_iter() .map(|field| field.span.until(field.expr.span)) @@ -1286,7 +1272,7 @@ impl<'a> Parser<'a> { } else { // Field access `expr.f` if let Some(args) = seg.args { - self.sess.emit_err(FieldExpressionWithGeneric(args.span())); + self.sess.emit_err(errors::FieldExpressionWithGeneric(args.span())); } let span = lo.to(self.prev_token.span); @@ -1500,7 +1486,7 @@ impl<'a> Parser<'a> { let (span, kind) = if self.eat(&token::Not) { // MACRO INVOCATION expression if qself.is_some() { - self.sess.emit_err(MacroInvocationWithQualifiedPath(path.span)); + self.sess.emit_err(errors::MacroInvocationWithQualifiedPath(path.span)); } let lo = path.span; let mac = P(MacCall { @@ -1550,7 +1536,7 @@ impl<'a> Parser<'a> { { let (lit, _) = self.recover_unclosed_char(label_.ident, Parser::mk_token_lit_char, |self_| { - self_.sess.create_err(UnexpectedTokenAfterLabel { + self_.sess.create_err(errors::UnexpectedTokenAfterLabel { span: self_.token.span, remove_label: None, enclose_in_block: None, @@ -1562,7 +1548,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 - self.sess.emit_err(UnexpectedTokenAfterLabel { + self.sess.emit_err(errors::UnexpectedTokenAfterLabel { span: self.token.span, remove_label: None, enclose_in_block: None, @@ -1570,7 +1556,7 @@ impl<'a> Parser<'a> { consume_colon = false; Ok(self.mk_expr_err(lo)) } else { - let mut err = UnexpectedTokenAfterLabel { + let mut err = errors::UnexpectedTokenAfterLabel { span: self.token.span, remove_label: None, enclose_in_block: None, @@ -1606,7 +1592,7 @@ impl<'a> Parser<'a> { return expr; } - err.enclose_in_block = Some(UnexpectedTokenAfterLabelSugg { + err.enclose_in_block = Some(errors::UnexpectedTokenAfterLabelSugg { left: span.shrink_to_lo(), right: span.shrink_to_hi(), }); @@ -1622,7 +1608,7 @@ impl<'a> Parser<'a> { }?; if !ate_colon && consume_colon { - self.sess.emit_err(RequireColonAfterLabeledExpression { + self.sess.emit_err(errors::RequireColonAfterLabeledExpression { span: expr.span, label: lo, label_end: lo.shrink_to_hi(), @@ -1671,7 +1657,7 @@ impl<'a> Parser<'a> { self.bump(); // `catch` let span = lo.to(self.prev_token.span); - self.sess.emit_err(DoCatchSyntaxRemoved { span }); + self.sess.emit_err(errors::DoCatchSyntaxRemoved { span }); self.parse_try_block(lo) } @@ -1719,9 +1705,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_labeled_expr(label, true)?; - self.sess.emit_err(LabeledLoopInBreak { + self.sess.emit_err(errors::LabeledLoopInBreak { span: lexpr.span, - sub: WrapExpressionInParentheses { + sub: errors::WrapExpressionInParentheses { left: lexpr.span.shrink_to_lo(), right: lexpr.span.shrink_to_hi(), }, @@ -1841,7 +1827,7 @@ impl<'a> Parser<'a> { }; if let Some(expr) = expr { if matches!(expr.kind, ExprKind::Err) { - let mut err = InvalidInterpolatedExpression { span: self.token.span } + let mut err = errors::InvalidInterpolatedExpression { span: self.token.span } .into_diagnostic(&self.sess.span_diagnostic); err.downgrade_to_delayed_bug(); return Err(err); @@ -1902,7 +1888,7 @@ impl<'a> Parser<'a> { }); if let Some(token) = &recovered { self.bump(); - self.sess.emit_err(FloatLiteralRequiresIntegerPart { + self.sess.emit_err(errors::FloatLiteralRequiresIntegerPart { span: token.span, correct: pprust::token_to_string(token).into_owned(), }); @@ -1963,13 +1949,17 @@ impl<'a> Parser<'a> { if [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suffix) { // #59553: warn instead of reject out of hand to allow the fix to percolate // through the ecosystem when people fix their macros - self.sess.emit_warning(InvalidLiteralSuffixOnTupleIndex { + self.sess.emit_warning(errors::InvalidLiteralSuffixOnTupleIndex { span, suffix, exception: Some(()), }); } else { - self.sess.emit_err(InvalidLiteralSuffixOnTupleIndex { span, suffix, exception: None }); + self.sess.emit_err(errors::InvalidLiteralSuffixOnTupleIndex { + span, + suffix, + exception: None, + }); } } @@ -2003,9 +1993,9 @@ impl<'a> Parser<'a> { let mut snapshot = self.create_snapshot_for_diagnostic(); match snapshot.parse_array_or_repeat_expr(Delimiter::Brace) { Ok(arr) => { - self.sess.emit_err(ArrayBracketsInsteadOfSpaces { + self.sess.emit_err(errors::ArrayBracketsInsteadOfSpaces { span: arr.span, - sub: ArrayBracketsInsteadOfSpacesSugg { + sub: errors::ArrayBracketsInsteadOfSpacesSugg { left: lo, right: snapshot.prev_token.span, }, @@ -2051,7 +2041,7 @@ impl<'a> Parser<'a> { .span_to_snippet(snapshot.token.span) .map_or(false, |snippet| snippet == "]") => { - return Err(MissingSemicolonBeforeArray { + return Err(errors::MissingSemicolonBeforeArray { open_delim: open_delim_span, semicolon: prev_span.shrink_to_hi(), }.into_diagnostic(&self.sess.span_diagnostic)); @@ -2077,7 +2067,7 @@ impl<'a> Parser<'a> { } if self.token.is_whole_block() { - self.sess.emit_err(InvalidBlockMacroSegment { + self.sess.emit_err(errors::InvalidBlockMacroSegment { span: self.token.span, context: lo.to(self.token.span), }); @@ -2181,7 +2171,7 @@ impl<'a> Parser<'a> { // Check for `move async` and recover if self.check_keyword(kw::Async) { let move_async_span = self.token.span.with_lo(self.prev_token.span.data().lo); - Err(AsyncMoveOrderIncorrect { span: move_async_span } + Err(errors::AsyncMoveOrderIncorrect { span: move_async_span } .into_diagnostic(&self.sess.span_diagnostic)) } else { Ok(CaptureBy::Value) @@ -2259,17 +2249,17 @@ impl<'a> Parser<'a> { let block = match &mut cond.kind { ExprKind::Binary(Spanned { span: binop_span, .. }, _, right) if let ExprKind::Block(_, None) = right.kind => { - self.sess.emit_err(IfExpressionMissingThenBlock { + self.sess.emit_err(errors::IfExpressionMissingThenBlock { if_span: lo, missing_then_block_sub: - IfExpressionMissingThenBlockSub::UnfinishedCondition(cond_span.shrink_to_lo().to(*binop_span)), + errors::IfExpressionMissingThenBlockSub::UnfinishedCondition(cond_span.shrink_to_lo().to(*binop_span)), let_else_sub: None, }); std::mem::replace(right, this.mk_expr_err(binop_span.shrink_to_hi())) }, ExprKind::Block(_, None) => { - self.sess.emit_err(IfExpressionMissingCondition { + self.sess.emit_err(errors::IfExpressionMissingCondition { if_span: lo.shrink_to_hi(), block_span: self.sess.source_map().start_point(cond_span), }); @@ -2291,11 +2281,11 @@ impl<'a> Parser<'a> { block } else { let let_else_sub = matches!(cond.kind, ExprKind::Let(..)) - .then(|| IfExpressionLetSomeSub { if_span: lo.until(cond_span) }); + .then(|| errors::IfExpressionLetSomeSub { if_span: lo.until(cond_span) }); - self.sess.emit_err(IfExpressionMissingThenBlock { + self.sess.emit_err(errors::IfExpressionMissingThenBlock { if_span: lo, - missing_then_block_sub: IfExpressionMissingThenBlockSub::AddThenBlock( + missing_then_block_sub: errors::IfExpressionMissingThenBlockSub::AddThenBlock( cond_span.shrink_to_hi(), ), let_else_sub, @@ -2351,7 +2341,7 @@ impl<'a> Parser<'a> { TokenKind::AndAnd | TokenKind::Ident(kw::If, _) | TokenKind::Ident(kw::While, _) ); if !self.restrictions.contains(Restrictions::ALLOW_LET) || not_in_chain { - self.sess.emit_err(ExpectedExpressionFoundLet { span: self.token.span }); + self.sess.emit_err(errors::ExpectedExpressionFoundLet { span: self.token.span }); } self.bump(); // Eat `let` token @@ -2363,7 +2353,7 @@ impl<'a> Parser<'a> { CommaRecoveryMode::LikelyTuple, )?; if self.token == token::EqEq { - self.sess.emit_err(ExpectedEqForLetExpr { + self.sess.emit_err(errors::ExpectedEqForLetExpr { span: self.token.span, sugg_span: self.token.span, }); @@ -2398,7 +2388,7 @@ impl<'a> Parser<'a> { if self.check(&TokenKind::OpenDelim(Delimiter::Brace)) && classify::expr_requires_semi_to_be_stmt(&cond) => { - self.sess.emit_err(ExpectedElseBlock { + self.sess.emit_err(errors::ExpectedElseBlock { first_tok_span, first_tok, else_span, @@ -2438,7 +2428,7 @@ impl<'a> Parser<'a> { [x0 @ xn] | [x0, .., xn] => (x0.span.to(xn.span), xn.span), }; let ctx = if is_ctx_else { "else" } else { "if" }; - self.sess.emit_err(OuterAttributeNotAllowedOnIfElse { + self.sess.emit_err(errors::OuterAttributeNotAllowedOnIfElse { last, branch_span, ctx_span, @@ -2451,7 +2441,7 @@ impl<'a> Parser<'a> { if let ExprKind::Binary(Spanned { span: binop_span, node: binop}, _, right) = &cond.kind && let BinOpKind::And = binop && let ExprKind::If(cond, ..) = &right.kind { - Err(self.sess.create_err(UnexpectedIfWithIf(binop_span.shrink_to_hi().to(cond.span.shrink_to_lo())))) + Err(self.sess.create_err(errors::UnexpectedIfWithIf(binop_span.shrink_to_hi().to(cond.span.shrink_to_lo())))) } else { Ok(()) } @@ -2492,12 +2482,12 @@ impl<'a> Parser<'a> { // Possibly using JS syntax (#75311). let span = self.token.span; self.bump(); - (span, MissingInInForLoopSub::InNotOf) + (span, errors::MissingInInForLoopSub::InNotOf) } else { - (self.prev_token.span.between(self.token.span), MissingInInForLoopSub::AddIn) + (self.prev_token.span.between(self.token.span), errors::MissingInInForLoopSub::AddIn) }; - self.sess.emit_err(MissingInInForLoop { span, sub: sub(span) }); + self.sess.emit_err(errors::MissingInInForLoop { span, sub: sub(span) }); } /// Parses a `while` or `while let` expression (`while` token already eaten). @@ -2601,17 +2591,17 @@ impl<'a> Parser<'a> { let err = |this: &Parser<'_>, stmts: Vec| { let span = stmts[0].span.to(stmts[stmts.len() - 1].span); - this.sess.emit_err(MatchArmBodyWithoutBraces { + this.sess.emit_err(errors::MatchArmBodyWithoutBraces { statements: span, arrow: arrow_span, num_statements: stmts.len(), sub: if stmts.len() > 1 { - MatchArmBodyWithoutBracesSugg::AddBraces { + errors::MatchArmBodyWithoutBracesSugg::AddBraces { left: span.shrink_to_lo(), right: span.shrink_to_hi(), } } else { - MatchArmBodyWithoutBracesSugg::UseComma { semicolon: semi_sp } + errors::MatchArmBodyWithoutBracesSugg::UseComma { semicolon: semi_sp } }, }); this.mk_expr_err(span) @@ -2802,7 +2792,7 @@ impl<'a> Parser<'a> { .is_ok(); if pattern_follows && snapshot.check(&TokenKind::FatArrow) { err.cancel(); - this.sess.emit_err(MissingCommaAfterMatchArm { + this.sess.emit_err(errors::MissingCommaAfterMatchArm { span: hi.shrink_to_hi(), }); return Ok(true); @@ -2834,7 +2824,7 @@ impl<'a> Parser<'a> { fn parse_try_block(&mut self, span_lo: Span) -> PResult<'a, P> { let (attrs, body) = self.parse_inner_attrs_and_block()?; if self.eat_keyword(kw::Catch) { - Err(CatchAfterTry { span: self.prev_token.span } + Err(errors::CatchAfterTry { span: self.prev_token.span } .into_diagnostic(&self.sess.span_diagnostic)) } else { let span = span_lo.to(body.span); @@ -2910,9 +2900,9 @@ impl<'a> Parser<'a> { let expr = self.parse_struct_expr(qself.clone(), path.clone(), true); if let (Ok(expr), false) = (&expr, struct_allowed) { // This is a struct literal, but we don't can't accept them here. - self.sess.emit_err(StructLiteralNotAllowedHere { + self.sess.emit_err(errors::StructLiteralNotAllowedHere { span: expr.span, - sub: StructLiteralNotAllowedHereSugg { + sub: errors::StructLiteralNotAllowedHereSugg { left: path.span.shrink_to_lo(), right: expr.span.shrink_to_hi(), }, @@ -2935,8 +2925,8 @@ impl<'a> Parser<'a> { let mut async_block_err = |e: &mut Diagnostic, span: Span| { recover_async = true; - AsyncBlockIn2015 { span }.add_to_diagnostic(e); - HelpUseLatestEdition::new().add_to_diagnostic(e); + errors::AsyncBlockIn2015 { span }.add_to_diagnostic(e); + errors::HelpUseLatestEdition::new().add_to_diagnostic(e); }; while self.token != token::CloseDelim(close_delim) { @@ -3080,7 +3070,7 @@ impl<'a> Parser<'a> { if self.token != token::Comma { return; } - self.sess.emit_err(CommaAfterBaseStruct { + self.sess.emit_err(errors::CommaAfterBaseStruct { span: span.to(self.prev_token.span), comma: self.token.span, }); @@ -3093,7 +3083,7 @@ impl<'a> Parser<'a> { { // recover from typo of `...`, suggest `..` let span = self.prev_token.span; - self.sess.emit_err(MissingDotDot { token_span: span, sugg_span: span }); + self.sess.emit_err(errors::MissingDotDot { token_span: span, sugg_span: span }); return true; } false @@ -3161,18 +3151,18 @@ impl<'a> Parser<'a> { return; } - self.sess.emit_err(EqFieldInit { + self.sess.emit_err(errors::EqFieldInit { span: self.token.span, eq: field_name.span.shrink_to_hi().to(self.token.span), }); } fn err_dotdotdot_syntax(&self, span: Span) { - self.sess.emit_err(DotDotDot { span }); + self.sess.emit_err(errors::DotDotDot { span }); } fn err_larrow_operator(&self, span: Span) { - self.sess.emit_err(LeftArrowOperator { span }); + self.sess.emit_err(errors::LeftArrowOperator { span }); } fn mk_assign_op(&self, binop: BinOp, lhs: P, rhs: P) -> ExprKind { diff --git a/compiler/rustc_parse/src/parser/stmt.rs b/compiler/rustc_parse/src/parser/stmt.rs index 647639b9b62b4..3afda5f69f0e1 100644 --- a/compiler/rustc_parse/src/parser/stmt.rs +++ b/compiler/rustc_parse/src/parser/stmt.rs @@ -7,12 +7,7 @@ use super::TrailingToken; use super::{ AttrWrapper, BlockMode, FnParseMode, ForceCollect, Parser, Restrictions, SemiColonMode, }; -use crate::errors::{ - AssignmentElseNotAllowed, CompoundAssignmentExpressionInLet, ConstLetMutuallyExclusive, - DocCommentDoesNotDocumentAnything, ExpectedStatementAfterOuterAttr, InvalidCurlyInLetElse, - InvalidExpressionInLetElse, InvalidIdentiferStartsWithNumber, InvalidVariableDeclaration, - InvalidVariableDeclarationSub, WrapExpressionInParentheses, -}; +use crate::errors; use crate::maybe_whole; use rustc_ast as ast; @@ -64,29 +59,33 @@ 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.sess.emit_err(InvalidVariableDeclaration { + self.sess.emit_err(errors::InvalidVariableDeclaration { span: mut_let_span, - sub: InvalidVariableDeclarationSub::SwitchMutLetOrder(mut_let_span), + sub: errors::InvalidVariableDeclarationSub::SwitchMutLetOrder(mut_let_span), }); } Ok(Some(if self.token.is_keyword(kw::Let) { self.parse_local_mk(lo, attrs, capture_semi, force_collect)? } else if self.is_kw_followed_by_ident(kw::Mut) && self.may_recover() { - self.recover_stmt_local_after_let(lo, attrs, InvalidVariableDeclarationSub::MissingLet)? + self.recover_stmt_local_after_let( + lo, + attrs, + errors::InvalidVariableDeclarationSub::MissingLet, + )? } else if self.is_kw_followed_by_ident(kw::Auto) && self.may_recover() { self.bump(); // `auto` self.recover_stmt_local_after_let( lo, attrs, - InvalidVariableDeclarationSub::UseLetNotAuto, + errors::InvalidVariableDeclarationSub::UseLetNotAuto, )? } else if self.is_kw_followed_by_ident(sym::var) && self.may_recover() { self.bump(); // `var` self.recover_stmt_local_after_let( lo, attrs, - InvalidVariableDeclarationSub::UseLetNotVar, + errors::InvalidVariableDeclarationSub::UseLetNotVar, )? } else if self.check_path() && !self.token.is_qpath_start() && !self.is_path_start_item() { // We have avoided contextual keywords like `union`, items with `crate` visibility, @@ -124,7 +123,7 @@ 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.sess.emit_err(AssignmentElseNotAllowed { span: e.span.to(bl.span) }); + self.sess.emit_err(errors::AssignmentElseNotAllowed { span: e.span.to(bl.span) }); } self.mk_stmt(lo.to(e.span), StmtKind::Expr(e)) } else { @@ -217,12 +216,12 @@ impl<'a> Parser<'a> { && let attrs = attrs.take_for_recovery(self.sess) && let attrs @ [.., last] = &*attrs { if last.is_doc_comment() { - self.sess.emit_err(DocCommentDoesNotDocumentAnything { + self.sess.emit_err(errors::DocCommentDoesNotDocumentAnything { span: last.span, missing_comma: None, }); } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) { - self.sess.emit_err(ExpectedStatementAfterOuterAttr { span: last.span }); + self.sess.emit_err(errors::ExpectedStatementAfterOuterAttr { span: last.span }); } } } @@ -231,7 +230,7 @@ impl<'a> Parser<'a> { &mut self, lo: Span, attrs: AttrWrapper, - subdiagnostic: fn(Span) -> InvalidVariableDeclarationSub, + subdiagnostic: fn(Span) -> errors::InvalidVariableDeclarationSub, ) -> PResult<'a, Stmt> { let stmt = self.collect_tokens_trailing_token(attrs, ForceCollect::Yes, |this, attrs| { @@ -242,7 +241,7 @@ impl<'a> Parser<'a> { TrailingToken::None, )) })?; - self.sess.emit_err(InvalidVariableDeclaration { span: lo, sub: subdiagnostic(lo) }); + self.sess.emit_err(errors::InvalidVariableDeclaration { span: lo, sub: subdiagnostic(lo) }); Ok(stmt) } @@ -270,7 +269,7 @@ impl<'a> Parser<'a> { let lo = self.prev_token.span; if self.token.is_keyword(kw::Const) && self.look_ahead(1, |t| t.is_ident()) { - self.sess.emit_err(ConstLetMutuallyExclusive { span: lo.to(self.token.span) }); + self.sess.emit_err(errors::ConstLetMutuallyExclusive { span: lo.to(self.token.span) }); self.bump(); } @@ -373,7 +372,7 @@ impl<'a> Parser<'a> { rustc_ast::MetaItemLit::from_token(&self.token).is_none() && (lit.kind == token::LitKind::Integer || lit.kind == token::LitKind::Float) && self.look_ahead(1, |t| matches!(t.kind, token::Eq) || matches!(t.kind, token::Colon ) ) { - return Err(self.sess.create_err(InvalidIdentiferStartsWithNumber { span: self.token.span })); + return Err(self.sess.create_err(errors::InvalidIdentiferStartsWithNumber { span: self.token.span })); } Ok(()) } @@ -381,10 +380,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.lazy() { - self.sess.emit_err(InvalidExpressionInLetElse { + self.sess.emit_err(errors::InvalidExpressionInLetElse { span: init.span, operator: op.node.to_string(), - sugg: WrapExpressionInParentheses { + sugg: errors::WrapExpressionInParentheses { left: init.span.shrink_to_lo(), right: init.span.shrink_to_hi(), }, @@ -395,9 +394,9 @@ impl<'a> Parser<'a> { fn check_let_else_init_trailing_brace(&self, init: &ast::Expr) { if let Some(trailing) = classify::expr_trailing_brace(init) { - self.sess.emit_err(InvalidCurlyInLetElse { + self.sess.emit_err(errors::InvalidCurlyInLetElse { span: trailing.span.with_lo(trailing.span.hi() - BytePos(1)), - sugg: WrapExpressionInParentheses { + sugg: errors::WrapExpressionInParentheses { left: trailing.span.shrink_to_lo(), right: trailing.span.shrink_to_hi(), }, @@ -410,7 +409,8 @@ impl<'a> Parser<'a> { let eq_consumed = match self.token.kind { token::BinOpEq(..) => { // Recover `let x = 1` as `let x = 1` - self.sess.emit_err(CompoundAssignmentExpressionInLet { span: self.token.span }); + self.sess + .emit_err(errors::CompoundAssignmentExpressionInLet { span: self.token.span }); self.bump(); true } From 580cc89e9c36a89d3cc13a352c96f874eaa76581 Mon Sep 17 00:00:00 2001 From: est31 Date: Sun, 5 Feb 2023 03:39:18 +0100 Subject: [PATCH 7/7] rustc_session: remove huge error imports --- compiler/rustc_session/src/session.rs | 52 ++++++++++++--------------- 1 file changed, 23 insertions(+), 29 deletions(-) diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index dbd419c1406f8..8a0176f639174 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -3,15 +3,7 @@ use crate::code_stats::CodeStats; pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo}; use crate::config::Input; use crate::config::{self, CrateType, InstrumentCoverage, OptLevel, OutputType, SwitchWithOptPath}; -use crate::errors::{ - BranchProtectionRequiresAArch64, CannotEnableCrtStaticLinux, CannotMixAndMatchSanitizers, - LinkerPluginToWindowsNotSupported, NotCircumventFeature, OptimisationFuelExhausted, - ProfileSampleUseFileDoesNotExist, ProfileUseFileDoesNotExist, SanitizerCfiEnabled, - SanitizerNotSupported, SanitizersNotSupported, SkippingConstChecks, - SplitDebugInfoUnstablePlatform, StackProtectorNotSupportedForTarget, - TargetRequiresUnwindTables, UnleashedFeatureHelp, UnstableVirtualFunctionElimination, - UnsupportedDwarfVersion, -}; +use crate::errors; use crate::parse::{add_feature_diagnostics, ParseSess}; use crate::search_paths::{PathKind, SearchPath}; use crate::{filesearch, lint}; @@ -246,15 +238,15 @@ impl Session { if !unleashed_features.is_empty() { let mut must_err = false; // Create a diagnostic pointing at where things got unleashed. - self.emit_warning(SkippingConstChecks { + self.emit_warning(errors::SkippingConstChecks { unleashed_features: unleashed_features .iter() .map(|(span, gate)| { gate.map(|gate| { must_err = true; - UnleashedFeatureHelp::Named { span: *span, gate } + errors::UnleashedFeatureHelp::Named { span: *span, gate } }) - .unwrap_or(UnleashedFeatureHelp::Unnamed { span: *span }) + .unwrap_or(errors::UnleashedFeatureHelp::Unnamed { span: *span }) }) .collect(), }); @@ -262,7 +254,7 @@ impl Session { // If we should err, make sure we did. if must_err && self.has_errors().is_none() { // We have skipped a feature gate, and not run into other errors... reject. - self.emit_err(NotCircumventFeature); + self.emit_err(errors::NotCircumventFeature); } } } @@ -901,7 +893,7 @@ impl Session { // We only call `msg` in case we can actually emit warnings. // Otherwise, this could cause a `delay_good_path_bug` to // trigger (issue #79546). - self.emit_warning(OptimisationFuelExhausted { msg: msg() }); + self.emit_warning(errors::OptimisationFuelExhausted { msg: msg() }); } fuel.out_of_fuel = true; } else if fuel.remaining > 0 { @@ -1502,28 +1494,28 @@ fn validate_commandline_args_with_session_available(sess: &Session) { && sess.opts.cg.prefer_dynamic && sess.target.is_like_windows { - sess.emit_err(LinkerPluginToWindowsNotSupported); + sess.emit_err(errors::LinkerPluginToWindowsNotSupported); } // Make sure that any given profiling data actually exists so LLVM can't // decide to silently skip PGO. if let Some(ref path) = sess.opts.cg.profile_use { if !path.exists() { - sess.emit_err(ProfileUseFileDoesNotExist { path }); + sess.emit_err(errors::ProfileUseFileDoesNotExist { path }); } } // Do the same for sample profile data. if let Some(ref path) = sess.opts.unstable_opts.profile_sample_use { if !path.exists() { - sess.emit_err(ProfileSampleUseFileDoesNotExist { path }); + sess.emit_err(errors::ProfileSampleUseFileDoesNotExist { path }); } } // Unwind tables cannot be disabled if the target requires them. if let Some(include_uwtables) = sess.opts.cg.force_unwind_tables { if sess.target.requires_uwtable && !include_uwtables { - sess.emit_err(TargetRequiresUnwindTables); + sess.emit_err(errors::TargetRequiresUnwindTables); } } @@ -1533,16 +1525,18 @@ fn validate_commandline_args_with_session_available(sess: &Session) { match unsupported_sanitizers.into_iter().count() { 0 => {} 1 => { - sess.emit_err(SanitizerNotSupported { us: unsupported_sanitizers.to_string() }); + sess.emit_err(errors::SanitizerNotSupported { us: unsupported_sanitizers.to_string() }); } _ => { - sess.emit_err(SanitizersNotSupported { us: unsupported_sanitizers.to_string() }); + sess.emit_err(errors::SanitizersNotSupported { + us: unsupported_sanitizers.to_string(), + }); } } // Cannot mix and match sanitizers. let mut sanitizer_iter = sess.opts.unstable_opts.sanitizer.into_iter(); if let (Some(first), Some(second)) = (sanitizer_iter.next(), sanitizer_iter.next()) { - sess.emit_err(CannotMixAndMatchSanitizers { + sess.emit_err(errors::CannotMixAndMatchSanitizers { first: first.to_string(), second: second.to_string(), }); @@ -1550,22 +1544,22 @@ fn validate_commandline_args_with_session_available(sess: &Session) { // Cannot enable crt-static with sanitizers on Linux if sess.crt_static(None) && !sess.opts.unstable_opts.sanitizer.is_empty() { - sess.emit_err(CannotEnableCrtStaticLinux); + sess.emit_err(errors::CannotEnableCrtStaticLinux); } // LLVM CFI and VFE both require LTO. if sess.lto() != config::Lto::Fat { if sess.is_sanitizer_cfi_enabled() { - sess.emit_err(SanitizerCfiEnabled); + sess.emit_err(errors::SanitizerCfiEnabled); } if sess.opts.unstable_opts.virtual_function_elimination { - sess.emit_err(UnstableVirtualFunctionElimination); + sess.emit_err(errors::UnstableVirtualFunctionElimination); } } // LLVM CFI and KCFI are mutually exclusive if sess.is_sanitizer_cfi_enabled() && sess.is_sanitizer_kcfi_enabled() { - sess.emit_err(CannotMixAndMatchSanitizers { + sess.emit_err(errors::CannotMixAndMatchSanitizers { first: "cfi".to_string(), second: "kcfi".to_string(), }); @@ -1573,7 +1567,7 @@ fn validate_commandline_args_with_session_available(sess: &Session) { if sess.opts.unstable_opts.stack_protector != StackProtector::None { if !sess.target.options.supports_stack_protector { - sess.emit_warning(StackProtectorNotSupportedForTarget { + sess.emit_warning(errors::StackProtectorNotSupportedForTarget { stack_protector: sess.opts.unstable_opts.stack_protector, target_triple: &sess.opts.target_triple, }); @@ -1581,19 +1575,19 @@ fn validate_commandline_args_with_session_available(sess: &Session) { } if sess.opts.unstable_opts.branch_protection.is_some() && sess.target.arch != "aarch64" { - sess.emit_err(BranchProtectionRequiresAArch64); + sess.emit_err(errors::BranchProtectionRequiresAArch64); } if let Some(dwarf_version) = sess.opts.unstable_opts.dwarf_version { if dwarf_version > 5 { - sess.emit_err(UnsupportedDwarfVersion { dwarf_version }); + sess.emit_err(errors::UnsupportedDwarfVersion { dwarf_version }); } } if !sess.target.options.supported_split_debuginfo.contains(&sess.split_debuginfo()) && !sess.opts.unstable_opts.unstable_options { - sess.emit_err(SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() }); + sess.emit_err(errors::SplitDebugInfoUnstablePlatform { debuginfo: sess.split_debuginfo() }); } }