diff options
Diffstat (limited to 'compiler/rustc_metadata/src')
-rw-r--r-- | compiler/rustc_metadata/src/creader.rs | 46 | ||||
-rw-r--r-- | compiler/rustc_metadata/src/dependency_format.rs | 31 | ||||
-rw-r--r-- | compiler/rustc_metadata/src/errors.rs | 2 | ||||
-rw-r--r-- | compiler/rustc_metadata/src/lib.rs | 2 | ||||
-rw-r--r-- | compiler/rustc_metadata/src/locator.rs | 28 | ||||
-rw-r--r-- | compiler/rustc_metadata/src/native_libs.rs | 20 | ||||
-rw-r--r-- | compiler/rustc_metadata/src/rmeta/decoder.rs | 138 | ||||
-rw-r--r-- | compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs | 21 | ||||
-rw-r--r-- | compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs | 6 | ||||
-rw-r--r-- | compiler/rustc_metadata/src/rmeta/encoder.rs | 98 | ||||
-rw-r--r-- | compiler/rustc_metadata/src/rmeta/mod.rs | 25 | ||||
-rw-r--r-- | compiler/rustc_metadata/src/rmeta/table.rs | 6 |
12 files changed, 223 insertions, 200 deletions
diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index 23aceca06..aaf72ab94 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -4,7 +4,7 @@ use crate::errors; use crate::locator::{CrateError, CrateLocator, CratePaths}; use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob}; -use rustc_ast::expand::allocator::AllocatorKind; +use rustc_ast::expand::allocator::{alloc_error_handler_name, global_fn_name, AllocatorKind}; use rustc_ast::{self as ast, *}; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::svh::Svh; @@ -12,7 +12,7 @@ use rustc_data_structures::sync::{MappedReadGuard, MappedWriteGuard, ReadGuard, use rustc_expand::base::SyntaxExtension; use rustc_hir::def_id::{CrateNum, LocalDefId, StableCrateId, StableCrateIdMap, LOCAL_CRATE}; use rustc_hir::definitions::Definitions; -use rustc_index::vec::IndexVec; +use rustc_index::IndexVec; use rustc_middle::ty::TyCtxt; use rustc_session::config::{self, CrateType, ExternLocation}; use rustc_session::cstore::ExternCrateSource; @@ -27,6 +27,7 @@ use rustc_span::{Span, DUMMY_SP}; use rustc_target::spec::{PanicStrategy, TargetTriple}; use proc_macro::bridge::client::ProcMacro; +use std::error::Error; use std::ops::Fn; use std::path::Path; use std::time::Duration; @@ -147,11 +148,15 @@ impl CStore { assert_eq!(self.metas.len(), self.stable_crate_ids.len()); let num = CrateNum::new(self.stable_crate_ids.len()); if let Some(&existing) = self.stable_crate_ids.get(&root.stable_crate_id()) { - let crate_name0 = root.name(); - if let Some(crate_name1) = self.metas[existing].as_ref().map(|data| data.name()) { + // Check for (potential) conflicts with the local crate + if existing == LOCAL_CRATE { + Err(CrateError::SymbolConflictsCurrent(root.name())) + } else if let Some(crate_name1) = self.metas[existing].as_ref().map(|data| data.name()) + { + let crate_name0 = root.name(); Err(CrateError::StableCrateIdCollision(crate_name0, crate_name1)) } else { - Err(CrateError::SymbolConflictsCurrent(crate_name0)) + Err(CrateError::NotFound(root.name())) } } else { self.metas.push(None); @@ -368,7 +373,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash()); let private_dep = - self.sess.opts.externs.get(name.as_str()).map_or(false, |e| e.is_private_dep); + self.sess.opts.externs.get(name.as_str()).is_some_and(|e| e.is_private_dep); // Claim this crate number and cache it let cnum = self.cstore.intern_stable_crate_id(&crate_root)?; @@ -864,6 +869,17 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { } } + fn inject_forced_externs(&mut self) { + for (name, entry) in self.sess.opts.externs.iter() { + if entry.force { + let name_interned = Symbol::intern(name); + if !self.used_extern_options.contains(&name_interned) { + self.resolve_crate(name_interned, DUMMY_SP, CrateDepKind::Explicit); + } + } + } + } + fn inject_dependency_if( &self, krate: CrateNum, @@ -912,7 +928,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { // Don't worry about pathless `--extern foo` sysroot references continue; } - if entry.nounused_dep { + if entry.nounused_dep || entry.force { // We're not worried about this one continue; } @@ -931,7 +947,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { lint::builtin::UNUSED_CRATE_DEPENDENCIES, span, ast::CRATE_NODE_ID, - &format!( + format!( "external crate `{}` unused in `{}`: remove the dependency or add `use {} as _;`", name, self.tcx.crate_name(LOCAL_CRATE), @@ -941,6 +957,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { } pub fn postprocess(&mut self, krate: &ast::Crate) { + self.inject_forced_externs(); self.inject_profiler_runtime(krate); self.inject_allocator_crate(krate); self.inject_panic_runtime(krate); @@ -1031,7 +1048,7 @@ fn global_allocator_spans(krate: &ast::Crate) -> Vec<Span> { } } - let name = Symbol::intern(&AllocatorKind::Global.fn_name(sym::alloc)); + let name = Symbol::intern(&global_fn_name(sym::alloc)); let mut f = Finder { name, spans: Vec::new() }; visit::walk_crate(&mut f, krate); f.spans @@ -1053,7 +1070,7 @@ fn alloc_error_handler_spans(krate: &ast::Crate) -> Vec<Span> { } } - let name = Symbol::intern(&AllocatorKind::Global.fn_name(sym::oom)); + let name = Symbol::intern(alloc_error_handler_name(AllocatorKind::Global)); let mut f = Finder { name, spans: Vec::new() }; visit::walk_crate(&mut f, krate); f.spans @@ -1094,5 +1111,12 @@ fn load_dylib(path: &Path, max_attempts: usize) -> Result<libloading::Library, S } debug!("Failed to load proc-macro `{}` even after {} attempts.", path.display(), max_attempts); - Err(format!("{} (retried {} times)", last_error.unwrap(), max_attempts)) + + let last_error = last_error.unwrap(); + let message = if let Some(src) = last_error.source() { + format!("{last_error} ({src}) (retried {max_attempts} times)") + } else { + format!("{last_error} (retried {max_attempts} times)") + }; + Err(message) } diff --git a/compiler/rustc_metadata/src/dependency_format.rs b/compiler/rustc_metadata/src/dependency_format.rs index 39ef4276f..72b208a71 100644 --- a/compiler/rustc_metadata/src/dependency_format.rs +++ b/compiler/rustc_metadata/src/dependency_format.rs @@ -89,11 +89,25 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList { // to try to eagerly statically link all dependencies. This is normally // done for end-product dylibs, not intermediate products. // - // Treat cdylibs similarly. If `-C prefer-dynamic` is set, the caller may - // be code-size conscious, but without it, it makes sense to statically - // link a cdylib. - CrateType::Dylib | CrateType::Cdylib if !sess.opts.cg.prefer_dynamic => Linkage::Static, - CrateType::Dylib | CrateType::Cdylib => Linkage::Dynamic, + // Treat cdylibs and staticlibs similarly. If `-C prefer-dynamic` is set, + // the caller may be code-size conscious, but without it, it makes sense + // to statically link a cdylib or staticlib. For staticlibs we use + // `-Z staticlib-prefer-dynamic` for now. This may be merged into + // `-C prefer-dynamic` in the future. + CrateType::Dylib | CrateType::Cdylib => { + if sess.opts.cg.prefer_dynamic { + Linkage::Dynamic + } else { + Linkage::Static + } + } + CrateType::Staticlib => { + if sess.opts.unstable_opts.staticlib_prefer_dynamic { + Linkage::Dynamic + } else { + Linkage::Static + } + } // If the global prefer_dynamic switch is turned off, or the final // executable will be statically linked, prefer static crate linkage. @@ -108,9 +122,6 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList { // No linkage happens with rlibs, we just needed the metadata (which we // got long ago), so don't bother with anything. CrateType::Rlib => Linkage::NotLinked, - - // staticlibs must have all static dependencies. - CrateType::Staticlib => Linkage::Static, }; match preferred_linkage { @@ -123,9 +134,9 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList { return v; } - // Staticlibs and static executables must have all static dependencies. + // Static executables must have all static dependencies. // If any are not found, generate some nice pretty errors. - if ty == CrateType::Staticlib + if (ty == CrateType::Staticlib && !sess.opts.unstable_opts.staticlib_allow_rdylib_deps) || (ty == CrateType::Executable && sess.crt_static(Some(ty)) && !sess.target.crt_static_allows_dylibs) diff --git a/compiler/rustc_metadata/src/errors.rs b/compiler/rustc_metadata/src/errors.rs index 51b41b5f6..a44c1dd58 100644 --- a/compiler/rustc_metadata/src/errors.rs +++ b/compiler/rustc_metadata/src/errors.rs @@ -498,7 +498,7 @@ impl IntoDiagnostic<'_> for MultipleCandidates { diag.code(error_code!(E0464)); diag.set_span(self.span); for (i, candidate) in self.candidates.iter().enumerate() { - diag.note(&format!("candidate #{}: {}", i + 1, candidate.display())); + diag.note(format!("candidate #{}: {}", i + 1, candidate.display())); } diag } diff --git a/compiler/rustc_metadata/src/lib.rs b/compiler/rustc_metadata/src/lib.rs index 81e62eccb..9f664d0f0 100644 --- a/compiler/rustc_metadata/src/lib.rs +++ b/compiler/rustc_metadata/src/lib.rs @@ -28,7 +28,7 @@ extern crate tracing; pub use rmeta::{provide, provide_extern}; use rustc_errors::{DiagnosticMessage, SubdiagnosticMessage}; -use rustc_macros::fluent_messages; +use rustc_fluent_macro::fluent_messages; mod dependency_format; mod foreign_modules; diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index c6af8d632..ceb348f34 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -220,7 +220,6 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::memmap::Mmap; use rustc_data_structures::owned_slice::slice_owned; use rustc_data_structures::svh::Svh; -use rustc_data_structures::sync::MetadataRef; use rustc_errors::{DiagnosticArgValue, FatalError, IntoDiagnosticArg}; use rustc_fs_util::try_canonicalize; use rustc_session::config::{self, CrateType}; @@ -246,6 +245,7 @@ pub(crate) struct CrateLocator<'a> { only_needs_metadata: bool, sysroot: &'a Path, metadata_loader: &'a dyn MetadataLoader, + cfg_version: &'static str, // Immutable per-search configuration. crate_name: Symbol, @@ -323,6 +323,7 @@ impl<'a> CrateLocator<'a> { only_needs_metadata, sysroot: &sess.sysroot, metadata_loader, + cfg_version: sess.cfg_version, crate_name, exact_paths: if hash.is_none() { sess.opts @@ -566,7 +567,7 @@ impl<'a> CrateLocator<'a> { let mut err_data: Option<Vec<PathBuf>> = None; for (lib, kind) in m { info!("{} reading metadata from: {}", flavor, lib.display()); - if flavor == CrateFlavor::Rmeta && lib.metadata().map_or(false, |m| m.len() == 0) { + if flavor == CrateFlavor::Rmeta && lib.metadata().is_ok_and(|m| m.len() == 0) { // Empty files will cause get_metadata_section to fail. Rmeta // files can be empty, for example with binaries (which can // often appear with `cargo check` when checking a library as @@ -601,7 +602,7 @@ impl<'a> CrateLocator<'a> { } }; // If we see multiple hashes, emit an error about duplicate candidates. - if slot.as_ref().map_or(false, |s| s.0 != hash) { + if slot.as_ref().is_some_and(|s| s.0 != hash) { if let Some(candidates) = err_data { return Err(CrateError::MultipleCandidates( self.crate_name, @@ -655,7 +656,7 @@ impl<'a> CrateLocator<'a> { } fn crate_matches(&mut self, metadata: &MetadataBlob, libpath: &Path) -> Option<Svh> { - let rustc_version = rustc_version(); + let rustc_version = rustc_version(self.cfg_version); let found_version = metadata.get_rustc_version(); if found_version != rustc_version { info!("Rejecting via version: expected {} got {}", rustc_version, found_version); @@ -782,7 +783,7 @@ fn get_metadata_section<'p>( if !filename.exists() { return Err(MetadataError::NotPresent(filename)); } - let raw_bytes: MetadataRef = match flavor { + let raw_bytes = match flavor { CrateFlavor::Rlib => { loader.get_rlib_metadata(target, filename).map_err(MetadataError::LoadFailure)? } @@ -843,7 +844,7 @@ fn get_metadata_section<'p>( slice_owned(mmap, Deref::deref) } }; - let blob = MetadataBlob::new(raw_bytes); + let blob = MetadataBlob(raw_bytes); if blob.is_compatible() { Ok(blob) } else { @@ -960,6 +961,7 @@ pub(crate) enum CrateError { DlSym(String), LocatorCombined(Box<CombinedLocatorError>), NonDylibPlugin(Symbol), + NotFound(Symbol), } enum MetadataError<'a> { @@ -1097,7 +1099,7 @@ impl CrateError { crate_name, add_info, found_crates, - rustc_version: rustc_version(), + rustc_version: rustc_version(sess.cfg_version), }); } else if !locator.crate_rejections.via_invalid.is_empty() { let mut crate_rejections = Vec::new(); @@ -1130,6 +1132,18 @@ impl CrateError { CrateError::NonDylibPlugin(crate_name) => { sess.emit_err(errors::NoDylibPlugin { span, crate_name }); } + CrateError::NotFound(crate_name) => { + sess.emit_err(errors::CannotFindCrate { + span, + crate_name, + add_info: String::new(), + missing_core, + current_crate: sess.opts.crate_name.clone().unwrap_or("<unknown>".to_string()), + is_nightly_build: sess.is_nightly_build(), + profiler_runtime: Symbol::intern(&sess.opts.unstable_opts.profiler_runtime), + locator_triple: sess.opts.target_triple.clone(), + }); + } } } } diff --git a/compiler/rustc_metadata/src/native_libs.rs b/compiler/rustc_metadata/src/native_libs.rs index b855c8e43..c83c47e72 100644 --- a/compiler/rustc_metadata/src/native_libs.rs +++ b/compiler/rustc_metadata/src/native_libs.rs @@ -161,14 +161,6 @@ impl<'tcx> Collector<'tcx> { "raw-dylib" => { if !sess.target.is_like_windows { sess.emit_err(errors::FrameworkOnlyWindows { span }); - } else if !features.raw_dylib && sess.target.arch == "x86" { - feature_err( - &sess.parse_sess, - sym::raw_dylib, - span, - "link kind `raw-dylib` is unstable on x86", - ) - .emit(); } NativeLibKind::RawDylib } @@ -251,16 +243,6 @@ impl<'tcx> Collector<'tcx> { continue; } }; - if !features.raw_dylib { - let span = item.name_value_literal_span().unwrap(); - feature_err( - &sess.parse_sess, - sym::raw_dylib, - span, - "import name type is unstable", - ) - .emit(); - } import_name_type = Some((link_import_name_type, item.span())); } _ => { @@ -287,7 +269,7 @@ impl<'tcx> Collector<'tcx> { &sess.parse_sess, sym::$feature, span, - &format!("linking modifier `{modifier}` is unstable"), + format!("linking modifier `{modifier}` is unstable"), ) .emit(); } diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index 9f41dc92f..cc4e60cf6 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -7,6 +7,7 @@ use crate::rmeta::*; use rustc_ast as ast; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::owned_slice::OwnedSlice; use rustc_data_structures::svh::Svh; use rustc_data_structures::sync::{AppendOnlyVec, Lock, Lrc, OnceCell}; use rustc_data_structures::unhash::UnhashMap; @@ -16,14 +17,15 @@ use rustc_hir::def::{CtorKind, DefKind, DocLinkResMap, Res}; use rustc_hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE}; use rustc_hir::definitions::{DefKey, DefPath, DefPathData, DefPathHash}; use rustc_hir::diagnostic_items::DiagnosticItems; -use rustc_index::vec::{Idx, IndexVec}; +use rustc_index::{Idx, IndexVec}; use rustc_middle::metadata::ModChild; +use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile; use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo}; use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState}; use rustc_middle::ty::codec::TyDecoder; use rustc_middle::ty::fast_reject::SimplifiedType; use rustc_middle::ty::GeneratorDiagnosticData; -use rustc_middle::ty::{self, ParameterizedOverTcx, Ty, TyCtxt, Visibility}; +use rustc_middle::ty::{self, ParameterizedOverTcx, Predicate, Ty, TyCtxt, Visibility}; use rustc_serialize::opaque::MemDecoder; use rustc_serialize::{Decodable, Decoder}; use rustc_session::cstore::{ @@ -50,7 +52,7 @@ mod cstore_impl; /// A `MetadataBlob` internally is just a reference counted pointer to /// the actual data, so cloning it is cheap. #[derive(Clone)] -pub(crate) struct MetadataBlob(Lrc<MetadataRef>); +pub(crate) struct MetadataBlob(pub(crate) OwnedSlice); impl std::ops::Deref for MetadataBlob { type Target = [u8]; @@ -117,7 +119,7 @@ pub(crate) struct CrateMetadata { /// Additional data used for decoding `HygieneData` (e.g. `SyntaxContext` /// and `ExpnId`). - /// Note that we store a `HygieneDecodeContext` for each `CrateMetadat`. This is + /// Note that we store a `HygieneDecodeContext` for each `CrateMetadata`. This is /// because `SyntaxContext` ids are not globally unique, so we need /// to track which ids we've decoded on a per-crate basis. hygiene_context: HygieneDecodeContext, @@ -373,16 +375,6 @@ impl<'a, 'tcx> TyDecoder for DecodeContext<'a, 'tcx> { self.tcx() } - #[inline] - fn peek_byte(&self) -> u8 { - self.opaque.data[self.opaque.position()] - } - - #[inline] - fn position(&self) -> usize { - self.opaque.position() - } - fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx> where F: FnOnce(&mut Self) -> Ty<'tcx>, @@ -404,7 +396,7 @@ impl<'a, 'tcx> TyDecoder for DecodeContext<'a, 'tcx> { where F: FnOnce(&mut Self) -> R, { - let new_opaque = MemDecoder::new(self.opaque.data, pos); + let new_opaque = MemDecoder::new(self.opaque.data(), pos); let old_opaque = mem::replace(&mut self.opaque, new_opaque); let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode); let r = f(self); @@ -625,17 +617,12 @@ impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for Symbol { SYMBOL_OFFSET => { // read str offset let pos = d.read_usize(); - let old_pos = d.opaque.position(); - - // move to str ofset and read - d.opaque.set_position(pos); - let s = d.read_str(); - let sym = Symbol::intern(s); - - // restore position - d.opaque.set_position(old_pos); - sym + // move to str offset and read + d.opaque.with_position(pos, |d| { + let s = d.read_str(); + Symbol::intern(s) + }) } SYMBOL_PREINTERNED => { let symbol_index = d.read_u32(); @@ -675,10 +662,6 @@ impl<'a, 'tcx, I: Idx, T> Decodable<DecodeContext<'a, 'tcx>> for LazyTable<I, T> implement_ty_decoder!(DecodeContext<'a, 'tcx>); impl MetadataBlob { - pub(crate) fn new(metadata_ref: MetadataRef) -> MetadataBlob { - MetadataBlob(Lrc::new(metadata_ref)) - } - pub(crate) fn is_compatible(&self) -> bool { self.blob().starts_with(METADATA_HEADER) } @@ -857,6 +840,20 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { ) } + fn get_explicit_item_bounds( + self, + index: DefIndex, + tcx: TyCtxt<'tcx>, + ) -> ty::EarlyBinder<&'tcx [(Predicate<'tcx>, Span)]> { + let lazy = self.root.tables.explicit_item_bounds.get(self, index); + let output = if lazy.is_default() { + &mut [] + } else { + tcx.arena.alloc_from_iter(lazy.decode((self, tcx))) + }; + ty::EarlyBinder(&*output) + } + fn get_variant( self, kind: DefKind, @@ -883,16 +880,11 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { variant_did, ctor, data.discr, - self.root - .tables - .children - .get(self, index) - .expect("fields are not encoded for a variant") - .decode(self) - .map(|index| ty::FieldDef { - did: self.local_def_id(index), - name: self.item_name(index), - vis: self.get_visibility(index), + self.get_associated_item_or_field_def_ids(index) + .map(|did| ty::FieldDef { + did, + name: self.item_name(did.index), + vis: self.get_visibility(did.index), }) .collect(), adt_kind, @@ -918,7 +910,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { let mut variants: Vec<_> = if let ty::AdtKind::Enum = adt_kind { self.root .tables - .children + .module_children_non_reexports .get(self, item_id) .expect("variants are not encoded for an enum") .decode(self) @@ -967,7 +959,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { .decode((self, sess)) } - fn get_debugger_visualizers(self) -> Vec<rustc_span::DebuggerVisualizerFile> { + fn get_debugger_visualizers(self) -> Vec<DebuggerVisualizerFile> { self.root.debugger_visualizers.decode(self).collect::<Vec<_>>() } @@ -1013,9 +1005,8 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { let ident = self.item_ident(id, sess); let res = Res::Def(self.def_kind(id), self.local_def_id(id)); let vis = self.get_visibility(id); - let span = self.get_span(id, sess); - ModChild { ident, res, vis, span, reexport_chain: Default::default() } + ModChild { ident, res, vis, reexport_chain: Default::default() } } /// Iterates over all named children of the given module, @@ -1038,11 +1029,9 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { } } else { // Iterate over all children. - for child_index in self.root.tables.children.get(self, id).unwrap().decode(self) { - // FIXME: Do not encode RPITITs as a part of this list. - if self.root.tables.opt_rpitit_info.get(self, child_index).is_none() { - yield self.get_mod_child(child_index, sess); - } + let non_reexports = self.root.tables.module_children_non_reexports.get(self, id); + for child_index in non_reexports.unwrap().decode(self) { + yield self.get_mod_child(child_index, sess); } let reexports = self.root.tables.module_children_reexports.get(self, id); @@ -1071,20 +1060,19 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { .expect("argument names not encoded for a function") .decode((self, sess)) .nth(0) - .map_or(false, |ident| ident.name == kw::SelfLower) + .is_some_and(|ident| ident.name == kw::SelfLower) } - fn get_associated_item_def_ids( + fn get_associated_item_or_field_def_ids( self, id: DefIndex, - sess: &'a Session, ) -> impl Iterator<Item = DefId> + 'a { self.root .tables - .children + .associated_item_or_field_def_ids .get(self, id) - .expect("associated items not encoded for an item") - .decode((self, sess)) + .unwrap_or_else(|| self.missing("associated_item_or_field_def_ids", id)) + .decode(self) .map(move |child_index| self.local_def_id(child_index)) } @@ -1264,14 +1252,6 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { } } - fn is_foreign_item(self, id: DefIndex) -> bool { - if let Some(parent) = self.def_key(id).parent { - matches!(self.def_kind(parent), DefKind::ForeignMod) - } else { - false - } - } - #[inline] fn def_key(self, index: DefIndex) -> DefKey { *self @@ -1482,28 +1462,30 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { .. } = source_file_to_import; - // If this file is under $sysroot/lib/rustlib/src/ but has not been remapped - // during rust bootstrapping by `remap-debuginfo = true`, and the user - // wish to simulate that behaviour by -Z simulate-remapped-rust-src-base, + // If this file is under $sysroot/lib/rustlib/src/ + // and the user wish to simulate remapping with -Z simulate-remapped-rust-src-base, // then we change `name` to a similar state as if the rust was bootstrapped // with `remap-debuginfo = true`. // This is useful for testing so that tests about the effects of // `try_to_translate_virtual_to_real` don't have to worry about how the // compiler is bootstrapped. if let Some(virtual_dir) = &sess.opts.unstable_opts.simulate_remapped_rust_src_base - { - if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { - for subdir in ["library", "compiler"] { - if let rustc_span::FileName::Real(ref mut old_name) = name { - if let rustc_span::RealFileName::LocalPath(local) = old_name { - if let Ok(rest) = local.strip_prefix(real_dir.join(subdir)) { - *old_name = rustc_span::RealFileName::Remapped { - local_path: None, - virtual_name: virtual_dir.join(subdir).join(rest), - }; - } - } - } + && let Some(real_dir) = &sess.opts.real_rust_source_base_dir + && let rustc_span::FileName::Real(ref mut old_name) = name { + let relative_path = match old_name { + rustc_span::RealFileName::LocalPath(local) => local.strip_prefix(real_dir).ok(), + rustc_span::RealFileName::Remapped { virtual_name, .. } => { + option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR").and_then(|virtual_dir| virtual_name.strip_prefix(virtual_dir).ok()) + } + }; + debug!(?relative_path, ?virtual_dir, "simulate_remapped_rust_src_base"); + for subdir in ["library", "compiler"] { + if let Some(rest) = relative_path.and_then(|p| p.strip_prefix(subdir).ok()) { + *old_name = rustc_span::RealFileName::Remapped { + local_path: None, // FIXME: maybe we should preserve this? + virtual_name: virtual_dir.join(subdir).join(rest), + }; + break; } } } diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index 31798afb8..7425963d3 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -14,8 +14,8 @@ use rustc_middle::metadata::ModChild; use rustc_middle::middle::exported_symbols::ExportedSymbol; use rustc_middle::middle::stability::DeprecationEntry; use rustc_middle::query::LocalCrate; +use rustc_middle::query::{ExternProviders, Providers}; use rustc_middle::ty::fast_reject::SimplifiedType; -use rustc_middle::ty::query::{ExternProviders, Providers}; use rustc_middle::ty::{self, TyCtxt}; use rustc_session::cstore::CrateStore; use rustc_session::{Session, StableCrateId}; @@ -114,8 +114,8 @@ macro_rules! provide_one { ($tcx:ident, $def_id:ident, $other:ident, $cdata:ident, $name:ident => $compute:block) => { fn $name<'tcx>( $tcx: TyCtxt<'tcx>, - def_id_arg: ty::query::query_keys::$name<'tcx>, - ) -> ty::query::query_provided::$name<'tcx> { + def_id_arg: rustc_middle::query::queries::$name::Key<'tcx>, + ) -> rustc_middle::query::queries::$name::ProvidedValue<'tcx> { let _prof_timer = $tcx.prof.generic_activity(concat!("metadata_decode_entry_", stringify!($name))); @@ -203,7 +203,7 @@ impl IntoArgs for (CrateNum, SimplifiedType) { } provide! { tcx, def_id, other, cdata, - explicit_item_bounds => { table_defaulted_array } + explicit_item_bounds => { cdata.get_explicit_item_bounds(def_id.index, tcx) } explicit_predicates_of => { table } generics_of => { table } inferred_outlives_of => { table_defaulted_array } @@ -276,11 +276,10 @@ provide! { tcx, def_id, other, cdata, tcx.calculate_dtor(def_id, |_,_| Ok(())) } associated_item_def_ids => { - tcx.arena.alloc_from_iter(cdata.get_associated_item_def_ids(def_id.index, tcx.sess)) + tcx.arena.alloc_from_iter(cdata.get_associated_item_or_field_def_ids(def_id.index)) } associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) } inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) } - is_foreign_item => { cdata.is_foreign_item(def_id.index) } item_attrs => { tcx.arena.alloc_from_iter(cdata.get_item_attrs(def_id.index, tcx.sess)) } is_mir_available => { cdata.is_item_mir_available(def_id.index) } is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) } @@ -324,7 +323,7 @@ provide! { tcx, def_id, other, cdata, extra_filename => { cdata.root.extra_filename.clone() } - traits_in_crate => { tcx.arena.alloc_from_iter(cdata.get_traits()) } + traits => { tcx.arena.alloc_from_iter(cdata.get_traits()) } trait_impls_in_crate => { tcx.arena.alloc_from_iter(cdata.get_trait_impls()) } implementations_of_trait => { cdata.get_implementations_of_trait(tcx, other) } crate_incoherent_impls => { cdata.get_incoherent_impls(tcx, other) } @@ -516,14 +515,6 @@ impl CStore { self.get_crate_data(def.krate).get_ctor(def.index) } - pub fn module_children_untracked<'a>( - &'a self, - def_id: DefId, - sess: &'a Session, - ) -> impl Iterator<Item = ModChild> + 'a { - self.get_crate_data(def_id.krate).get_module_children(def_id.index, sess) - } - pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro { let _prof_timer = sess.prof.generic_activity("metadata_load_macro"); diff --git a/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs b/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs index 02cab561b..4f280bb9d 100644 --- a/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs +++ b/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs @@ -1,6 +1,5 @@ use crate::rmeta::DecodeContext; use crate::rmeta::EncodeContext; -use rustc_data_structures::owned_slice::slice_owned; use rustc_data_structures::owned_slice::OwnedSlice; use rustc_hir::def_path_hash_map::{Config as HashMapConfig, DefPathHashMap}; use rustc_middle::parameterized_over_tcx; @@ -45,12 +44,9 @@ impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefPathHashMapRef<'tcx> { impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for DefPathHashMapRef<'static> { fn decode(d: &mut DecodeContext<'a, 'tcx>) -> DefPathHashMapRef<'static> { - // Import TyDecoder so we can access the DecodeContext::position() method - use crate::rustc_middle::ty::codec::TyDecoder; - let len = d.read_usize(); let pos = d.position(); - let o = slice_owned(d.blob().clone(), |blob| &blob[pos..pos + len]); + let o = d.blob().clone().0.slice(|blob| &blob[pos..pos + len]); // Although we already have the data we need via the `OwnedSlice`, we still need // to advance the `DecodeContext`'s position so it's in a valid state after diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index e44b133a9..f067bca4b 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -7,8 +7,8 @@ use rustc_ast::Attribute; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::{FxHashMap, FxIndexSet}; use rustc_data_structures::memmap::{Mmap, MmapMut}; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; -use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator}; +use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher}; +use rustc_data_structures::sync::{join, par_for_each_in, Lrc}; use rustc_data_structures::temp_dir::MaybeTempDir; use rustc_hir as hir; use rustc_hir::def::DefKind; @@ -19,16 +19,17 @@ use rustc_hir::definitions::DefPathData; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::lang_items::LangItem; use rustc_middle::hir::nested_filter; +use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile; use rustc_middle::middle::dependency_format::Linkage; use rustc_middle::middle::exported_symbols::{ metadata_symbol_name, ExportedSymbol, SymbolExportInfo, }; use rustc_middle::mir::interpret; use rustc_middle::query::LocalCrate; +use rustc_middle::query::Providers; use rustc_middle::traits::specialization_graph; use rustc_middle::ty::codec::TyEncoder; use rustc_middle::ty::fast_reject::{self, SimplifiedType, TreatParams}; -use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt}; use rustc_middle::util::common::to_readable_str; use rustc_serialize::{opaque, Decodable, Decoder, Encodable, Encoder}; @@ -36,9 +37,7 @@ use rustc_session::config::{CrateType, OptLevel}; use rustc_session::cstore::{ForeignModule, LinkagePreference, NativeLib}; use rustc_span::hygiene::{ExpnIndex, HygieneEncodeContext, MacroKind}; use rustc_span::symbol::{sym, Symbol}; -use rustc_span::{ - self, DebuggerVisualizerFile, ExternalSource, FileName, SourceFile, Span, SyntaxContext, -}; +use rustc_span::{self, ExternalSource, FileName, SourceFile, Span, SyntaxContext}; use std::borrow::Borrow; use std::collections::hash_map::Entry; use std::hash::Hash; @@ -108,11 +107,7 @@ impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> { emit_i64(i64); emit_i32(i32); emit_i16(i16); - emit_i8(i8); - emit_bool(bool); - emit_char(char); - emit_str(&str); emit_raw_bytes(&[u8]); } } @@ -531,7 +526,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { adapted.name_hash = { let mut hasher: StableHasher = StableHasher::new(); adapted.name.hash(&mut hasher); - hasher.finish::<u128>() + hasher.finish::<Hash128>() }; Lrc::new(adapted) } else { @@ -832,18 +827,17 @@ fn should_encode_span(def_kind: DefKind) -> bool { | DefKind::AssocFn | DefKind::AssocConst | DefKind::Macro(_) + | DefKind::ExternCrate + | DefKind::Use | DefKind::AnonConst | DefKind::InlineConst | DefKind::OpaqueTy + | DefKind::ImplTraitPlaceholder | DefKind::Field | DefKind::Impl { .. } | DefKind::Closure | DefKind::Generator => true, - DefKind::ExternCrate - | DefKind::Use - | DefKind::ForeignMod - | DefKind::ImplTraitPlaceholder - | DefKind::GlobalAsm => false, + DefKind::ForeignMod | DefKind::GlobalAsm => false, } } @@ -867,6 +861,11 @@ fn should_encode_attrs(def_kind: DefKind) -> bool { | DefKind::Macro(_) | DefKind::Field | DefKind::Impl { .. } => true, + // Tools may want to be able to detect their tool lints on + // closures from upstream crates, too. This is used by + // https://github.com/model-checking/kani and is not a performance + // or maintenance issue for us. + DefKind::Closure => true, DefKind::TyParam | DefKind::ConstParam | DefKind::Ctor(..) @@ -879,7 +878,6 @@ fn should_encode_attrs(def_kind: DefKind) -> bool { | DefKind::ImplTraitPlaceholder | DefKind::LifetimeParam | DefKind::GlobalAsm - | DefKind::Closure | DefKind::Generator => false, } } @@ -1366,9 +1364,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { record!(self.tables.params_in_repr[def_id] <- params_in_repr); if adt_def.is_enum() { - let module_children = tcx.module_children_non_reexports(local_def_id); - record_array!(self.tables.children[def_id] <- - module_children.iter().map(|def_id| def_id.local_def_index)); + let module_children = tcx.module_children_local(local_def_id); + record_array!(self.tables.module_children_non_reexports[def_id] <- + module_children.iter().map(|child| child.res.def_id().index)); } else { // For non-enum, there is only one variant, and its def_id is the adt's. debug_assert_eq!(adt_def.variants().len(), 1); @@ -1386,7 +1384,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { record!(self.tables.variant_data[variant.def_id] <- data); self.tables.constness.set_some(variant.def_id.index, hir::Constness::Const); - record_array!(self.tables.children[variant.def_id] <- variant.fields.iter().map(|f| { + record_array!(self.tables.associated_item_or_field_def_ids[variant.def_id] <- variant.fields.iter().map(|f| { assert!(f.did.is_local()); f.did.index })); @@ -1415,18 +1413,20 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { // Encode this here because we don't do it in encode_def_ids. record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id)); } else { - let non_reexports = tcx.module_children_non_reexports(local_def_id); - record_array!(self.tables.children[def_id] <- - non_reexports.iter().map(|def_id| def_id.local_def_index)); + let module_children = tcx.module_children_local(local_def_id); + + record_array!(self.tables.module_children_non_reexports[def_id] <- + module_children.iter().filter(|child| child.reexport_chain.is_empty()) + .map(|child| child.res.def_id().index)); record_defaulted_array!(self.tables.module_children_reexports[def_id] <- - tcx.module_children_reexports(local_def_id)); + module_children.iter().filter(|child| !child.reexport_chain.is_empty())); } } fn encode_explicit_item_bounds(&mut self, def_id: DefId) { debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id); - let bounds = self.tcx.explicit_item_bounds(def_id); + let bounds = self.tcx.explicit_item_bounds(def_id).skip_binder(); record_defaulted_array!(self.tables.explicit_item_bounds[def_id] <- bounds); } @@ -1470,8 +1470,8 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { match impl_item.kind { ty::AssocKind::Fn => { - let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local()); - let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind else { bug!() }; + let (sig, body) = + self.tcx.hir().expect_impl_item(def_id.expect_local()).expect_fn(); self.tables.asyncness.set_some(def_id.index, sig.header.asyncness); record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body)); // Can be inside `impl const Trait`, so using sig.header.constness is not reliable @@ -1515,8 +1515,11 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { if encode_opt { record!(self.tables.optimized_mir[def_id.to_def_id()] <- tcx.optimized_mir(def_id)); - if tcx.sess.opts.unstable_opts.drop_tracking_mir && let DefKind::Generator = self.tcx.def_kind(def_id) { - record!(self.tables.mir_generator_witnesses[def_id.to_def_id()] <- tcx.mir_generator_witnesses(def_id)); + if tcx.sess.opts.unstable_opts.drop_tracking_mir + && let DefKind::Generator = self.tcx.def_kind(def_id) + && let Some(witnesses) = tcx.mir_generator_witnesses(def_id) + { + record!(self.tables.mir_generator_witnesses[def_id.to_def_id()] <- witnesses); } } if encode_const { @@ -1540,8 +1543,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { } record!(self.tables.promoted_mir[def_id.to_def_id()] <- tcx.promoted_mir(def_id)); - let instance = - ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id())); + let instance = ty::InstanceDef::Item(def_id.to_def_id()); let unused = tcx.unused_generic_params(instance); self.tables.unused_generic_params.set(def_id.local_def_index, unused); } @@ -1619,7 +1621,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { debug!("EncodeContext::encode_info_for_item({:?})", def_id); let record_associated_item_def_ids = |this: &mut Self, def_ids: &[DefId]| { - record_array!(this.tables.children[def_id] <- def_ids.iter().map(|&def_id| { + record_array!(this.tables.associated_item_or_field_def_ids[def_id] <- def_ids.iter().map(|&def_id| { assert!(def_id.is_local()); def_id.index })) @@ -1642,9 +1644,10 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { } hir::ItemKind::OpaqueTy(ref opaque) => { self.encode_explicit_item_bounds(def_id); - self.tables - .is_type_alias_impl_trait - .set(def_id.index, matches!(opaque.origin, hir::OpaqueTyOrigin::TyAlias)); + self.tables.is_type_alias_impl_trait.set( + def_id.index, + matches!(opaque.origin, hir::OpaqueTyOrigin::TyAlias { .. }), + ); } hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => { self.tables.impl_defaultness.set_some(def_id.index, *defaultness); @@ -1680,6 +1683,10 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { hir::ItemKind::Trait(..) => { record!(self.tables.trait_def[def_id] <- self.tcx.trait_def(def_id)); + let module_children = tcx.module_children_local(item.owner_id.def_id); + record_array!(self.tables.module_children_non_reexports[def_id] <- + module_children.iter().map(|child| child.res.def_id().index)); + let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id); record_associated_item_def_ids(self, associated_item_def_ids); for &item_def_id in associated_item_def_ids { @@ -1847,7 +1854,16 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> { empty_proc_macro!(self); - self.lazy_array(self.tcx.debugger_visualizers(LOCAL_CRATE).iter()) + self.lazy_array( + self.tcx + .debugger_visualizers(LOCAL_CRATE) + .iter() + // Erase the path since it may contain privacy sensitive data + // that we don't want to end up in crate metadata. + // The path is only needed for the local crate because of + // `--emit dep-info`. + .map(DebuggerVisualizerFile::path_erased), + ) } fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> { @@ -1922,7 +1938,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { fn encode_traits(&mut self) -> LazyArray<DefIndex> { empty_proc_macro!(self); - self.lazy_array(self.tcx.traits_in_crate(LOCAL_CRATE).iter().map(|def_id| def_id.index)) + self.lazy_array(self.tcx.traits(LOCAL_CRATE).iter().map(|def_id| def_id.index)) } /// Encodes an index, mapping each trait to its (local) implementations. @@ -2126,7 +2142,7 @@ fn prefetch_mir(tcx: TyCtxt<'_>) { return; } - par_iter(tcx.mir_keys(())).for_each(|&def_id| { + par_for_each_in(tcx.mir_keys(()), |&def_id| { let (encode_const, encode_opt) = should_encode_mir(tcx, def_id); if encode_const { @@ -2268,7 +2284,7 @@ fn encode_metadata_impl(tcx: TyCtxt<'_>, path: &Path) { }; // Encode the rustc version string in a predictable location. - rustc_version().encode(&mut ecx); + rustc_version(tcx.sess.cfg_version).encode(&mut ecx); // Encode all the entries and extra information in the crate, // culminating in the `CrateRoot` which points to all of it. @@ -2313,7 +2329,7 @@ pub fn provide(providers: &mut Providers) { .get(&def_id) .expect("no traits in scope for a doc link") }, - traits_in_crate: |tcx, LocalCrate| { + traits: |tcx, LocalCrate| { let mut traits = Vec::new(); for id in tcx.hir().items() { if matches!(tcx.def_kind(id.owner_id), DefKind::Trait | DefKind::TraitAlias) { diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index 67710054c..97e67fcf8 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -2,26 +2,26 @@ use crate::creader::CrateMetadataRef; use decoder::Metadata; use def_path_hash_map::DefPathHashMapRef; use rustc_data_structures::fx::FxHashMap; +use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile; use table::TableBuilder; use rustc_ast as ast; use rustc_attr as attr; use rustc_data_structures::svh::Svh; -use rustc_data_structures::sync::MetadataRef; use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind, DocLinkResMap}; use rustc_hir::def_id::{CrateNum, DefId, DefIndex, DefPathHash, StableCrateId}; use rustc_hir::definitions::DefKey; use rustc_hir::lang_items::LangItem; use rustc_index::bit_set::BitSet; -use rustc_index::vec::IndexVec; +use rustc_index::IndexVec; use rustc_middle::metadata::ModChild; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo}; use rustc_middle::middle::resolve_bound_vars::ObjectLifetimeDefault; use rustc_middle::mir; +use rustc_middle::query::Providers; use rustc_middle::ty::fast_reject::SimplifiedType; -use rustc_middle::ty::query::Providers; use rustc_middle::ty::{self, ReprOptions, Ty, UnusedGenericParams}; use rustc_middle::ty::{DeducedParamAttrs, GeneratorDiagnosticData, ParameterizedOverTcx, TyCtxt}; use rustc_serialize::opaque::FileEncoder; @@ -49,8 +49,8 @@ mod def_path_hash_map; mod encoder; mod table; -pub(crate) fn rustc_version() -> String { - format!("rustc {}", option_env!("CFG_VERSION").unwrap_or("unknown version")) +pub(crate) fn rustc_version(cfg_version: &'static str) -> String { + format!("rustc {}", cfg_version) } /// Metadata encoding version. @@ -246,7 +246,7 @@ pub(crate) struct CrateRoot { proc_macro_data: Option<ProcMacroData>, tables: LazyTables, - debugger_visualizers: LazyArray<rustc_span::DebuggerVisualizerFile>, + debugger_visualizers: LazyArray<DebuggerVisualizerFile>, exported_symbols: LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)>, @@ -358,11 +358,18 @@ define_tables! { associated_types_for_impl_traits_in_associated_fn: Table<DefIndex, LazyArray<DefId>>, opt_rpitit_info: Table<DefIndex, Option<LazyValue<ty::ImplTraitInTraitData>>>, unused_generic_params: Table<DefIndex, UnusedGenericParams>, + // Reexported names are not associated with individual `DefId`s, + // e.g. a glob import can introduce a lot of names, all with the same `DefId`. + // That's why the encoded list needs to contain `ModChild` structures describing all the names + // individually instead of `DefId`s. module_children_reexports: Table<DefIndex, LazyArray<ModChild>>, - optional: attributes: Table<DefIndex, LazyArray<ast::Attribute>>, - children: Table<DefIndex, LazyArray<DefIndex>>, + // For non-reexported names in a module every name is associated with a separate `DefId`, + // so we can take their names, visibilities etc from other encoded tables. + module_children_non_reexports: Table<DefIndex, LazyArray<DefIndex>>, + associated_item_or_field_def_ids: Table<DefIndex, LazyArray<DefIndex>>, opt_def_kind: Table<DefIndex, DefKind>, visibility: Table<DefIndex, LazyValue<ty::Visibility<DefIndex>>>, def_span: Table<DefIndex, LazyValue<Span>>, @@ -388,7 +395,7 @@ define_tables! { mir_for_ctfe: Table<DefIndex, LazyValue<mir::Body<'static>>>, mir_generator_witnesses: Table<DefIndex, LazyValue<mir::GeneratorLayout<'static>>>, promoted_mir: Table<DefIndex, LazyValue<IndexVec<mir::Promoted, mir::Body<'static>>>>, - thir_abstract_const: Table<DefIndex, LazyValue<ty::Const<'static>>>, + thir_abstract_const: Table<DefIndex, LazyValue<ty::EarlyBinder<ty::Const<'static>>>>, impl_parent: Table<DefIndex, RawDefId>, impl_polarity: Table<DefIndex, ty::ImplPolarity>, constness: Table<DefIndex, hir::Constness>, @@ -417,7 +424,7 @@ define_tables! { macro_definition: Table<DefIndex, LazyValue<ast::DelimArgs>>, proc_macro: Table<DefIndex, MacroKind>, deduced_param_attrs: Table<DefIndex, LazyArray<DeducedParamAttrs>>, - trait_impl_trait_tys: Table<DefIndex, LazyValue<FxHashMap<DefId, Ty<'static>>>>, + trait_impl_trait_tys: Table<DefIndex, LazyValue<FxHashMap<DefId, ty::EarlyBinder<Ty<'static>>>>>, doc_link_resolutions: Table<DefIndex, LazyValue<DocLinkResMap>>, doc_link_traits_in_scope: Table<DefIndex, LazyArray<DefId>>, } diff --git a/compiler/rustc_metadata/src/rmeta/table.rs b/compiler/rustc_metadata/src/rmeta/table.rs index 364fa74ab..dda30bce2 100644 --- a/compiler/rustc_metadata/src/rmeta/table.rs +++ b/compiler/rustc_metadata/src/rmeta/table.rs @@ -2,7 +2,7 @@ use crate::rmeta::*; use rustc_data_structures::fingerprint::Fingerprint; use rustc_hir::def::{CtorKind, CtorOf}; -use rustc_index::vec::Idx; +use rustc_index::Idx; use rustc_middle::ty::{ParameterizedOverTcx, UnusedGenericParams}; use rustc_serialize::opaque::FileEncoder; use rustc_serialize::Encoder as _; @@ -413,8 +413,8 @@ impl<I: Idx, const N: usize, T: FixedSizeEncoding<ByteArray = [u8; N]>> TableBui // > Space requirements could perhaps be optimized by using the HAMT `popcnt` // > trick (i.e. divide things into buckets of 32 or 64 items and then // > store bit-masks of which item in each bucket is actually serialized). - self.blocks.ensure_contains_elem(i, || [0; N]); - value.write_to_bytes(&mut self.blocks[i]); + let block = self.blocks.ensure_contains_elem(i, || [0; N]); + value.write_to_bytes(block); } } |