From 023939b627b7dc93b01471f7d41fb8553ddb4ffa Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Thu, 30 May 2024 05:59:24 +0200 Subject: Merging upstream version 1.73.0+dfsg1. Signed-off-by: Daniel Baumann --- compiler/rustc_metadata/messages.ftl | 3 + compiler/rustc_metadata/src/creader.rs | 34 ++++-- compiler/rustc_metadata/src/dependency_format.rs | 3 +- compiler/rustc_metadata/src/errors.rs | 16 ++- compiler/rustc_metadata/src/foreign_modules.rs | 17 ++- compiler/rustc_metadata/src/fs.rs | 6 +- compiler/rustc_metadata/src/locator.rs | 74 ++++++------ compiler/rustc_metadata/src/native_libs.rs | 99 +++++++-------- compiler/rustc_metadata/src/rmeta/decoder.rs | 49 ++++++-- .../src/rmeta/decoder/cstore_impl.rs | 14 +-- compiler/rustc_metadata/src/rmeta/encoder.rs | 133 ++++++++++----------- compiler/rustc_metadata/src/rmeta/mod.rs | 11 +- compiler/rustc_metadata/src/rmeta/table.rs | 10 +- 13 files changed, 261 insertions(+), 208 deletions(-) (limited to 'compiler/rustc_metadata') diff --git a/compiler/rustc_metadata/messages.ftl b/compiler/rustc_metadata/messages.ftl index 13b3dac85..cc58d51be 100644 --- a/compiler/rustc_metadata/messages.ftl +++ b/compiler/rustc_metadata/messages.ftl @@ -25,6 +25,9 @@ metadata_conflicting_alloc_error_handler = metadata_conflicting_global_alloc = the `#[global_allocator]` in {$other_crate_name} conflicts with global allocator in: {$crate_name} +metadata_consider_adding_std = + consider adding the standard library to the sysroot with `x build library --target {$locator_triple}` + metadata_consider_building_std = consider building the standard library from source with `cargo build -Zbuild-std` diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index b3976d756..fce80ab37 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -15,12 +15,12 @@ use rustc_hir::definitions::Definitions; use rustc_index::IndexVec; use rustc_middle::ty::TyCtxt; use rustc_session::config::{self, CrateType, ExternLocation}; -use rustc_session::cstore::ExternCrateSource; -use rustc_session::cstore::{CrateDepKind, CrateSource, ExternCrate}; +use rustc_session::cstore::{ + CrateDepKind, CrateSource, ExternCrate, ExternCrateSource, MetadataLoaderDyn, +}; use rustc_session::lint; use rustc_session::output::validate_crate_name; use rustc_session::search_paths::PathKind; -use rustc_session::Session; use rustc_span::edition::Edition; use rustc_span::symbol::{sym, Symbol}; use rustc_span::{Span, DUMMY_SP}; @@ -34,6 +34,8 @@ use std::time::Duration; use std::{cmp, env, iter}; pub struct CStore { + metadata_loader: Box, + metas: IndexVec>>, injected_panic_runtime: Option, /// This crate needs an allocator and either provides it itself, or finds it in a dependency. @@ -262,10 +264,14 @@ impl CStore { } } - pub fn new(sess: &Session) -> CStore { + pub fn new( + metadata_loader: Box, + local_stable_crate_id: StableCrateId, + ) -> CStore { let mut stable_crate_ids = StableCrateIdMap::default(); - stable_crate_ids.insert(sess.local_stable_crate_id(), LOCAL_CRATE); + stable_crate_ids.insert(local_stable_crate_id, LOCAL_CRATE); CStore { + metadata_loader, // 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 @@ -539,11 +545,13 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { (LoadResult::Previous(cnum), None) } else { info!("falling back to a load"); - let metadata_loader = self.tcx.metadata_loader(()).borrow(); let mut locator = CrateLocator::new( self.sess, - &**metadata_loader, + &*self.cstore.metadata_loader, name, + // The all loop is because `--crate-type=rlib --crate-type=rlib` is + // legal and produces both inside this type. + self.tcx.crate_types().iter().all(|c| *c == CrateType::Rlib), hash, extra_filename, false, // is_host @@ -687,7 +695,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { fn inject_panic_runtime(&mut self, krate: &ast::Crate) { // If we're only compiling an rlib, then there's no need to select a // panic runtime, so we just skip this section entirely. - let any_non_rlib = self.sess.crate_types().iter().any(|ct| *ct != CrateType::Rlib); + let any_non_rlib = self.tcx.crate_types().iter().any(|ct| *ct != CrateType::Rlib); if !any_non_rlib { info!("panic runtime injection skipped, only generating rlib"); return; @@ -741,7 +749,9 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { }; info!("panic runtime not found -- loading {}", name); - let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; }; + let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { + return; + }; let data = self.cstore.get_crate_data(cnum); // Sanity check the loaded crate to ensure it is indeed a panic runtime @@ -774,7 +784,9 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { self.sess.emit_err(errors::ProfilerBuiltinsNeedsCore); } - let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; }; + let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { + return; + }; let data = self.cstore.get_crate_data(cnum); // Sanity check the loaded crate to ensure it is indeed a profiler runtime @@ -812,7 +824,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { // At this point we've determined that we need an allocator. Let's see // if our compilation session actually needs an allocator based on what // we're emitting. - let all_rlib = self.sess.crate_types().iter().all(|ct| matches!(*ct, CrateType::Rlib)); + let all_rlib = self.tcx.crate_types().iter().all(|ct| matches!(*ct, CrateType::Rlib)); if all_rlib { return; } diff --git a/compiler/rustc_metadata/src/dependency_format.rs b/compiler/rustc_metadata/src/dependency_format.rs index 72b208a71..783d35ac7 100644 --- a/compiler/rustc_metadata/src/dependency_format.rs +++ b/compiler/rustc_metadata/src/dependency_format.rs @@ -66,8 +66,7 @@ use rustc_session::cstore::CrateDepKind; use rustc_session::cstore::LinkagePreference::{self, RequireDynamic, RequireStatic}; pub(crate) fn calculate(tcx: TyCtxt<'_>) -> Dependencies { - tcx.sess - .crate_types() + tcx.crate_types() .iter() .map(|&ty| { let linkage = calculate_type(tcx, ty); diff --git a/compiler/rustc_metadata/src/errors.rs b/compiler/rustc_metadata/src/errors.rs index fca06c0f4..91220629f 100644 --- a/compiler/rustc_metadata/src/errors.rs +++ b/compiler/rustc_metadata/src/errors.rs @@ -623,6 +623,7 @@ pub struct CannotFindCrate { pub is_nightly_build: bool, pub profiler_runtime: Symbol, pub locator_triple: TargetTriple, + pub is_ui_testing: bool, } impl IntoDiagnostic<'_> for CannotFindCrate { @@ -646,12 +647,19 @@ impl IntoDiagnostic<'_> for CannotFindCrate { } else { diag.note(fluent::metadata_target_no_std_support); } - // NOTE: this suggests using rustup, even though the user may not have it installed. - // That's because they could choose to install it; or this may give them a hint which - // target they need to install from their distro. + if self.missing_core { - diag.help(fluent::metadata_consider_downloading_target); + if env!("CFG_RELEASE_CHANNEL") == "dev" && !self.is_ui_testing { + // Note: Emits the nicer suggestion only for the dev channel. + diag.help(fluent::metadata_consider_adding_std); + } else { + // NOTE: this suggests using rustup, even though the user may not have it installed. + // That's because they could choose to install it; or this may give them a hint which + // target they need to install from their distro. + diag.help(fluent::metadata_consider_downloading_target); + } } + // Suggest using #![no_std]. #[no_core] is unstable and not really supported anyway. // NOTE: this is a dummy span if `extern crate std` was injected by the compiler. // If it's not a dummy, that means someone added `extern crate std` explicitly and diff --git a/compiler/rustc_metadata/src/foreign_modules.rs b/compiler/rustc_metadata/src/foreign_modules.rs index d1c2f3104..154eb684f 100644 --- a/compiler/rustc_metadata/src/foreign_modules.rs +++ b/compiler/rustc_metadata/src/foreign_modules.rs @@ -1,19 +1,28 @@ +use rustc_data_structures::fx::FxIndexMap; use rustc_hir as hir; use rustc_hir::def::DefKind; +use rustc_hir::def_id::DefId; +use rustc_middle::query::LocalCrate; use rustc_middle::ty::TyCtxt; use rustc_session::cstore::ForeignModule; -pub(crate) fn collect(tcx: TyCtxt<'_>) -> Vec { - let mut modules = Vec::new(); +pub(crate) fn collect(tcx: TyCtxt<'_>, LocalCrate: LocalCrate) -> FxIndexMap { + let mut modules = FxIndexMap::default(); + + // We need to collect all the `ForeignMod`, even if they are empty. for id in tcx.hir().items() { if !matches!(tcx.def_kind(id.owner_id), DefKind::ForeignMod) { continue; } + + let def_id = id.owner_id.to_def_id(); let item = tcx.hir().item(id); - if let hir::ItemKind::ForeignMod { items, .. } = item.kind { + + if let hir::ItemKind::ForeignMod { abi, items } = item.kind { let foreign_items = items.iter().map(|it| it.id.owner_id.to_def_id()).collect(); - modules.push(ForeignModule { foreign_items, def_id: id.owner_id.to_def_id() }); + modules.insert(def_id, ForeignModule { def_id, abi, foreign_items }); } } + modules } diff --git a/compiler/rustc_metadata/src/fs.rs b/compiler/rustc_metadata/src/fs.rs index 238f963ed..2a9662b80 100644 --- a/compiler/rustc_metadata/src/fs.rs +++ b/compiler/rustc_metadata/src/fs.rs @@ -56,7 +56,7 @@ pub fn encode_and_write_metadata(tcx: TyCtxt<'_>) -> (EncodedMetadata, bool) { // Always create a file at `metadata_filename`, even if we have nothing to write to it. // This simplifies the creation of the output `out_filename` when requested. - let metadata_kind = tcx.sess.metadata_kind(); + let metadata_kind = tcx.metadata_kind(); match metadata_kind { MetadataKind::None => { std::fs::File::create(&metadata_filename).unwrap_or_else(|err| { @@ -104,8 +104,8 @@ pub fn encode_and_write_metadata(tcx: TyCtxt<'_>) -> (EncodedMetadata, bool) { }; // Load metadata back to memory: codegen may need to include it in object files. - let metadata = EncodedMetadata::from_path(metadata_filename.clone(), metadata_tmpdir) - .unwrap_or_else(|err| { + let metadata = + EncodedMetadata::from_path(metadata_filename, metadata_tmpdir).unwrap_or_else(|err| { tcx.sess.emit_fatal(FailedCreateEncodedMetadata { err }); }); diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index a89d7b464..bf6004ba8 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -222,7 +222,7 @@ use rustc_data_structures::owned_slice::slice_owned; use rustc_data_structures::svh::Svh; use rustc_errors::{DiagnosticArgValue, FatalError, IntoDiagnosticArg}; use rustc_fs_util::try_canonicalize; -use rustc_session::config::{self, CrateType}; +use rustc_session::config; use rustc_session::cstore::{CrateSource, MetadataLoader}; use rustc_session::filesearch::FileSearch; use rustc_session::search_paths::PathKind; @@ -305,14 +305,12 @@ impl<'a> CrateLocator<'a> { sess: &'a Session, metadata_loader: &'a dyn MetadataLoader, crate_name: Symbol, + is_rlib: bool, hash: Option, extra_filename: Option<&'a str>, is_host: bool, path_kind: PathKind, ) -> CrateLocator<'a> { - // The all loop is because `--crate-type=rlib --crate-type=rlib` is - // legal and produces both inside this type. - let is_rlib = sess.crate_types().iter().all(|c| *c == CrateType::Rlib); let needs_object_code = sess.opts.output_types.should_codegen(); // If we're producing an rlib, then we don't need object code. // Or, if we're not producing object code, then we don't need it either @@ -511,7 +509,7 @@ impl<'a> CrateLocator<'a> { rlib: self.extract_one(rlibs, CrateFlavor::Rlib, &mut slot)?, dylib: self.extract_one(dylibs, CrateFlavor::Dylib, &mut slot)?, }; - Ok(slot.map(|(svh, metadata)| (svh, Library { source, metadata }))) + Ok(slot.map(|(svh, metadata, _)| (svh, Library { source, metadata }))) } fn needs_crate_flavor(&self, flavor: CrateFlavor) -> bool { @@ -535,11 +533,13 @@ impl<'a> CrateLocator<'a> { // read the metadata from it if `*slot` is `None`. If the metadata couldn't // be read, it is assumed that the file isn't a valid rust library (no // errors are emitted). + // + // The `PathBuf` in `slot` will only be used for diagnostic purposes. fn extract_one( &mut self, m: FxHashMap, flavor: CrateFlavor, - slot: &mut Option<(Svh, MetadataBlob)>, + slot: &mut Option<(Svh, MetadataBlob, PathBuf)>, ) -> Result, CrateError> { // If we are producing an rlib, and we've already loaded metadata, then // we should not attempt to discover further crate sources (unless we're @@ -550,16 +550,9 @@ impl<'a> CrateLocator<'a> { // // See also #68149 which provides more detail on why emitting the // dependency on the rlib is a bad thing. - // - // We currently do not verify that these other sources are even in sync, - // and this is arguably a bug (see #10786), but because reading metadata - // is quite slow (especially from dylibs) we currently do not read it - // from the other crate sources. if slot.is_some() { if m.is_empty() || !self.needs_crate_flavor(flavor) { return Ok(None); - } else if m.len() == 1 { - return Ok(Some(m.into_iter().next().unwrap())); } } @@ -610,8 +603,7 @@ impl<'a> CrateLocator<'a> { candidates, )); } - err_data = Some(vec![ret.as_ref().unwrap().0.clone()]); - *slot = None; + err_data = Some(vec![slot.take().unwrap().2]); } if let Some(candidates) = &mut err_data { candidates.push(lib); @@ -644,7 +636,7 @@ impl<'a> CrateLocator<'a> { continue; } } - *slot = Some((hash, metadata)); + *slot = Some((hash, metadata, lib.clone())); ret = Some((lib, kind)); } @@ -804,25 +796,36 @@ fn get_metadata_section<'p>( } // Length of the compressed stream - this allows linkers to pad the section if they want - let Ok(len_bytes) = <[u8; 4]>::try_from(&buf[header_len..cmp::min(data_start, buf.len())]) else { - return Err(MetadataError::LoadFailure("invalid metadata length found".to_string())); + let Ok(len_bytes) = + <[u8; 4]>::try_from(&buf[header_len..cmp::min(data_start, buf.len())]) + else { + return Err(MetadataError::LoadFailure( + "invalid metadata length found".to_string(), + )); }; let compressed_len = u32::from_be_bytes(len_bytes) as usize; // Header is okay -> inflate the actual metadata - let compressed_bytes = &buf[data_start..(data_start + compressed_len)]; - debug!("inflating {} bytes of compressed metadata", compressed_bytes.len()); - // Assume the decompressed data will be at least the size of the compressed data, so we - // don't have to grow the buffer as much. - let mut inflated = Vec::with_capacity(compressed_bytes.len()); - FrameDecoder::new(compressed_bytes).read_to_end(&mut inflated).map_err(|_| { - MetadataError::LoadFailure(format!( - "failed to decompress metadata: {}", - filename.display() - )) - })?; + let compressed_bytes = buf.slice(|buf| &buf[data_start..(data_start + compressed_len)]); + if &compressed_bytes[..cmp::min(METADATA_HEADER.len(), compressed_bytes.len())] + == METADATA_HEADER + { + // The metadata was not actually compressed. + compressed_bytes + } else { + debug!("inflating {} bytes of compressed metadata", compressed_bytes.len()); + // Assume the decompressed data will be at least the size of the compressed data, so we + // don't have to grow the buffer as much. + let mut inflated = Vec::with_capacity(compressed_bytes.len()); + FrameDecoder::new(&*compressed_bytes).read_to_end(&mut inflated).map_err(|_| { + MetadataError::LoadFailure(format!( + "failed to decompress metadata: {}", + filename.display() + )) + })?; - slice_owned(inflated, Deref::deref) + slice_owned(inflated, Deref::deref) + } } CrateFlavor::Rmeta => { // mmap the file, because only a small fraction of it is read. @@ -878,9 +881,10 @@ fn find_plugin_registrar_impl<'a>( sess, metadata_loader, name, - None, // hash - None, // extra_filename - true, // is_host + false, // is_rlib + None, // hash + None, // extra_filename + true, // is_host PathKind::Crate, ); @@ -903,7 +907,7 @@ pub fn list_file_metadata( 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), + Err(msg) => write!(out, "{msg}\n"), } } @@ -1125,6 +1129,7 @@ impl CrateError { is_nightly_build: sess.is_nightly_build(), profiler_runtime: Symbol::intern(&sess.opts.unstable_opts.profiler_runtime), locator_triple: locator.triple, + is_ui_testing: sess.opts.unstable_opts.ui_testing, }); } } @@ -1141,6 +1146,7 @@ impl CrateError { is_nightly_build: sess.is_nightly_build(), profiler_runtime: Symbol::intern(&sess.opts.unstable_opts.profiler_runtime), locator_triple: sess.opts.target_triple.clone(), + is_ui_testing: sess.opts.unstable_opts.ui_testing, }); } } diff --git a/compiler/rustc_metadata/src/native_libs.rs b/compiler/rustc_metadata/src/native_libs.rs index 0dd7b1197..098c411c8 100644 --- a/compiler/rustc_metadata/src/native_libs.rs +++ b/compiler/rustc_metadata/src/native_libs.rs @@ -1,15 +1,17 @@ use rustc_ast::{NestedMetaItem, CRATE_NODE_ID}; use rustc_attr as attr; use rustc_data_structures::fx::FxHashSet; -use rustc_hir as hir; -use rustc_hir::def::DefKind; +use rustc_middle::query::LocalCrate; use rustc_middle::ty::{List, ParamEnv, ParamEnvAnd, Ty, TyCtxt}; use rustc_session::config::CrateType; -use rustc_session::cstore::{DllCallingConvention, DllImport, NativeLib, PeImportNameType}; +use rustc_session::cstore::{ + DllCallingConvention, DllImport, ForeignModule, NativeLib, PeImportNameType, +}; use rustc_session::parse::feature_err; use rustc_session::search_paths::PathKind; use rustc_session::utils::NativeLibKind; use rustc_session::Session; +use rustc_span::def_id::{DefId, LOCAL_CRATE}; use rustc_span::symbol::{sym, Symbol}; use rustc_target::spec::abi::Abi; @@ -50,10 +52,11 @@ fn find_bundled_library( verbatim: Option, kind: NativeLibKind, has_cfg: bool, - sess: &Session, + tcx: TyCtxt<'_>, ) -> Option { + let sess = tcx.sess; if let NativeLibKind::Static { bundle: Some(true) | None, whole_archive } = kind - && sess.crate_types().iter().any(|t| matches!(t, &CrateType::Rlib | CrateType::Staticlib)) + && tcx.crate_types().iter().any(|t| matches!(t, &CrateType::Rlib | CrateType::Staticlib)) && (sess.opts.unstable_opts.packed_bundled_libs || has_cfg || whole_archive == Some(true)) { let verbatim = verbatim.unwrap_or(false); @@ -66,10 +69,12 @@ fn find_bundled_library( None } -pub(crate) fn collect(tcx: TyCtxt<'_>) -> Vec { +pub(crate) fn collect(tcx: TyCtxt<'_>, LocalCrate: LocalCrate) -> Vec { let mut collector = Collector { tcx, libs: Vec::new() }; - for id in tcx.hir().items() { - collector.process_item(id); + if tcx.sess.opts.unstable_opts.link_directives { + for module in tcx.foreign_modules(LOCAL_CRATE).values() { + collector.process_module(module); + } } collector.process_command_line(); collector.libs @@ -88,29 +93,20 @@ struct Collector<'tcx> { } impl<'tcx> Collector<'tcx> { - fn process_item(&mut self, id: rustc_hir::ItemId) { - if !matches!(self.tcx.def_kind(id.owner_id), DefKind::ForeignMod) { - return; - } + fn process_module(&mut self, module: &ForeignModule) { + let ForeignModule { def_id, abi, ref foreign_items } = *module; + let def_id = def_id.expect_local(); - let it = self.tcx.hir().item(id); - let hir::ItemKind::ForeignMod { abi, items: foreign_mod_items } = it.kind else { - return; - }; + let sess = self.tcx.sess; if matches!(abi, Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic) { return; } // Process all of the #[link(..)]-style arguments - let sess = self.tcx.sess; let features = self.tcx.features(); - if !sess.opts.unstable_opts.link_directives { - return; - } - - for m in self.tcx.hir().attrs(it.hir_id()).iter().filter(|a| a.has_name(sym::link)) { + for m in self.tcx.get_attrs(def_id, sym::link) { let Some(items) = m.meta_item_list() else { continue; }; @@ -340,9 +336,9 @@ impl<'tcx> Collector<'tcx> { if name.as_str().contains('\0') { sess.emit_err(errors::RawDylibNoNul { span: name_span }); } - foreign_mod_items + foreign_items .iter() - .map(|child_item| { + .map(|&child_item| { self.build_dll_import( abi, import_name_type.map(|(import_name_type, _)| import_name_type), @@ -352,21 +348,12 @@ impl<'tcx> Collector<'tcx> { .collect() } _ => { - for child_item in foreign_mod_items { - if self.tcx.def_kind(child_item.id.owner_id).has_codegen_attrs() - && self - .tcx - .codegen_fn_attrs(child_item.id.owner_id) - .link_ordinal - .is_some() + for &child_item in foreign_items { + if self.tcx.def_kind(child_item).has_codegen_attrs() + && self.tcx.codegen_fn_attrs(child_item).link_ordinal.is_some() { - let link_ordinal_attr = self - .tcx - .hir() - .attrs(child_item.id.owner_id.into()) - .iter() - .find(|a| a.has_name(sym::link_ordinal)) - .unwrap(); + let link_ordinal_attr = + self.tcx.get_attr(child_item, sym::link_ordinal).unwrap(); sess.emit_err(errors::LinkOrdinalRawDylib { span: link_ordinal_attr.span, }); @@ -378,13 +365,13 @@ impl<'tcx> Collector<'tcx> { }; let kind = kind.unwrap_or(NativeLibKind::Unspecified); - let filename = find_bundled_library(name, verbatim, kind, cfg.is_some(), sess); + let filename = find_bundled_library(name, verbatim, kind, cfg.is_some(), self.tcx); self.libs.push(NativeLib { name, filename, kind, cfg, - foreign_module: Some(it.owner_id.to_def_id()), + foreign_module: Some(def_id.to_def_id()), verbatim, dll_imports, }); @@ -456,9 +443,13 @@ impl<'tcx> Collector<'tcx> { // Add if not found let new_name: Option<&str> = passed_lib.new_name.as_deref(); let name = Symbol::intern(new_name.unwrap_or(&passed_lib.name)); - let sess = self.tcx.sess; - let filename = - find_bundled_library(name, passed_lib.verbatim, passed_lib.kind, false, sess); + let filename = find_bundled_library( + name, + passed_lib.verbatim, + passed_lib.kind, + false, + self.tcx, + ); self.libs.push(NativeLib { name, filename, @@ -476,11 +467,11 @@ impl<'tcx> Collector<'tcx> { } } - fn i686_arg_list_size(&self, item: &hir::ForeignItemRef) -> usize { + fn i686_arg_list_size(&self, item: DefId) -> usize { let argument_types: &List> = self.tcx.erase_late_bound_regions( self.tcx - .type_of(item.id.owner_id) - .subst_identity() + .type_of(item) + .instantiate_identity() .fn_sig(self.tcx) .inputs() .map_bound(|slice| self.tcx.mk_type_list(slice)), @@ -505,8 +496,10 @@ impl<'tcx> Collector<'tcx> { &self, abi: Abi, import_name_type: Option, - item: &hir::ForeignItemRef, + item: DefId, ) -> DllImport { + let span = self.tcx.def_span(item); + let calling_convention = if self.tcx.sess.target.arch == "x86" { match abi { Abi::C { .. } | Abi::Cdecl { .. } => DllCallingConvention::C, @@ -520,29 +513,29 @@ impl<'tcx> Collector<'tcx> { DllCallingConvention::Vectorcall(self.i686_arg_list_size(item)) } _ => { - self.tcx.sess.emit_fatal(errors::UnsupportedAbiI686 { span: item.span }); + self.tcx.sess.emit_fatal(errors::UnsupportedAbiI686 { span }); } } } else { match abi { Abi::C { .. } | Abi::Win64 { .. } | Abi::System { .. } => DllCallingConvention::C, _ => { - self.tcx.sess.emit_fatal(errors::UnsupportedAbi { span: item.span }); + self.tcx.sess.emit_fatal(errors::UnsupportedAbi { span }); } } }; - let codegen_fn_attrs = self.tcx.codegen_fn_attrs(item.id.owner_id); + let codegen_fn_attrs = self.tcx.codegen_fn_attrs(item); let import_name_type = codegen_fn_attrs .link_ordinal .map_or(import_name_type, |ord| Some(PeImportNameType::Ordinal(ord))); DllImport { - name: codegen_fn_attrs.link_name.unwrap_or(item.ident.name), + name: codegen_fn_attrs.link_name.unwrap_or(self.tcx.item_name(item)), import_name_type, calling_convention, - span: item.span, - is_fn: self.tcx.def_kind(item.id.owner_id).is_fn_like(), + span, + is_fn: self.tcx.def_kind(item).is_fn_like(), } } } diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index b9318aee5..e8f66c36a 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -34,7 +34,7 @@ use rustc_session::cstore::{ use rustc_session::Session; use rustc_span::hygiene::ExpnIndex; use rustc_span::symbol::{kw, Ident, Symbol}; -use rustc_span::{self, BytePos, ExpnId, Pos, Span, SyntaxContext, DUMMY_SP}; +use rustc_span::{self, BytePos, ExpnId, Pos, Span, SpanData, SyntaxContext, DUMMY_SP}; use proc_macro::bridge::client::ProcMacro; use std::iter::TrustedLen; @@ -311,8 +311,10 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> { #[inline] fn tcx(&self) -> TyCtxt<'tcx> { let Some(tcx) = self.tcx else { - bug!("No TyCtxt found for decoding. \ - You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`."); + bug!( + "No TyCtxt found for decoding. \ + You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`." + ); }; tcx } @@ -448,8 +450,10 @@ impl<'a, 'tcx> Decodable> for SyntaxContext { let cdata = decoder.cdata(); let Some(sess) = decoder.sess else { - bug!("Cannot decode SyntaxContext without Session.\ - You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`."); + bug!( + "Cannot decode SyntaxContext without Session.\ + You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`." + ); }; let cname = cdata.root.name(); @@ -470,8 +474,10 @@ impl<'a, 'tcx> Decodable> for ExpnId { let local_cdata = decoder.cdata(); let Some(sess) = decoder.sess else { - bug!("Cannot decode ExpnId without Session. \ - You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`."); + bug!( + "Cannot decode ExpnId without Session. \ + You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`." + ); }; let cnum = CrateNum::decode(decoder); @@ -507,11 +513,26 @@ impl<'a, 'tcx> Decodable> for ExpnId { impl<'a, 'tcx> Decodable> for Span { fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Span { + let mode = SpanEncodingMode::decode(decoder); + let data = match mode { + SpanEncodingMode::Direct => SpanData::decode(decoder), + SpanEncodingMode::Shorthand(position) => decoder.with_position(position, |decoder| { + let mode = SpanEncodingMode::decode(decoder); + debug_assert!(matches!(mode, SpanEncodingMode::Direct)); + SpanData::decode(decoder) + }), + }; + Span::new(data.lo, data.hi, data.ctxt, data.parent) + } +} + +impl<'a, 'tcx> Decodable> for SpanData { + fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> SpanData { let ctxt = SyntaxContext::decode(decoder); let tag = u8::decode(decoder); if tag == TAG_PARTIAL_SPAN { - return DUMMY_SP.with_ctxt(ctxt); + return DUMMY_SP.with_ctxt(ctxt).data(); } debug_assert!(tag == TAG_VALID_SPAN_LOCAL || tag == TAG_VALID_SPAN_FOREIGN); @@ -521,8 +542,10 @@ impl<'a, 'tcx> Decodable> for Span { let hi = lo + len; let Some(sess) = decoder.sess else { - bug!("Cannot decode Span without Session. \ - You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`.") + bug!( + "Cannot decode Span without Session. \ + You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`." + ) }; // Index of the file in the corresponding crate's list of encoded files. @@ -604,7 +627,7 @@ impl<'a, 'tcx> Decodable> for Span { let hi = hi + source_file.translated_source_file.start_pos; // Do not try to decode parent for foreign spans. - Span::new(lo, hi, ctxt, None) + SpanData { lo, hi, ctxt, parent: None } } } @@ -819,7 +842,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { .decode((self, sess)) } - fn load_proc_macro(self, id: DefIndex, sess: &Session) -> SyntaxExtension { + fn load_proc_macro(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> SyntaxExtension { let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) { ProcMacro::CustomDerive { trait_name, attributes, client } => { let helper_attrs = @@ -838,9 +861,11 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { } }; + let sess = tcx.sess; let attrs: Vec<_> = self.get_item_attrs(id, sess).collect(); SyntaxExtension::new( sess, + tcx.features(), kind, self.get_span(id, sess), helper_attrs, diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index 848535fb3..aeda8af6d 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -6,6 +6,7 @@ use crate::rmeta::AttrFlags; use rustc_ast as ast; use rustc_attr::Deprecation; +use rustc_data_structures::sync::Lrc; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE}; use rustc_hir::definitions::{DefKey, DefPath, DefPathHash}; @@ -23,7 +24,6 @@ use rustc_span::hygiene::{ExpnHash, ExpnId}; use rustc_span::symbol::{kw, Symbol}; use rustc_span::Span; -use rustc_data_structures::sync::Lrc; use std::any::Any; use super::{Decodable, DecodeContext, DecodeIterator}; @@ -246,6 +246,7 @@ provide! { tcx, def_id, other, cdata, debug_assert_eq!(tcx.def_kind(def_id), DefKind::OpaqueTy); cdata.root.tables.is_type_alias_impl_trait.get(cdata, def_id.index) } + assumed_wf_types_for_rpitit => { table } collect_return_position_impl_trait_in_trait_tys => { Ok(cdata .root @@ -403,10 +404,8 @@ pub(in crate::rmeta) fn provide(providers: &mut Providers) { .contains(&id) }) }, - native_libraries: |tcx, LocalCrate| native_libs::collect(tcx), - foreign_modules: |tcx, LocalCrate| { - foreign_modules::collect(tcx).into_iter().map(|m| (m.def_id, m)).collect() - }, + native_libraries: native_libs::collect, + foreign_modules: foreign_modules::collect, // Returns a map from a sufficiently visible external item (i.e., an // external item that is visible from at least one local module) to a @@ -523,12 +522,13 @@ impl CStore { self.get_crate_data(def.krate).get_ctor(def.index) } - pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro { + pub fn load_macro_untracked(&self, id: DefId, tcx: TyCtxt<'_>) -> LoadedMacro { + let sess = tcx.sess; let _prof_timer = sess.prof.generic_activity("metadata_load_macro"); let data = self.get_crate_data(id.krate); if data.root.is_proc_macro_crate() { - return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess)); + return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, tcx)); } let span = data.get_span(id.index, sess); diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 541c19c35..be91ad408 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -30,6 +30,7 @@ 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::TypeVisitableExt; use rustc_middle::ty::{self, AssocItemContainer, SymbolName, Ty, TyCtxt}; use rustc_middle::util::common::to_readable_str; use rustc_serialize::{opaque, Decodable, Decoder, Encodable, Encoder}; @@ -37,7 +38,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, ExternalSource, FileName, SourceFile, Span, SyntaxContext}; +use rustc_span::{self, ExternalSource, FileName, SourceFile, Span, SpanData, SyntaxContext}; use std::borrow::Borrow; use std::collections::hash_map::Entry; use std::hash::Hash; @@ -53,6 +54,7 @@ pub(super) struct EncodeContext<'a, 'tcx> { tables: TableBuilders, lazy_state: LazyState, + span_shorthands: FxHashMap, type_shorthands: FxHashMap, usize>, predicate_shorthands: FxHashMap, usize>, @@ -177,8 +179,20 @@ impl<'a, 'tcx> Encodable> for ExpnId { impl<'a, 'tcx> Encodable> for Span { fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) { - let span = self.data(); + match s.span_shorthands.entry(*self) { + Entry::Occupied(o) => SpanEncodingMode::Shorthand(*o.get()).encode(s), + Entry::Vacant(v) => { + let position = s.opaque.position(); + v.insert(position); + SpanEncodingMode::Direct.encode(s); + self.data().encode(s); + } + } + } +} +impl<'a, 'tcx> Encodable> for SpanData { + fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) { // Don't serialize any `SyntaxContext`s from a proc-macro crate, // since we don't load proc-macro dependencies during serialization. // This means that any hygiene information from macros used *within* @@ -213,7 +227,7 @@ impl<'a, 'tcx> Encodable> for Span { if s.is_proc_macro { SyntaxContext::root().encode(s); } else { - span.ctxt.encode(s); + self.ctxt.encode(s); } if self.is_dummy() { @@ -221,18 +235,18 @@ impl<'a, 'tcx> Encodable> for Span { } // The Span infrastructure should make sure that this invariant holds: - debug_assert!(span.lo <= span.hi); + debug_assert!(self.lo <= self.hi); - if !s.source_file_cache.0.contains(span.lo) { + if !s.source_file_cache.0.contains(self.lo) { let source_map = s.tcx.sess.source_map(); - let source_file_index = source_map.lookup_source_file_idx(span.lo); + let source_file_index = source_map.lookup_source_file_idx(self.lo); s.source_file_cache = (source_map.files()[source_file_index].clone(), source_file_index); } let (ref source_file, source_file_index) = s.source_file_cache; - debug_assert!(source_file.contains(span.lo)); + debug_assert!(source_file.contains(self.lo)); - if !source_file.contains(span.hi) { + if !source_file.contains(self.hi) { // Unfortunately, macro expansion still sometimes generates Spans // that malformed in this way. return TAG_PARTIAL_SPAN.encode(s); @@ -286,11 +300,11 @@ impl<'a, 'tcx> Encodable> for Span { // Encode the start position relative to the file start, so we profit more from the // variable-length integer encoding. - let lo = span.lo - source_file.start_pos; + let lo = self.lo - source_file.start_pos; // Encode length which is usually less than span.hi and profits more // from the variable-length integer encoding that we use. - let len = span.hi - span.lo; + let len = self.hi - self.lo; tag.encode(s); lo.encode(s); @@ -608,7 +622,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { trace!("encoding {} further alloc ids", new_n - n); for idx in n..new_n { let id = self.interpret_allocs[idx]; - let pos = self.position() as u32; + let pos = self.position() as u64; interpret_alloc_index.push(pos); interpret::specialized_encode_alloc_id(self, tcx, id); } @@ -805,7 +819,7 @@ fn should_encode_span(def_kind: DefKind) -> bool { | DefKind::Enum | DefKind::Variant | DefKind::Trait - | DefKind::TyAlias + | DefKind::TyAlias { .. } | DefKind::ForeignTy | DefKind::TraitAlias | DefKind::AssocTy @@ -824,7 +838,6 @@ fn should_encode_span(def_kind: DefKind) -> bool { | DefKind::AnonConst | DefKind::InlineConst | DefKind::OpaqueTy - | DefKind::ImplTraitPlaceholder | DefKind::Field | DefKind::Impl { .. } | DefKind::Closure @@ -841,7 +854,7 @@ fn should_encode_attrs(def_kind: DefKind) -> bool { | DefKind::Enum | DefKind::Variant | DefKind::Trait - | DefKind::TyAlias + | DefKind::TyAlias { .. } | DefKind::ForeignTy | DefKind::TraitAlias | DefKind::AssocTy @@ -867,7 +880,6 @@ fn should_encode_attrs(def_kind: DefKind) -> bool { | DefKind::AnonConst | DefKind::InlineConst | DefKind::OpaqueTy - | DefKind::ImplTraitPlaceholder | DefKind::LifetimeParam | DefKind::GlobalAsm | DefKind::Generator => false, @@ -883,7 +895,7 @@ fn should_encode_expn_that_defined(def_kind: DefKind) -> bool { | DefKind::Variant | DefKind::Trait | DefKind::Impl { .. } => true, - DefKind::TyAlias + DefKind::TyAlias { .. } | DefKind::ForeignTy | DefKind::TraitAlias | DefKind::AssocTy @@ -902,7 +914,6 @@ fn should_encode_expn_that_defined(def_kind: DefKind) -> bool { | DefKind::AnonConst | DefKind::InlineConst | DefKind::OpaqueTy - | DefKind::ImplTraitPlaceholder | DefKind::Field | DefKind::LifetimeParam | DefKind::GlobalAsm @@ -919,7 +930,7 @@ fn should_encode_visibility(def_kind: DefKind) -> bool { | DefKind::Enum | DefKind::Variant | DefKind::Trait - | DefKind::TyAlias + | DefKind::TyAlias { .. } | DefKind::ForeignTy | DefKind::TraitAlias | DefKind::AssocTy @@ -939,7 +950,6 @@ fn should_encode_visibility(def_kind: DefKind) -> bool { | DefKind::AnonConst | DefKind::InlineConst | DefKind::OpaqueTy - | DefKind::ImplTraitPlaceholder | DefKind::GlobalAsm | DefKind::Impl { .. } | DefKind::Closure @@ -964,9 +974,8 @@ fn should_encode_stability(def_kind: DefKind) -> bool { | DefKind::Const | DefKind::Fn | DefKind::ForeignMod - | DefKind::TyAlias + | DefKind::TyAlias { .. } | DefKind::OpaqueTy - | DefKind::ImplTraitPlaceholder | DefKind::Enum | DefKind::Union | DefKind::Impl { .. } @@ -1026,14 +1035,13 @@ fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) { } } -fn should_encode_variances(def_kind: DefKind) -> bool { +fn should_encode_variances<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: DefKind) -> bool { match def_kind { DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::Variant | DefKind::OpaqueTy - | DefKind::ImplTraitPlaceholder | DefKind::Fn | DefKind::Ctor(..) | DefKind::AssocFn => true, @@ -1046,7 +1054,6 @@ fn should_encode_variances(def_kind: DefKind) -> bool { | DefKind::Static(..) | DefKind::Const | DefKind::ForeignMod - | DefKind::TyAlias | DefKind::Impl { .. } | DefKind::Trait | DefKind::TraitAlias @@ -1060,6 +1067,9 @@ fn should_encode_variances(def_kind: DefKind) -> bool { | DefKind::Closure | DefKind::Generator | DefKind::ExternCrate => false, + DefKind::TyAlias { lazy } => { + lazy || tcx.type_of(def_id).instantiate_identity().has_opaque_types() + } } } @@ -1070,7 +1080,7 @@ fn should_encode_generics(def_kind: DefKind) -> bool { | DefKind::Enum | DefKind::Variant | DefKind::Trait - | DefKind::TyAlias + | DefKind::TyAlias { .. } | DefKind::ForeignTy | DefKind::TraitAlias | DefKind::AssocTy @@ -1083,7 +1093,6 @@ fn should_encode_generics(def_kind: DefKind) -> bool { | DefKind::AnonConst | DefKind::InlineConst | DefKind::OpaqueTy - | DefKind::ImplTraitPlaceholder | DefKind::Impl { .. } | DefKind::Field | DefKind::TyParam @@ -1111,7 +1120,7 @@ fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> | DefKind::Fn | DefKind::Const | DefKind::Static(..) - | DefKind::TyAlias + | DefKind::TyAlias { .. } | DefKind::ForeignTy | DefKind::Impl { .. } | DefKind::AssocFn @@ -1134,30 +1143,11 @@ fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> } } - DefKind::ImplTraitPlaceholder => { - let parent_def_id = tcx.impl_trait_in_trait_parent_fn(def_id.to_def_id()); - let assoc_item = tcx.associated_item(parent_def_id); - match assoc_item.container { - // Always encode an RPIT in an impl fn, since it always has a body - ty::AssocItemContainer::ImplContainer => true, - ty::AssocItemContainer::TraitContainer => { - // Encode an RPIT for a trait only if the trait has a default body - assoc_item.defaultness(tcx).has_value() - } - } - } - DefKind::AssocTy => { let assoc_item = tcx.associated_item(def_id); match assoc_item.container { ty::AssocItemContainer::ImplContainer => true, - // Always encode RPITITs, since we need to be able to project - // from an RPITIT associated item to an opaque when installing - // the default projection predicates in default trait methods - // with RPITITs. - ty::AssocItemContainer::TraitContainer => { - assoc_item.defaultness(tcx).has_value() || assoc_item.opt_rpitit_info.is_some() - } + ty::AssocItemContainer::TraitContainer => assoc_item.defaultness(tcx).has_value(), } } DefKind::TyParam => { @@ -1190,9 +1180,8 @@ fn should_encode_fn_sig(def_kind: DefKind) -> bool { | DefKind::Const | DefKind::Static(..) | DefKind::Ctor(..) - | DefKind::TyAlias + | DefKind::TyAlias { .. } | DefKind::OpaqueTy - | DefKind::ImplTraitPlaceholder | DefKind::ForeignTy | DefKind::Impl { .. } | DefKind::AssocConst @@ -1232,10 +1221,9 @@ fn should_encode_constness(def_kind: DefKind) -> bool { | DefKind::AssocConst | DefKind::AnonConst | DefKind::Static(..) - | DefKind::TyAlias + | DefKind::TyAlias { .. } | DefKind::OpaqueTy | DefKind::Impl { of_trait: false } - | DefKind::ImplTraitPlaceholder | DefKind::ForeignTy | DefKind::Generator | DefKind::ConstParam @@ -1266,9 +1254,8 @@ fn should_encode_const(def_kind: DefKind) -> bool { | DefKind::Field | DefKind::Fn | DefKind::Static(..) - | DefKind::TyAlias + | DefKind::TyAlias { .. } | DefKind::OpaqueTy - | DefKind::ImplTraitPlaceholder | DefKind::ForeignTy | DefKind::Impl { .. } | DefKind::AssocFn @@ -1289,11 +1276,8 @@ fn should_encode_const(def_kind: DefKind) -> bool { } } -// We only encode impl trait in trait when using `lower-impl-trait-in-trait-to-assoc-ty` unstable -// option. fn should_encode_fn_impl_trait_in_trait<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool { - if tcx.lower_impl_trait_in_trait_to_assoc_ty() - && let Some(assoc_item) = tcx.opt_associated_item(def_id) + if let Some(assoc_item) = tcx.opt_associated_item(def_id) && assoc_item.container == ty::AssocItemContainer::TraitContainer && assoc_item.kind == ty::AssocKind::Fn { @@ -1368,7 +1352,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { self.encode_default_body_stability(def_id); self.encode_deprecation(def_id); } - if should_encode_variances(def_kind) { + if should_encode_variances(tcx, def_id, def_kind) { let v = self.tcx.variances_of(def_id); record_array!(self.tables.variances_of[def_id] <- v); } @@ -1447,9 +1431,6 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { .is_type_alias_impl_trait .set(def_id.index, self.tcx.is_type_alias_impl_trait(def_id)); } - if let DefKind::ImplTraitPlaceholder = def_kind { - self.encode_explicit_item_bounds(def_id); - } if tcx.impl_method_has_trait_impl_trait_tys(def_id) && let Ok(table) = self.tcx.collect_return_position_impl_trait_in_trait_tys(def_id) { @@ -1576,6 +1557,12 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { } if let Some(rpitit_info) = item.opt_rpitit_info { record!(self.tables.opt_rpitit_info[def_id] <- rpitit_info); + if matches!(rpitit_info, ty::ImplTraitInTraitData::Trait { .. }) { + record_array!( + self.tables.assumed_wf_types_for_rpitit[def_id] + <- self.tcx.assumed_wf_types_for_rpitit(def_id) + ); + } } } @@ -1700,7 +1687,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { fn encode_info_for_macro(&mut self, def_id: LocalDefId) { let tcx = self.tcx; - let hir::ItemKind::Macro(ref macro_def, _) = tcx.hir().expect_item(def_id).kind else { bug!() }; + let hir::ItemKind::Macro(ref macro_def, _) = tcx.hir().expect_item(def_id).kind else { + bug!() + }; self.tables.is_macro_rules.set(def_id.local_def_index, macro_def.macro_rules); record!(self.tables.macro_definition[def_id.to_def_id()] <- &*macro_def.body); } @@ -1752,7 +1741,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { } fn encode_proc_macros(&mut self) -> Option { - let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro); + let is_proc_macro = self.tcx.crate_types().contains(&CrateType::ProcMacro); if is_proc_macro { let tcx = self.tcx; let hir = tcx.hir(); @@ -1940,7 +1929,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { FxHashMap::default(); for id in tcx.hir().items() { - let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else { continue; }; + let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else { + continue; + }; let def_id = id.owner_id.to_def_id(); self.tables.defaultness.set_some(def_id.index, tcx.defaultness(def_id)); @@ -1949,7 +1940,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { if of_trait && let Some(trait_ref) = tcx.impl_trait_ref(def_id) { record!(self.tables.impl_trait_ref[def_id] <- trait_ref); - let trait_ref = trait_ref.subst_identity(); + let trait_ref = trait_ref.instantiate_identity(); let simplified_self_ty = fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), TreatParams::AsCandidateKey); fx_hash_map @@ -2207,12 +2198,13 @@ fn encode_metadata_impl(tcx: TyCtxt<'_>, path: &Path) { feat: tcx.features(), tables: Default::default(), lazy_state: LazyState::NoNode, + span_shorthands: Default::default(), type_shorthands: Default::default(), predicate_shorthands: Default::default(), source_file_cache, interpret_allocs: Default::default(), required_source_files, - is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro), + is_proc_macro: tcx.crate_types().contains(&CrateType::ProcMacro), hygiene_ctxt: &hygiene_ctxt, symbol_table: Default::default(), }; @@ -2255,13 +2247,12 @@ pub fn provide(providers: &mut Providers) { tcx.resolutions(()) .doc_link_resolutions .get(&def_id) - .expect("no resolutions for a doc link") + .unwrap_or_else(|| span_bug!(tcx.def_span(def_id), "no resolutions for a doc link")) }, doc_link_traits_in_scope: |tcx, def_id| { - tcx.resolutions(()) - .doc_link_traits_in_scope - .get(&def_id) - .expect("no traits in scope for a doc link") + tcx.resolutions(()).doc_link_traits_in_scope.get(&def_id).unwrap_or_else(|| { + span_bug!(tcx.def_span(def_id), "no traits in scope for a doc link") + }) }, traits: |tcx, LocalCrate| { let mut traits = Vec::new(); diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index 9cffd96f4..a89e235ff 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -51,7 +51,7 @@ mod encoder; mod table; pub(crate) fn rustc_version(cfg_version: &'static str) -> String { - format!("rustc {}", cfg_version) + format!("rustc {cfg_version}") } /// Metadata encoding version. @@ -66,6 +66,12 @@ const METADATA_VERSION: u8 = 8; /// unsigned integer, and further followed by the rustc version string. pub const METADATA_HEADER: &[u8] = &[b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION]; +#[derive(Encodable, Decodable)] +enum SpanEncodingMode { + Shorthand(usize), + Direct, +} + /// A value of type T referred to by its absolute position /// in the metadata, and which can be decoded lazily. /// @@ -264,7 +270,7 @@ pub(crate) struct CrateRoot { traits: LazyArray, impls: LazyArray, incoherent_impls: LazyArray, - interpret_alloc_index: LazyArray, + interpret_alloc_index: LazyArray, proc_macro_data: Option, tables: LazyTables, @@ -451,6 +457,7 @@ define_tables! { trait_impl_trait_tys: Table>>>>, doc_link_resolutions: Table>, doc_link_traits_in_scope: Table>, + assumed_wf_types_for_rpitit: Table, Span)>>, } #[derive(TyEncodable, TyDecodable)] diff --git a/compiler/rustc_metadata/src/rmeta/table.rs b/compiler/rustc_metadata/src/rmeta/table.rs index f002d7f97..ea66c770b 100644 --- a/compiler/rustc_metadata/src/rmeta/table.rs +++ b/compiler/rustc_metadata/src/rmeta/table.rs @@ -126,7 +126,8 @@ fixed_size_enum! { ( Enum ) ( Variant ) ( Trait ) - ( TyAlias ) + ( TyAlias { lazy: false } ) + ( TyAlias { lazy: true } ) ( ForeignTy ) ( TraitAlias ) ( AssocTy ) @@ -142,7 +143,6 @@ fixed_size_enum! { ( AnonConst ) ( InlineConst ) ( OpaqueTy ) - ( ImplTraitPlaceholder ) ( Field ) ( LifetimeParam ) ( GlobalAsm ) @@ -324,7 +324,7 @@ impl FixedSizeEncoding for Option> { impl LazyArray { #[inline] fn write_to_bytes_impl(self, b: &mut [u8; 8]) { - let ([position_bytes, meta_bytes],[])= b.as_chunks_mut::<4>() else { panic!() }; + let ([position_bytes, meta_bytes], []) = b.as_chunks_mut::<4>() else { panic!() }; let position = self.position.get(); let position: u32 = position.try_into().unwrap(); @@ -347,7 +347,7 @@ impl FixedSizeEncoding for LazyArray { #[inline] fn from_bytes(b: &[u8; 8]) -> Self { - let ([position_bytes, meta_bytes],[])= b.as_chunks::<4>() else { panic!() }; + let ([position_bytes, meta_bytes], []) = b.as_chunks::<4>() else { panic!() }; if *meta_bytes == [0; 4] { return Default::default(); } @@ -366,7 +366,7 @@ impl FixedSizeEncoding for Option> { #[inline] fn from_bytes(b: &[u8; 8]) -> Self { - let ([position_bytes, meta_bytes],[])= b.as_chunks::<4>() else { panic!() }; + let ([position_bytes, meta_bytes], []) = b.as_chunks::<4>() else { panic!() }; LazyArray::from_bytes_impl(position_bytes, meta_bytes) } -- cgit v1.2.3