summaryrefslogtreecommitdiffstats
path: root/compiler/rustc_metadata
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 12:18:58 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 12:18:58 +0000
commita4b7ed7a42c716ab9f05e351f003d589124fd55d (patch)
treeb620cd3f223850b28716e474e80c58059dca5dd4 /compiler/rustc_metadata
parentAdding upstream version 1.67.1+dfsg1. (diff)
downloadrustc-a4b7ed7a42c716ab9f05e351f003d589124fd55d.tar.xz
rustc-a4b7ed7a42c716ab9f05e351f003d589124fd55d.zip
Adding upstream version 1.68.2+dfsg1.upstream/1.68.2+dfsg1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'compiler/rustc_metadata')
-rw-r--r--compiler/rustc_metadata/src/creader.rs81
-rw-r--r--compiler/rustc_metadata/src/dependency_format.rs9
-rw-r--r--compiler/rustc_metadata/src/errors.rs30
-rw-r--r--compiler/rustc_metadata/src/fs.rs2
-rw-r--r--compiler/rustc_metadata/src/locator.rs81
-rw-r--r--compiler/rustc_metadata/src/native_libs.rs6
-rw-r--r--compiler/rustc_metadata/src/rmeta/decoder.rs46
-rw-r--r--compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs14
-rw-r--r--compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs2
-rw-r--r--compiler/rustc_metadata/src/rmeta/encoder.rs84
-rw-r--r--compiler/rustc_metadata/src/rmeta/mod.rs15
-rw-r--r--compiler/rustc_metadata/src/rmeta/table.rs1
12 files changed, 162 insertions, 209 deletions
diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs
index efeaac8fe..653f2b39d 100644
--- a/compiler/rustc_metadata/src/creader.rs
+++ b/compiler/rustc_metadata/src/creader.rs
@@ -1,10 +1,9 @@
//! Validates all used crates and extern libraries and loads their metadata
use crate::errors::{
- AllocFuncRequired, ConflictingAllocErrorHandler, ConflictingGlobalAlloc, CrateNotPanicRuntime,
- GlobalAllocRequired, MissingAllocErrorHandler, NoMultipleAllocErrorHandler,
- NoMultipleGlobalAlloc, NoPanicStrategy, NoTransitiveNeedsDep, NotProfilerRuntime,
- ProfilerBuiltinsNeedsCore,
+ ConflictingAllocErrorHandler, ConflictingGlobalAlloc, CrateNotPanicRuntime,
+ GlobalAllocRequired, NoMultipleAllocErrorHandler, NoMultipleGlobalAlloc, NoPanicStrategy,
+ NoTransitiveNeedsDep, NotProfilerRuntime, ProfilerBuiltinsNeedsCore,
};
use crate::locator::{CrateError, CrateLocator, CratePaths};
use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob};
@@ -13,7 +12,7 @@ use rustc_ast::expand::allocator::AllocatorKind;
use rustc_ast::{self as ast, *};
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::svh::Svh;
-use rustc_data_structures::sync::Lrc;
+use rustc_data_structures::sync::{Lrc, ReadGuard};
use rustc_expand::base::SyntaxExtension;
use rustc_hir::def_id::{CrateNum, LocalDefId, StableCrateId, LOCAL_CRATE};
use rustc_hir::definitions::Definitions;
@@ -68,11 +67,12 @@ impl std::fmt::Debug for CStore {
pub struct CrateLoader<'a> {
// Immutable configuration.
sess: &'a Session,
- metadata_loader: Box<MetadataLoaderDyn>,
+ metadata_loader: &'a MetadataLoaderDyn,
+ definitions: ReadGuard<'a, Definitions>,
local_crate_name: Symbol,
// Mutable output.
- cstore: CStore,
- used_extern_options: FxHashSet<Symbol>,
+ cstore: &'a mut CStore,
+ used_extern_options: &'a mut FxHashSet<Symbol>,
}
pub enum LoadedMacro {
@@ -112,7 +112,7 @@ impl<'a> std::fmt::Debug for CrateDump<'a> {
writeln!(fmt, "resolved crates:")?;
for (cnum, data) in self.0.iter_crate_data() {
writeln!(fmt, " name: {}", data.name())?;
- writeln!(fmt, " cnum: {}", cnum)?;
+ writeln!(fmt, " cnum: {cnum}")?;
writeln!(fmt, " hash: {}", data.hash())?;
writeln!(fmt, " reqd: {:?}", data.dep_kind())?;
let CrateSource { dylib, rlib, rmeta } = data.source();
@@ -150,7 +150,7 @@ impl CStore {
pub(crate) fn get_crate_data(&self, cnum: CrateNum) -> CrateMetadataRef<'_> {
let cdata = self.metas[cnum]
.as_ref()
- .unwrap_or_else(|| panic!("Failed to get crate data for {:?}", cnum));
+ .unwrap_or_else(|| panic!("Failed to get crate data for {cnum:?}"));
CrateMetadataRef { cdata, cstore: self }
}
@@ -239,47 +239,49 @@ impl CStore {
);
}
}
+
+ pub fn new(sess: &Session) -> CStore {
+ let mut stable_crate_ids = FxHashMap::default();
+ stable_crate_ids.insert(sess.local_stable_crate_id(), LOCAL_CRATE);
+ CStore {
+ // We add an empty entry for LOCAL_CRATE (which maps to zero) in
+ // order to make array indices in `metas` match with the
+ // corresponding `CrateNum`. This first entry will always remain
+ // `None`.
+ metas: IndexVec::from_elem_n(None, 1),
+ injected_panic_runtime: None,
+ allocator_kind: None,
+ alloc_error_handler_kind: None,
+ has_global_allocator: false,
+ has_alloc_error_handler: false,
+ stable_crate_ids,
+ unused_externs: Vec::new(),
+ }
+ }
}
impl<'a> CrateLoader<'a> {
pub fn new(
sess: &'a Session,
- metadata_loader: Box<MetadataLoaderDyn>,
+ metadata_loader: &'a MetadataLoaderDyn,
local_crate_name: Symbol,
+ cstore: &'a mut CStore,
+ definitions: ReadGuard<'a, Definitions>,
+ used_extern_options: &'a mut FxHashSet<Symbol>,
) -> Self {
- let mut stable_crate_ids = FxHashMap::default();
- stable_crate_ids.insert(sess.local_stable_crate_id(), LOCAL_CRATE);
-
CrateLoader {
sess,
metadata_loader,
local_crate_name,
- cstore: CStore {
- // We add an empty entry for LOCAL_CRATE (which maps to zero) in
- // order to make array indices in `metas` match with the
- // corresponding `CrateNum`. This first entry will always remain
- // `None`.
- metas: IndexVec::from_elem_n(None, 1),
- injected_panic_runtime: None,
- allocator_kind: None,
- alloc_error_handler_kind: None,
- has_global_allocator: false,
- has_alloc_error_handler: false,
- stable_crate_ids,
- unused_externs: Vec::new(),
- },
- used_extern_options: Default::default(),
+ cstore,
+ used_extern_options,
+ definitions,
}
}
-
pub fn cstore(&self) -> &CStore {
&self.cstore
}
- pub fn into_cstore(self) -> CStore {
- self.cstore
- }
-
fn existing_match(&self, name: Symbol, hash: Option<Svh>, kind: PathKind) -> Option<CrateNum> {
for (cnum, data) in self.cstore.iter_crate_data() {
if data.name() != name {
@@ -518,8 +520,8 @@ impl<'a> CrateLoader<'a> {
}))
}
- fn resolve_crate<'b>(
- &'b mut self,
+ fn resolve_crate(
+ &mut self,
name: Symbol,
span: Span,
dep_kind: CrateDepKind,
@@ -892,10 +894,6 @@ impl<'a> CrateLoader<'a> {
} else {
// The alloc crate provides a default allocation error handler if
// one isn't specified.
- if !self.sess.features_untracked().default_alloc_error_handler {
- self.sess.emit_err(AllocFuncRequired);
- self.sess.emit_note(MissingAllocErrorHandler);
- }
self.cstore.alloc_error_handler_kind = Some(AllocatorKind::Default);
}
}
@@ -989,7 +987,6 @@ impl<'a> CrateLoader<'a> {
pub fn process_extern_crate(
&mut self,
item: &ast::Item,
- definitions: &Definitions,
def_id: LocalDefId,
) -> Option<CrateNum> {
match item.kind {
@@ -1013,7 +1010,7 @@ impl<'a> CrateLoader<'a> {
let cnum = self.resolve_crate(name, item.span, dep_kind)?;
- let path_len = definitions.def_path(def_id).data.len();
+ let path_len = self.definitions.def_path(def_id).data.len();
self.update_extern_crate(
cnum,
ExternCrate {
diff --git a/compiler/rustc_metadata/src/dependency_format.rs b/compiler/rustc_metadata/src/dependency_format.rs
index 6112ec9e4..cee4ba56a 100644
--- a/compiler/rustc_metadata/src/dependency_format.rs
+++ b/compiler/rustc_metadata/src/dependency_format.rs
@@ -54,7 +54,7 @@
use crate::creader::CStore;
use crate::errors::{
BadPanicStrategy, CrateDepMultiple, IncompatiblePanicInDropStrategy, LibRequired,
- RequiredPanicStrategy, RlibRequired, TwoPanicRuntimes,
+ RequiredPanicStrategy, RlibRequired, RustcLibRequired, TwoPanicRuntimes,
};
use rustc_data_structures::fx::FxHashMap;
@@ -224,7 +224,12 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList {
Linkage::Static => "rlib",
_ => "dylib",
};
- sess.emit_err(LibRequired { crate_name: tcx.crate_name(cnum), kind: kind });
+ let crate_name = tcx.crate_name(cnum);
+ if crate_name.as_str().starts_with("rustc_") {
+ sess.emit_err(RustcLibRequired { crate_name, kind });
+ } else {
+ sess.emit_err(LibRequired { crate_name, kind });
+ }
}
}
}
diff --git a/compiler/rustc_metadata/src/errors.rs b/compiler/rustc_metadata/src/errors.rs
index 6f7e6e09c..02c03114e 100644
--- a/compiler/rustc_metadata/src/errors.rs
+++ b/compiler/rustc_metadata/src/errors.rs
@@ -25,6 +25,14 @@ pub struct LibRequired<'a> {
}
#[derive(Diagnostic)]
+#[diag(metadata_rustc_lib_required)]
+#[help]
+pub struct RustcLibRequired<'a> {
+ pub crate_name: Symbol,
+ pub kind: &'a str,
+}
+
+#[derive(Diagnostic)]
#[diag(metadata_crate_dep_multiple)]
#[help]
pub struct CrateDepMultiple {
@@ -372,14 +380,6 @@ pub struct ConflictingAllocErrorHandler {
pub struct GlobalAllocRequired;
#[derive(Diagnostic)]
-#[diag(metadata_alloc_func_required)]
-pub struct AllocFuncRequired;
-
-#[derive(Diagnostic)]
-#[diag(metadata_missing_alloc_error_handler)]
-pub struct MissingAllocErrorHandler;
-
-#[derive(Diagnostic)]
#[diag(metadata_no_transitive_needs_dep)]
pub struct NoTransitiveNeedsDep<'a> {
pub crate_name: Symbol,
@@ -494,26 +494,16 @@ impl IntoDiagnostic<'_> for MultipleCandidates {
let mut diag = handler.struct_err(rustc_errors::fluent::metadata_multiple_candidates);
diag.set_arg("crate_name", self.crate_name);
diag.set_arg("flavor", self.flavor);
- diag.code(error_code!(E0465));
+ diag.code(error_code!(E0464));
diag.set_span(self.span);
for (i, candidate) in self.candidates.iter().enumerate() {
- diag.span_note(self.span, &format!("candidate #{}: {}", i + 1, candidate.display()));
+ diag.note(&format!("candidate #{}: {}", i + 1, candidate.display()));
}
diag
}
}
#[derive(Diagnostic)]
-#[diag(metadata_multiple_matching_crates, code = "E0464")]
-#[note]
-pub struct MultipleMatchingCrates {
- #[primary_span]
- pub span: Span,
- pub crate_name: Symbol,
- pub candidates: String,
-}
-
-#[derive(Diagnostic)]
#[diag(metadata_symbol_conflicts_current, code = "E0519")]
pub struct SymbolConflictsCurrent {
#[primary_span]
diff --git a/compiler/rustc_metadata/src/fs.rs b/compiler/rustc_metadata/src/fs.rs
index 7601f6bd3..f64318997 100644
--- a/compiler/rustc_metadata/src/fs.rs
+++ b/compiler/rustc_metadata/src/fs.rs
@@ -90,7 +90,7 @@ pub fn encode_and_write_metadata(tcx: TyCtxt<'_>) -> (EncodedMetadata, bool) {
let _prof_timer = tcx.sess.prof.generic_activity("write_crate_metadata");
// If the user requests metadata as output, rename `metadata_filename`
- // to the expected output `out_filename`. The match above should ensure
+ // to the expected output `out_filename`. The match above should ensure
// this file always exists.
let need_metadata_file = tcx.sess.opts.output_types.contains_key(&OutputType::Metadata);
let (metadata_filename, metadata_tmpdir) = if need_metadata_file {
diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs
index 15546092e..0f5f74007 100644
--- a/compiler/rustc_metadata/src/locator.rs
+++ b/compiler/rustc_metadata/src/locator.rs
@@ -216,9 +216,8 @@ use crate::creader::Library;
use crate::errors::{
CannotFindCrate, CrateLocationUnknownType, DlError, ExternLocationNotExist,
ExternLocationNotFile, FoundStaticlib, IncompatibleRustc, InvalidMetadataFiles,
- LibFilenameForm, MultipleCandidates, MultipleMatchingCrates, NewerCrateVersion,
- NoCrateWithTriple, NoDylibPlugin, NonAsciiName, StableCrateIdCollision, SymbolConflictsCurrent,
- SymbolConflictsOthers,
+ LibFilenameForm, MultipleCandidates, NewerCrateVersion, NoCrateWithTriple, NoDylibPlugin,
+ NonAsciiName, StableCrateIdCollision, SymbolConflictsCurrent, SymbolConflictsOthers,
};
use crate::rmeta::{rustc_version, MetadataBlob, METADATA_HEADER};
@@ -240,7 +239,6 @@ use rustc_target::spec::{Target, TargetTriple};
use snap::read::FrameDecoder;
use std::borrow::Cow;
-use std::fmt::Write as _;
use std::io::{Read, Result as IoResult, Write};
use std::path::{Path, PathBuf};
use std::{cmp, fmt, fs};
@@ -482,7 +480,22 @@ impl<'a> CrateLocator<'a> {
match libraries.len() {
0 => Ok(None),
1 => Ok(Some(libraries.into_iter().next().unwrap().1)),
- _ => Err(CrateError::MultipleMatchingCrates(self.crate_name, libraries)),
+ _ => {
+ let mut libraries: Vec<_> = libraries.into_values().collect();
+
+ libraries.sort_by_cached_key(|lib| lib.source.paths().next().unwrap().clone());
+ let candidates = libraries
+ .iter()
+ .map(|lib| lib.source.paths().next().unwrap().clone())
+ .collect::<Vec<_>>();
+
+ Err(CrateError::MultipleCandidates(
+ self.crate_name,
+ // these are the same for all candidates
+ get_flavor_from_path(candidates.first().unwrap()),
+ candidates,
+ ))
+ }
}
}
@@ -578,7 +591,7 @@ impl<'a> CrateLocator<'a> {
Err(MetadataError::LoadFailure(err)) => {
info!("no metadata found: {}", err);
// The file was present and created by the same compiler version, but we
- // couldn't load it for some reason. Give a hard error instead of silently
+ // couldn't load it for some reason. Give a hard error instead of silently
// ignoring it, but only if we would have given an error anyway.
self.crate_rejections
.via_invalid
@@ -882,17 +895,22 @@ pub fn list_file_metadata(
metadata_loader: &dyn MetadataLoader,
out: &mut dyn Write,
) -> IoResult<()> {
+ let flavor = get_flavor_from_path(path);
+ match get_metadata_section(target, flavor, path, metadata_loader) {
+ Ok(metadata) => metadata.list_crate_metadata(out),
+ Err(msg) => write!(out, "{}\n", msg),
+ }
+}
+
+fn get_flavor_from_path(path: &Path) -> CrateFlavor {
let filename = path.file_name().unwrap().to_str().unwrap();
- let flavor = if filename.ends_with(".rlib") {
+
+ if filename.ends_with(".rlib") {
CrateFlavor::Rlib
} else if filename.ends_with(".rmeta") {
CrateFlavor::Rmeta
} else {
CrateFlavor::Dylib
- };
- match get_metadata_section(target, flavor, path, metadata_loader) {
- Ok(metadata) => metadata.list_crate_metadata(out),
- Err(msg) => write!(out, "{}\n", msg),
}
}
@@ -931,7 +949,6 @@ pub(crate) enum CrateError {
ExternLocationNotExist(Symbol, PathBuf),
ExternLocationNotFile(Symbol, PathBuf),
MultipleCandidates(Symbol, CrateFlavor, Vec<PathBuf>),
- MultipleMatchingCrates(Symbol, FxHashMap<Svh, Library>),
SymbolConflictsCurrent(Symbol),
SymbolConflictsOthers(Symbol),
StableCrateIdCollision(Symbol, Symbol),
@@ -972,37 +989,7 @@ impl CrateError {
sess.emit_err(ExternLocationNotFile { span, crate_name, location: &loc });
}
CrateError::MultipleCandidates(crate_name, flavor, candidates) => {
- sess.emit_err(MultipleCandidates { span, flavor: flavor, crate_name, candidates });
- }
- CrateError::MultipleMatchingCrates(crate_name, libraries) => {
- let mut libraries: Vec<_> = libraries.into_values().collect();
- // Make ordering of candidates deterministic.
- // This has to `clone()` to work around lifetime restrictions with `sort_by_key()`.
- // `sort_by()` could be used instead, but this is in the error path,
- // so the performance shouldn't matter.
- libraries.sort_by_cached_key(|lib| lib.source.paths().next().unwrap().clone());
- let candidates = libraries
- .iter()
- .map(|lib| {
- let crate_name = lib.metadata.get_root().name();
- let crate_name = crate_name.as_str();
- let mut paths = lib.source.paths();
-
- // This `unwrap()` should be okay because there has to be at least one
- // source file. `CrateSource`'s docs confirm that too.
- let mut s = format!(
- "\ncrate `{}`: {}",
- crate_name,
- paths.next().unwrap().display()
- );
- let padding = 8 + crate_name.len();
- for path in paths {
- write!(s, "\n{:>padding$}", path.display(), padding = padding).unwrap();
- }
- s
- })
- .collect::<String>();
- sess.emit_err(MultipleMatchingCrates { span, crate_name, candidates });
+ sess.emit_err(MultipleCandidates { span, crate_name, flavor, candidates });
}
CrateError::SymbolConflictsCurrent(root_name) => {
sess.emit_err(SymbolConflictsCurrent { span, crate_name: root_name });
@@ -1011,11 +998,7 @@ impl CrateError {
sess.emit_err(SymbolConflictsOthers { span, crate_name: root_name });
}
CrateError::StableCrateIdCollision(crate_name0, crate_name1) => {
- sess.emit_err(StableCrateIdCollision {
- span,
- crate_name0: crate_name0,
- crate_name1: crate_name1,
- });
+ sess.emit_err(StableCrateIdCollision { span, crate_name0, crate_name1 });
}
CrateError::DlOpen(s) | CrateError::DlSym(s) => {
sess.emit_err(DlError { span, err: s });
@@ -1074,7 +1057,7 @@ impl CrateError {
}
sess.emit_err(NoCrateWithTriple {
span,
- crate_name: crate_name,
+ crate_name,
locator_triple: locator.triple.triple(),
add_info,
found_crates,
diff --git a/compiler/rustc_metadata/src/native_libs.rs b/compiler/rustc_metadata/src/native_libs.rs
index 1fd35adf1..6f05c76e8 100644
--- a/compiler/rustc_metadata/src/native_libs.rs
+++ b/compiler/rustc_metadata/src/native_libs.rs
@@ -45,7 +45,7 @@ pub fn find_native_static_library(
for path in search_paths {
for (prefix, suffix) in &formats {
- let test = path.join(format!("{}{}{}", prefix, name, suffix));
+ let test = path.join(format!("{prefix}{name}{suffix}"));
if test.exists() {
return test;
}
@@ -433,10 +433,10 @@ impl<'tcx> Collector<'tcx> {
}
// Update kind and, optionally, the name of all native libraries
- // (there may be more than one) with the specified name. If any
+ // (there may be more than one) with the specified name. If any
// library is mentioned more than once, keep the latest mention
// of it, so that any possible dependent libraries appear before
- // it. (This ensures that the linker is able to see symbols from
+ // it. (This ensures that the linker is able to see symbols from
// all possible dependent libraries before linking in the library
// in question.)
for passed_lib in &self.tcx.sess.opts.libs {
diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs
index af7b0793a..143d8f2f1 100644
--- a/compiler/rustc_metadata/src/rmeta/decoder.rs
+++ b/compiler/rustc_metadata/src/rmeta/decoder.rs
@@ -78,10 +78,6 @@ pub(crate) struct CrateMetadata {
blob: MetadataBlob,
// --- Some data pre-decoded from the metadata blob, usually for performance ---
- /// NOTE(eddyb) we pass `'static` to a `'tcx` parameter because this
- /// lifetime is only used behind `LazyValue`, `LazyArray`, or `LazyTable`, and therefore acts like a
- /// universal (`for<'tcx>`), that is paired up with whichever `TyCtxt`
- /// is being used to decode those values.
root: CrateRoot,
/// Trait impl data.
/// FIXME: Used only from queries and can use query cache,
@@ -466,7 +462,7 @@ impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for SyntaxContext {
.root
.syntax_contexts
.get(cdata, id)
- .unwrap_or_else(|| panic!("Missing SyntaxContext {:?} for crate {:?}", id, cname))
+ .unwrap_or_else(|| panic!("Missing SyntaxContext {id:?} for crate {cname:?}"))
.decode((cdata, sess))
})
}
@@ -688,10 +684,10 @@ impl MetadataBlob {
pub(crate) fn get_root(&self) -> CrateRoot {
let slice = &self.blob()[..];
let offset = METADATA_HEADER.len();
- let pos = (((slice[offset + 0] as u32) << 24)
- | ((slice[offset + 1] as u32) << 16)
- | ((slice[offset + 2] as u32) << 8)
- | ((slice[offset + 3] as u32) << 0)) as usize;
+
+ let pos_bytes = slice[offset..][..4].try_into().unwrap();
+ let pos = u32::from_be_bytes(pos_bytes) as usize;
+
LazyValue::<CrateRoot>::from_position(NonZeroUsize::new(pos).unwrap()).decode(self)
}
@@ -702,16 +698,14 @@ impl MetadataBlob {
writeln!(out, "hash {} stable_crate_id {:?}", root.hash, root.stable_crate_id)?;
writeln!(out, "proc_macro {:?}", root.proc_macro_data.is_some())?;
writeln!(out, "=External Dependencies=")?;
+
for (i, dep) in root.crate_deps.decode(self).enumerate() {
+ let CrateDep { name, extra_filename, hash, host_hash, kind } = dep;
+ let number = i + 1;
+
writeln!(
out,
- "{} {}{} hash {} host_hash {:?} kind {:?}",
- i + 1,
- dep.name,
- dep.extra_filename,
- dep.hash,
- dep.host_hash,
- dep.kind
+ "{number} {name}{extra_filename} hash {hash} host_hash {host_hash:?} kind {kind:?}"
)?;
}
write!(out, "\n")?;
@@ -812,7 +806,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
.tables
.def_span
.get(self, index)
- .unwrap_or_else(|| panic!("Missing span for {:?}", index))
+ .unwrap_or_else(|| panic!("Missing span for {index:?}"))
.decode((self, sess))
}
@@ -1255,7 +1249,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
.tables
.proc_macro_quoted_spans
.get(self, index)
- .unwrap_or_else(|| panic!("Missing proc macro quoted span: {:?}", index))
+ .unwrap_or_else(|| panic!("Missing proc macro quoted span: {index:?}"))
.decode((self, sess))
}
@@ -1527,13 +1521,15 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
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 {
- 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) {
- *old_name = rustc_span::RealFileName::Remapped {
- local_path: None,
- virtual_name: virtual_dir.join(rest),
- };
+ 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),
+ };
+ }
}
}
}
diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
index c5d4da079..6fd5bd52a 100644
--- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
+++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
@@ -232,14 +232,14 @@ provide! { tcx, def_id, other, cdata,
.get(cdata, def_id.index)
.is_some()
}
- collect_trait_impl_trait_tys => {
+ collect_return_position_impl_trait_in_trait_tys => {
Ok(cdata
.root
.tables
.trait_impl_trait_tys
.get(cdata, def_id.index)
.map(|lazy| lazy.decode((cdata, tcx)))
- .process_decoded(tcx, || panic!("{:?} does not have trait_impl_trait_tys", def_id)))
+ .process_decoded(tcx, || panic!("{def_id:?} does not have trait_impl_trait_tys")))
}
visibility => { cdata.get_visibility(def_id.index) }
@@ -391,7 +391,7 @@ pub(in crate::rmeta) fn provide(providers: &mut Providers) {
// keys from the former.
// This is a rudimentary check that does not catch all cases,
// just the easiest.
- let mut fallback_map: DefIdMap<DefId> = Default::default();
+ let mut fallback_map: Vec<(DefId, DefId)> = Default::default();
// Issue 46112: We want the map to prefer the shortest
// paths when reporting the path to an item. Therefore we
@@ -421,12 +421,12 @@ pub(in crate::rmeta) fn provide(providers: &mut Providers) {
if let Some(def_id) = child.res.opt_def_id() {
if child.ident.name == kw::Underscore {
- fallback_map.insert(def_id, parent);
+ fallback_map.push((def_id, parent));
return;
}
if ty::util::is_doc_hidden(tcx, parent) {
- fallback_map.insert(def_id, parent);
+ fallback_map.push((def_id, parent));
return;
}
@@ -460,6 +460,7 @@ pub(in crate::rmeta) fn provide(providers: &mut Providers) {
// Fill in any missing entries with the less preferable path.
// If this path re-exports the child as `_`, we still use this
// path in a diagnostic that suggests importing `::*`.
+
for (child, parent) in fallback_map {
visible_parent_map.entry(child).or_insert(parent);
}
@@ -638,6 +639,9 @@ impl CrateStore for CStore {
fn as_any(&self) -> &dyn Any {
self
}
+ fn untracked_as_any(&mut self) -> &mut dyn Any {
+ self
+ }
fn crate_name(&self, cnum: CrateNum) -> Symbol {
self.get_crate_data(cnum).root.name
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 40c94b372..a6133f1b4 100644
--- a/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs
+++ b/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs
@@ -58,7 +58,7 @@ impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for DefPathHashMapRef<'static>
let _ = d.read_raw_bytes(len);
let inner = odht::HashTable::from_raw_bytes(o).unwrap_or_else(|e| {
- panic!("decode error: {}", e);
+ panic!("decode error: {e}");
});
DefPathHashMapRef::OwnedFromMetadata(inner)
}
diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs
index 7304c891e..8f7a61b72 100644
--- a/compiler/rustc_metadata/src/rmeta/encoder.rs
+++ b/compiler/rustc_metadata/src/rmeta/encoder.rs
@@ -76,7 +76,7 @@ pub(super) struct EncodeContext<'a, 'tcx> {
symbol_table: FxHashMap<Symbol, usize>,
}
-/// If the current crate is a proc-macro, returns early with `Lazy:empty()`.
+/// If the current crate is a proc-macro, returns early with `LazyArray::empty()`.
/// This is useful for skipping the encoding of things that aren't needed
/// for proc-macro crates.
macro_rules! empty_proc_macro {
@@ -145,7 +145,7 @@ impl<'a, 'tcx, I, T> Encodable<EncodeContext<'a, 'tcx>> for LazyTable<I, T> {
impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum {
fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
if *self != LOCAL_CRATE && s.is_proc_macro {
- panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self);
+ panic!("Attempted to encode non-local CrateNum {self:?} for proc-macro crate");
}
s.emit_u32(self.as_u32());
}
@@ -172,7 +172,7 @@ impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
if self.krate == LOCAL_CRATE {
- // We will only write details for local expansions. Non-local expansions will fetch
+ // We will only write details for local expansions. Non-local expansions will fetch
// data from the corresponding crate's metadata.
// FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external
// metadata from proc-macro crates.
@@ -276,7 +276,7 @@ impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
// Introduce a new scope so that we drop the 'lock()' temporary
match &*source_file.external_src.lock() {
ExternalSource::Foreign { metadata_index, .. } => *metadata_index,
- src => panic!("Unexpected external source {:?}", src),
+ src => panic!("Unexpected external source {src:?}"),
}
};
@@ -332,7 +332,7 @@ impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Symbol {
s.emit_str(self.as_str());
}
Entry::Occupied(o) => {
- let x = o.get().clone();
+ let x = *o.get();
s.emit_u8(SYMBOL_OFFSET);
s.emit_usize(x);
}
@@ -713,7 +713,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
let computed_total_bytes: usize = stats.iter().map(|(_, size)| size).sum();
assert_eq!(total_bytes, computed_total_bytes);
- if tcx.sess.meta_stats() {
+ if tcx.sess.opts.unstable_opts.meta_stats {
self.opaque.flush();
// Rewind and re-read all the metadata to count the zero bytes we wrote.
@@ -733,12 +733,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
let prefix = "meta-stats";
let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
- eprintln!("{} METADATA STATS", prefix);
+ eprintln!("{prefix} METADATA STATS");
eprintln!("{} {:<23}{:>10}", prefix, "Section", "Size");
- eprintln!(
- "{} ----------------------------------------------------------------",
- prefix
- );
+ eprintln!("{prefix} ----------------------------------------------------------------");
for (label, size) in stats {
eprintln!(
"{} {:<23}{:>10} ({:4.1}%)",
@@ -748,10 +745,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
perc(size)
);
}
- eprintln!(
- "{} ----------------------------------------------------------------",
- prefix
- );
+ eprintln!("{prefix} ----------------------------------------------------------------");
eprintln!(
"{} {:<23}{:>10} (of which {:.1}% are zero bytes)",
prefix,
@@ -759,7 +753,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
to_readable_str(total_bytes),
perc(zero_bytes)
);
- eprintln!("{}", prefix);
+ eprintln!("{prefix}");
}
root
@@ -894,8 +888,8 @@ fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) {
| DefKind::AssocConst
| DefKind::Static(..)
| DefKind::Const => (true, false),
- // Full-fledged functions
- DefKind::AssocFn | DefKind::Fn => {
+ // Full-fledged functions + closures
+ DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
let generics = tcx.generics_of(def_id);
let needs_inline = (generics.requires_monomorphization(tcx)
|| tcx.codegen_fn_attrs(def_id).requests_inline())
@@ -906,15 +900,6 @@ fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) {
let always_encode_mir = tcx.sess.opts.unstable_opts.always_encode_mir;
(is_const_fn, needs_inline || always_encode_mir)
}
- // Closures can't be const fn.
- DefKind::Closure => {
- let generics = tcx.generics_of(def_id);
- let needs_inline = (generics.requires_monomorphization(tcx)
- || tcx.codegen_fn_attrs(def_id).requests_inline())
- && tcx.sess.opts.output_types.should_codegen();
- let always_encode_mir = tcx.sess.opts.unstable_opts.always_encode_mir;
- (false, needs_inline || always_encode_mir)
- }
// Generators require optimized MIR to compute layout.
DefKind::Generator => (false, true),
// The others don't have MIR.
@@ -1093,7 +1078,7 @@ fn should_encode_const(def_kind: DefKind) -> bool {
}
}
-fn should_encode_trait_impl_trait_tys<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
+fn should_encode_trait_impl_trait_tys(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
if tcx.def_kind(def_id) != DefKind::AssocFn {
return false;
}
@@ -1111,8 +1096,8 @@ fn should_encode_trait_impl_trait_tys<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) ->
// associated types.
tcx.fn_sig(trait_item_def_id).skip_binder().output().walk().any(|arg| {
if let ty::GenericArgKind::Type(ty) = arg.unpack()
- && let ty::Projection(data) = ty.kind()
- && tcx.def_kind(data.item_def_id) == DefKind::ImplTraitPlaceholder
+ && let ty::Alias(ty::Projection, data) = ty.kind()
+ && tcx.def_kind(data.def_id) == DefKind::ImplTraitPlaceholder
{
true
} else {
@@ -1197,13 +1182,16 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
record!(self.tables.params_in_repr[def_id] <- params_in_repr);
}
if should_encode_trait_impl_trait_tys(tcx, def_id)
- && let Ok(table) = self.tcx.collect_trait_impl_trait_tys(def_id)
+ && let Ok(table) = self.tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
{
record!(self.tables.trait_impl_trait_tys[def_id] <- table);
}
}
- let inherent_impls = tcx.crate_inherent_impls(());
- for (def_id, implementations) in inherent_impls.inherent_impls.iter() {
+ let inherent_impls = tcx.with_stable_hashing_context(|hcx| {
+ tcx.crate_inherent_impls(()).inherent_impls.to_sorted(&hcx, true)
+ });
+
+ for (def_id, implementations) in inherent_impls {
if implementations.is_empty() {
continue;
}
@@ -1337,24 +1325,16 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
let tcx = self.tcx;
- let ast_item = tcx.hir().expect_trait_item(def_id.expect_local());
- self.tables.impl_defaultness.set(def_id.index, ast_item.defaultness);
+ let impl_defaultness = tcx.impl_defaultness(def_id.expect_local());
+ self.tables.impl_defaultness.set(def_id.index, impl_defaultness);
let trait_item = tcx.associated_item(def_id);
self.tables.assoc_container.set(def_id.index, trait_item.container);
match trait_item.kind {
ty::AssocKind::Const => {}
ty::AssocKind::Fn => {
- let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind else { bug!() };
- match *m {
- hir::TraitFn::Required(ref names) => {
- record_array!(self.tables.fn_arg_names[def_id] <- *names)
- }
- hir::TraitFn::Provided(body) => {
- record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body))
- }
- };
- self.tables.asyncness.set(def_id.index, m_sig.header.asyncness);
+ record_array!(self.tables.fn_arg_names[def_id] <- tcx.fn_arg_names(def_id));
+ self.tables.asyncness.set(def_id.index, tcx.asyncness(def_id));
self.tables.constness.set(def_id.index, hir::Constness::NotConst);
}
ty::AssocKind::Type => {
@@ -1443,7 +1423,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
let instance =
ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id()));
let unused = tcx.unused_generic_params(instance);
- if !unused.is_empty() {
+ if !unused.all_used() {
record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
}
}
@@ -1572,10 +1552,10 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
self.tables.impl_defaultness.set(def_id.index, *defaultness);
self.tables.constness.set(def_id.index, *constness);
- let trait_ref = self.tcx.impl_trait_ref(def_id);
+ let trait_ref = self.tcx.impl_trait_ref(def_id).map(ty::EarlyBinder::skip_binder);
if let Some(trait_ref) = trait_ref {
let trait_def = self.tcx.trait_def(trait_ref.def_id);
- if let Some(mut an) = trait_def.ancestors(self.tcx, def_id).ok() {
+ if let Ok(mut an) = trait_def.ancestors(self.tcx, def_id) {
if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) {
self.tables.impl_parent.set(def_id.index, parent.into());
}
@@ -1703,6 +1683,8 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
}
ty::Closure(_, substs) => {
+ let constness = self.tcx.constness(def_id.to_def_id());
+ self.tables.constness.set(def_id.to_def_id().index, constness);
record!(self.tables.fn_sig[def_id.to_def_id()] <- substs.as_closure().sig());
}
@@ -1860,7 +1842,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
// the assumption that they are numbered 1 to n.
// FIXME (#2166): This is not nearly enough to support correct versioning
// but is enough to get transitive crate dependencies working.
- self.lazy_array(deps.iter().map(|&(_, ref dep)| dep))
+ self.lazy_array(deps.iter().map(|(_, dep)| dep))
}
fn encode_lib_features(&mut self) -> LazyArray<(Symbol, Option<Symbol>)> {
@@ -1914,6 +1896,8 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
for id in tcx.hir().items() {
if matches!(tcx.def_kind(id.owner_id), DefKind::Impl) {
if let Some(trait_ref) = tcx.impl_trait_ref(id.owner_id) {
+ let trait_ref = trait_ref.subst_identity();
+
let simplified_self_ty = fast_reject::simplify_type(
self.tcx,
trait_ref.self_ty(),
@@ -1997,7 +1981,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
self.lazy_array(
exported_symbols
.iter()
- .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
+ .filter(|&(exported_symbol, _)| match *exported_symbol {
ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
_ => true,
})
diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs
index 571804644..5066dbbb9 100644
--- a/compiler/rustc_metadata/src/rmeta/mod.rs
+++ b/compiler/rustc_metadata/src/rmeta/mod.rs
@@ -13,7 +13,7 @@ use rustc_hir::def::{CtorKind, DefKind};
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, FiniteBitSet};
+use rustc_index::bit_set::BitSet;
use rustc_index::vec::IndexVec;
use rustc_middle::metadata::ModChild;
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
@@ -22,7 +22,7 @@ use rustc_middle::middle::resolve_lifetime::ObjectLifetimeDefault;
use rustc_middle::mir;
use rustc_middle::ty::fast_reject::SimplifiedType;
use rustc_middle::ty::query::Providers;
-use rustc_middle::ty::{self, ReprOptions, Ty};
+use rustc_middle::ty::{self, ReprOptions, Ty, UnusedGenericParams};
use rustc_middle::ty::{DeducedParamAttrs, GeneratorDiagnosticData, ParameterizedOverTcx, TyCtxt};
use rustc_serialize::opaque::FileEncoder;
use rustc_session::config::SymbolManglingVersion;
@@ -359,8 +359,8 @@ define_tables! {
variances_of: Table<DefIndex, LazyArray<ty::Variance>>,
fn_sig: Table<DefIndex, LazyValue<ty::PolyFnSig<'static>>>,
codegen_fn_attrs: Table<DefIndex, LazyValue<CodegenFnAttrs>>,
- impl_trait_ref: Table<DefIndex, LazyValue<ty::TraitRef<'static>>>,
- const_param_default: Table<DefIndex, LazyValue<rustc_middle::ty::Const<'static>>>,
+ impl_trait_ref: Table<DefIndex, LazyValue<ty::EarlyBinder<ty::TraitRef<'static>>>>,
+ const_param_default: Table<DefIndex, LazyValue<ty::EarlyBinder<rustc_middle::ty::Const<'static>>>>,
object_lifetime_default: Table<DefIndex, LazyValue<ObjectLifetimeDefault>>,
optimized_mir: Table<DefIndex, LazyValue<mir::Body<'static>>>,
mir_for_ctfe: Table<DefIndex, LazyValue<mir::Body<'static>>>,
@@ -384,7 +384,7 @@ define_tables! {
trait_item_def_id: Table<DefIndex, RawDefId>,
inherent_impls: Table<DefIndex, LazyArray<DefIndex>>,
expn_that_defined: Table<DefIndex, LazyValue<ExpnId>>,
- unused_generic_params: Table<DefIndex, LazyValue<FiniteBitSet<u32>>>,
+ unused_generic_params: Table<DefIndex, LazyValue<UnusedGenericParams>>,
params_in_repr: Table<DefIndex, LazyValue<BitSet<u32>>>,
repr_options: Table<DefIndex, LazyValue<ReprOptions>>,
// `def_keys` and `def_path_hashes` represent a lazy version of a
@@ -418,11 +418,6 @@ struct VariantData {
is_non_exhaustive: bool,
}
-#[derive(TyEncodable, TyDecodable)]
-struct GeneratorData<'tcx> {
- layout: mir::GeneratorLayout<'tcx>,
-}
-
// Tags used for encoding Spans:
const TAG_VALID_SPAN_LOCAL: u8 = 0;
const TAG_VALID_SPAN_FOREIGN: u8 = 1;
diff --git a/compiler/rustc_metadata/src/rmeta/table.rs b/compiler/rustc_metadata/src/rmeta/table.rs
index 29fe61107..716655c7f 100644
--- a/compiler/rustc_metadata/src/rmeta/table.rs
+++ b/compiler/rustc_metadata/src/rmeta/table.rs
@@ -7,7 +7,6 @@ use rustc_middle::ty::ParameterizedOverTcx;
use rustc_serialize::opaque::FileEncoder;
use rustc_serialize::Encoder as _;
use rustc_span::hygiene::MacroKind;
-use std::convert::TryInto;
use std::marker::PhantomData;
use std::num::NonZeroUsize;