From 6f1ac8d756a7a7c22641020926458058a51d5dd3 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Sat, 3 Apr 2021 13:45:02 +0800 Subject: [PATCH 1/7] rustc: target: add sysroot to rust_target_path This enables placing a `target.json` file into the rust sysroot under the target-specific directory. Signed-off-by: Sean Cross --- compiler/rustc_session/src/config.rs | 4 ++-- compiler/rustc_session/src/session.rs | 13 +++++++------ compiler/rustc_target/src/spec/mod.rs | 20 ++++++++++++++++---- 3 files changed, 25 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 77a9a2b227ca0..f3da9a1bda108 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -927,8 +927,8 @@ pub fn build_configuration(sess: &Session, mut user_cfg: CrateConfig) -> CrateCo user_cfg } -pub fn build_target_config(opts: &Options, target_override: Option) -> Target { - let target_result = target_override.map_or_else(|| Target::search(&opts.target_triple), Ok); +pub fn build_target_config(opts: &Options, target_override: Option, sysroot: &PathBuf) -> Target { + let target_result = target_override.map_or_else(|| Target::search(&opts.target_triple, sysroot), Ok); let target = target_result.unwrap_or_else(|e| { early_error( opts.error_format, diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 493bbb3a76201..08a7447008ae7 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -1301,9 +1301,14 @@ pub fn build_session( DiagnosticOutput::Raw(write) => Some(write), }; - let target_cfg = config::build_target_config(&sopts, target_override); + let sysroot = match &sopts.maybe_sysroot { + Some(sysroot) => sysroot.clone(), + None => filesearch::get_or_default_sysroot(), + }; + + let target_cfg = config::build_target_config(&sopts, target_override, &sysroot); let host_triple = TargetTriple::from_triple(config::host_triple()); - let host = Target::search(&host_triple).unwrap_or_else(|e| { + let host = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| { early_error(sopts.error_format, &format!("Error loading host specification: {}", e)) }); @@ -1350,10 +1355,6 @@ pub fn build_session( let mut parse_sess = ParseSess::with_span_handler(span_diagnostic, source_map); parse_sess.assume_incomplete_release = sopts.debugging_opts.assume_incomplete_release; - let sysroot = match &sopts.maybe_sysroot { - Some(sysroot) => sysroot.clone(), - None => filesearch::get_or_default_sysroot(), - }; let host_triple = config::host_triple(); let target_triple = sopts.target_triple.triple(); diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 039e9a8b2745f..27653d3c331cb 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -1747,13 +1747,15 @@ impl Target { } /// Search RUST_TARGET_PATH for a JSON file specifying the given target - /// triple. Note that it could also just be a bare filename already, so also + /// triple. If none is found, look for a file called `target.json` inside + /// the sysroot under the target-triple's `rustlib` directory. + /// Note that it could also just be a bare filename already, so also /// check for that. If one of the hardcoded targets we know about, just /// return it directly. /// /// The error string could come from any of the APIs called, including /// filesystem access and JSON decoding. - pub fn search(target_triple: &TargetTriple) -> Result { + pub fn search(target_triple: &TargetTriple, sysroot: &PathBuf) -> Result { use rustc_serialize::json; use std::env; use std::fs; @@ -1780,14 +1782,24 @@ impl Target { let target_path = env::var_os("RUST_TARGET_PATH").unwrap_or_default(); - // FIXME 16351: add a sane default search path? - for dir in env::split_paths(&target_path) { let p = dir.join(&path); if p.is_file() { return load_file(&p); } } + + // Additionally look in the sysroot under `lib/rustlib//target.json` + // as a fallback. + let p = sysroot + .join("lib") + .join("rustlib") + .join(&target_triple) + .join("target.json"); + if p.is_file() { + return load_file(&p); + } + Err(format!("Could not find specification for target {:?}", target_triple)) } TargetTriple::TargetPath(ref target_path) => { From 8f73fe91f5db7de6e42ad7824a00b9729d2925b2 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Sat, 3 Apr 2021 15:00:10 +0800 Subject: [PATCH 2/7] compiler: run `python3 ./x.py fmt` This fixes a build issue with formatting as part of #83800. Signed-off-by: Sean Cross --- compiler/rustc_session/src/config.rs | 9 +++++++-- compiler/rustc_target/src/spec/mod.rs | 7 ++----- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index f3da9a1bda108..65be14e3510c7 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -927,8 +927,13 @@ pub fn build_configuration(sess: &Session, mut user_cfg: CrateConfig) -> CrateCo user_cfg } -pub fn build_target_config(opts: &Options, target_override: Option, sysroot: &PathBuf) -> Target { - let target_result = target_override.map_or_else(|| Target::search(&opts.target_triple, sysroot), Ok); +pub fn build_target_config( + opts: &Options, + target_override: Option, + sysroot: &PathBuf, +) -> Target { + let target_result = + target_override.map_or_else(|| Target::search(&opts.target_triple, sysroot), Ok); let target = target_result.unwrap_or_else(|e| { early_error( opts.error_format, diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 27653d3c331cb..72b2d089ebc3a 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -1791,11 +1791,8 @@ impl Target { // Additionally look in the sysroot under `lib/rustlib//target.json` // as a fallback. - let p = sysroot - .join("lib") - .join("rustlib") - .join(&target_triple) - .join("target.json"); + let p = + sysroot.join("lib").join("rustlib").join(&target_triple).join("target.json"); if p.is_file() { return load_file(&p); } From a8b49ff503d82171b480c9cf5a59fc47f5f6a351 Mon Sep 17 00:00:00 2001 From: Justus K Date: Sat, 8 May 2021 10:04:03 +0200 Subject: [PATCH 3/7] Minimize amount of fake `DefId`s used in rustdoc --- src/librustdoc/clean/mod.rs | 16 ++--- src/librustdoc/clean/types.rs | 8 +-- src/librustdoc/core.rs | 6 +- src/librustdoc/formats/cache.rs | 4 +- src/librustdoc/html/render/cache.rs | 8 +-- src/librustdoc/html/render/mod.rs | 8 +-- src/librustdoc/html/render/print_item.rs | 2 +- src/librustdoc/html/render/write_shared.rs | 2 - src/librustdoc/json/conversions.rs | 5 +- src/librustdoc/json/mod.rs | 15 ++--- .../passes/collect_intra_doc_links.rs | 63 +++++++------------ src/librustdoc/passes/collect_trait_impls.rs | 8 +-- 12 files changed, 55 insertions(+), 90 deletions(-) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 411cfab9f06a0..03578e396b5c1 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -533,8 +533,7 @@ impl Clean for hir::Generics<'_> { match param.kind { GenericParamDefKind::Lifetime => unreachable!(), GenericParamDefKind::Type { did, ref bounds, .. } => { - cx.impl_trait_bounds - .insert(FakeDefId::new_real(did).into(), bounds.clone()); + cx.impl_trait_bounds.insert(did.into(), bounds.clone()); } GenericParamDefKind::Const { .. } => unreachable!(), } @@ -615,7 +614,7 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, ty::GenericPredicates<'tcx .collect::>(); // param index -> [(DefId of trait, associated type name, type)] - let mut impl_trait_proj = FxHashMap::)>>::default(); + let mut impl_trait_proj = FxHashMap::)>>::default(); let where_predicates = preds .predicates @@ -687,13 +686,7 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, ty::GenericPredicates<'tcx if let Some(proj) = impl_trait_proj.remove(&idx) { for (trait_did, name, rhs) in proj { let rhs = rhs.clean(cx); - simplify::merge_bounds( - cx, - &mut bounds, - trait_did.expect_real(), - name, - &rhs, - ); + simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs); } } } else { @@ -1183,8 +1176,7 @@ fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type { if let Some(new_ty) = cx.ty_substs.get(&did).cloned() { return new_ty; } - if let Some(bounds) = cx.impl_trait_bounds.remove(&FakeDefId::new_real(did).into()) - { + if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) { return ImplTrait(bounds); } } diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 47dae63f1fdf7..c79ac96d9362b 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -73,10 +73,6 @@ impl FakeDefId { Self::Fake(DefIndex::from(id), krate) } - crate fn new_real(id: DefId) -> Self { - Self::Real(id) - } - #[inline] crate fn is_local(self) -> bool { match self { @@ -485,7 +481,7 @@ impl Item { .filter_map(|ItemLink { link: s, link_text, did, ref fragment }| { match did { Some(did) => { - if let Some((mut href, ..)) = href(did.expect_real(), cx) { + if let Some((mut href, ..)) = href(did.clone(), cx) { if let Some(ref fragment) = *fragment { href.push('#'); href.push_str(fragment); @@ -976,7 +972,7 @@ crate struct ItemLink { /// This may not be the same as `link` if there was a disambiguator /// in an intra-doc link (e.g. \[`fn@f`\]) pub(crate) link_text: String, - pub(crate) did: Option, + pub(crate) did: Option, /// The url fragment to append to the link pub(crate) fragment: Option, } diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 7b0c0b6699653..910a7d0f10f55 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -583,12 +583,12 @@ impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> { /// for `impl Trait` in argument position. #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] crate enum ImplTraitParam { - DefId(FakeDefId), + DefId(DefId), ParamIndex(u32), } -impl From for ImplTraitParam { - fn from(did: FakeDefId) -> Self { +impl From for ImplTraitParam { + fn from(did: DefId) -> Self { ImplTraitParam::DefId(did) } } diff --git a/src/librustdoc/formats/cache.rs b/src/librustdoc/formats/cache.rs index 50496f320096c..5734a4a98e2b5 100644 --- a/src/librustdoc/formats/cache.rs +++ b/src/librustdoc/formats/cache.rs @@ -67,7 +67,7 @@ crate struct Cache { /// When rendering traits, it's often useful to be able to list all /// implementors of the trait, and this mapping is exactly, that: a mapping /// of trait ids to the list of known implementors of the trait - crate implementors: FxHashMap>, + crate implementors: FxHashMap>, /// Cache of where external crate documentation can be found. crate extern_locations: FxHashMap, @@ -299,7 +299,7 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> { desc: item .doc_value() .map_or_else(String::new, |x| short_markdown_summary(&x.as_str())), - parent: parent.map(FakeDefId::new_real), + parent, parent_idx: None, search_type: get_index_search_type(&item, &self.empty_cache, self.tcx), aliases: item.attrs.get_doc_aliases(), diff --git a/src/librustdoc/html/render/cache.rs b/src/librustdoc/html/render/cache.rs index 57520a1a1fb46..3e056c4b67a70 100644 --- a/src/librustdoc/html/render/cache.rs +++ b/src/librustdoc/html/render/cache.rs @@ -7,7 +7,7 @@ use serde::ser::{Serialize, SerializeStruct, Serializer}; use crate::clean; use crate::clean::types::{ - FakeDefId, FnDecl, FnRetTy, GenericBound, Generics, GetDefId, Type, WherePredicate, + FnDecl, FnRetTy, GenericBound, Generics, GetDefId, Type, WherePredicate, }; use crate::formats::cache::Cache; use crate::formats::item_type::ItemType; @@ -82,7 +82,7 @@ crate fn build_index<'tcx>(krate: &clean::Crate, cache: &mut Cache, tcx: TyCtxt< defid_to_pathid.insert(defid, pathid); lastpathid += 1; - if let Some(&(ref fqp, short)) = paths.get(&defid.expect_real()) { + if let Some(&(ref fqp, short)) = paths.get(&defid) { crate_paths.push((short, fqp.last().unwrap().clone())); Some(pathid) } else { @@ -214,7 +214,7 @@ crate fn get_index_search_type<'tcx>( fn get_index_type(clean_type: &clean::Type, cache: &Cache) -> RenderType { RenderType { - ty: clean_type.def_id_full(cache).map(FakeDefId::new_real), + ty: clean_type.def_id_full(cache), idx: None, name: get_index_type_name(clean_type, true).map(|s| s.as_str().to_ascii_lowercase()), generics: get_generics(clean_type, cache), @@ -256,7 +256,7 @@ fn get_generics(clean_type: &clean::Type, cache: &Cache) -> Option> .filter_map(|t| { get_index_type_name(t, false).map(|name| Generic { name: name.as_str().to_ascii_lowercase(), - defid: t.def_id_full(cache).map(FakeDefId::new_real), + defid: t.def_id_full(cache), idx: None, }) }) diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index ea57831c0e5de..b29a9097a667a 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -87,7 +87,7 @@ crate struct IndexItem { crate name: String, crate path: String, crate desc: String, - crate parent: Option, + crate parent: Option, crate parent_idx: Option, crate search_type: Option, crate aliases: Box<[String]>, @@ -96,7 +96,7 @@ crate struct IndexItem { /// A type used for the search index. #[derive(Debug)] crate struct RenderType { - ty: Option, + ty: Option, idx: Option, name: Option, generics: Option>, @@ -128,7 +128,7 @@ impl Serialize for RenderType { #[derive(Debug)] crate struct Generic { name: String, - defid: Option, + defid: Option, idx: Option, } @@ -2118,7 +2118,7 @@ fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean "", ); - if let Some(implementors) = cx.cache.implementors.get(&it.def_id) { + if let Some(implementors) = cx.cache.implementors.get(&it.def_id.expect_real()) { let cache = cx.cache(); let mut res = implementors .iter() diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index 70b5458ece894..09cb55b91cabd 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -635,7 +635,7 @@ fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Tra // If there are methods directly on this trait object, render them here. render_assoc_items(w, cx, it, it.def_id.expect_real(), AssocItemRender::All); - if let Some(implementors) = cx.cache.implementors.get(&it.def_id) { + if let Some(implementors) = cx.cache.implementors.get(&it.def_id.expect_real()) { // The DefId is for the first Type found with that name. The bool is // if any Types with the same name but different DefId have been found. let mut implementor_dups: FxHashMap = FxHashMap::default(); diff --git a/src/librustdoc/html/render/write_shared.rs b/src/librustdoc/html/render/write_shared.rs index c493801d9907f..8c443d3771090 100644 --- a/src/librustdoc/html/render/write_shared.rs +++ b/src/librustdoc/html/render/write_shared.rs @@ -464,8 +464,6 @@ pub(super) fn write_shared( // Update the list of all implementors for traits let dst = cx.dst.join("implementors"); for (&did, imps) in &cx.cache.implementors { - let did = did.expect_real(); - // Private modules can leak through to this phase of rustdoc, which // could contain implementations for otherwise private types. In some // rare cases we could find an implementation for an item which wasn't diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index e3f1c6b1e2dc4..cf6f3e59bc9a8 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -14,9 +14,8 @@ use rustc_span::Pos; use rustdoc_json_types::*; -use crate::clean; use crate::clean::utils::print_const_expr; -use crate::clean::FakeDefId; +use crate::clean::{self, FakeDefId}; use crate::formats::item_type::ItemType; use crate::json::JsonRenderer; use std::collections::HashSet; @@ -31,7 +30,7 @@ impl JsonRenderer<'_> { .into_iter() .flatten() .filter_map(|clean::ItemLink { link, did, .. }| { - did.map(|did| (link.clone(), from_def_id(did))) + did.map(|did| (link.clone(), from_def_id(did.into()))) }) .collect(); let docs = item.attrs.collapsed_doc_value(); diff --git a/src/librustdoc/json/mod.rs b/src/librustdoc/json/mod.rs index d56acad60c00f..f8bd971081395 100644 --- a/src/librustdoc/json/mod.rs +++ b/src/librustdoc/json/mod.rs @@ -12,13 +12,14 @@ use std::path::PathBuf; use std::rc::Rc; use rustc_data_structures::fx::FxHashMap; +use rustc_hir::def_id::DefId; use rustc_middle::ty::TyCtxt; use rustc_session::Session; use rustdoc_json_types as types; use crate::clean; -use crate::clean::{ExternalCrate, FakeDefId}; +use crate::clean::ExternalCrate; use crate::config::RenderOptions; use crate::error::Error; use crate::formats::cache::Cache; @@ -42,7 +43,7 @@ impl JsonRenderer<'tcx> { self.tcx.sess } - fn get_trait_implementors(&mut self, id: FakeDefId) -> Vec { + fn get_trait_implementors(&mut self, id: DefId) -> Vec { Rc::clone(&self.cache) .implementors .get(&id) @@ -59,10 +60,10 @@ impl JsonRenderer<'tcx> { .unwrap_or_default() } - fn get_impls(&mut self, id: FakeDefId) -> Vec { + fn get_impls(&mut self, id: DefId) -> Vec { Rc::clone(&self.cache) .impls - .get(&id.expect_real()) + .get(&id) .map(|impls| { impls .iter() @@ -163,11 +164,11 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> { let id = item.def_id; if let Some(mut new_item) = self.convert_item(item) { if let types::ItemEnum::Trait(ref mut t) = new_item.inner { - t.implementors = self.get_trait_implementors(id) + t.implementors = self.get_trait_implementors(id.expect_real()) } else if let types::ItemEnum::Struct(ref mut s) = new_item.inner { - s.impls = self.get_impls(id) + s.impls = self.get_impls(id.expect_real()) } else if let types::ItemEnum::Enum(ref mut e) = new_item.inner { - e.impls = self.get_impls(id) + e.impls = self.get_impls(id.expect_real()) } let removed = self.index.borrow_mut().insert(from_def_id(id), new_item.clone()); diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 25b6c187f3b27..d136a7224a543 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -30,9 +30,7 @@ use std::convert::{TryFrom, TryInto}; use std::mem; use std::ops::Range; -use crate::clean::{ - self, utils::find_nearest_parent_module, Crate, FakeDefId, Item, ItemLink, PrimitiveType, -}; +use crate::clean::{self, utils::find_nearest_parent_module, Crate, Item, ItemLink, PrimitiveType}; use crate::core::DocContext; use crate::fold::DocFolder; use crate::html::markdown::{markdown_links, MarkdownLink}; @@ -248,7 +246,7 @@ enum AnchorFailure { #[derive(Clone, Debug, Hash, PartialEq, Eq)] struct ResolutionInfo { - module_id: FakeDefId, + module_id: DefId, dis: Option, path_str: String, extra_fragment: Option, @@ -274,7 +272,7 @@ struct LinkCollector<'a, 'tcx> { /// /// The last module will be used if the parent scope of the current item is /// unknown. - mod_ids: Vec, + mod_ids: Vec, /// This is used to store the kind of associated items, /// because `clean` and the disambiguator code expect them to be different. /// See the code for associated items on inherent impls for details. @@ -861,7 +859,7 @@ impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> { let inner_docs = item.inner_docs(self.cx.tcx); if item.is_mod() && inner_docs { - self.mod_ids.push(item.def_id); + self.mod_ids.push(item.def_id.expect_real()); } // We want to resolve in the lexical scope of the documentation. @@ -888,7 +886,7 @@ impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> { Some(if item.is_mod() { if !inner_docs { - self.mod_ids.push(item.def_id); + self.mod_ids.push(item.def_id.expect_real()); } let ret = self.fold_item_recur(item); @@ -1070,11 +1068,8 @@ impl LinkCollector<'_, '_> { // we've already pushed this node onto the resolution stack but // for outer comments we explicitly try and resolve against the // parent_node first. - let base_node = if item.is_mod() && inner_docs { - self.mod_ids.last().copied() - } else { - parent_node.map(|id| FakeDefId::new_real(id)) - }; + let base_node = + if item.is_mod() && inner_docs { self.mod_ids.last().copied() } else { parent_node }; let mut module_id = if let Some(id) = base_node { id @@ -1119,7 +1114,7 @@ impl LinkCollector<'_, '_> { resolved_self = format!("self::{}", &path_str["crate::".len()..]); path_str = &resolved_self; } - module_id = FakeDefId::new_real(DefId { krate, index: CRATE_DEF_INDEX }); + module_id = DefId { krate, index: CRATE_DEF_INDEX }; } let (mut res, mut fragment) = self.resolve_with_disambiguator_cached( @@ -1180,8 +1175,8 @@ impl LinkCollector<'_, '_> { report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, callback); }; - let verify = |kind: DefKind, id: FakeDefId| { - let (kind, id) = self.kind_side_channel.take().unwrap_or((kind, id.expect_real())); + let verify = |kind: DefKind, id: DefId| { + let (kind, id) = self.kind_side_channel.take().unwrap_or((kind, id)); debug!("intra-doc link to {} resolved to {:?} (id: {:?})", path_str, res, id); // Disallow e.g. linking to enums with `struct@` @@ -1341,7 +1336,7 @@ impl LinkCollector<'_, '_> { match disambiguator.map(Disambiguator::ns) { Some(expected_ns @ (ValueNS | TypeNS)) => { - match self.resolve(path_str, expected_ns, base_node.expect_real(), extra_fragment) { + match self.resolve(path_str, expected_ns, base_node, extra_fragment) { Ok(res) => Some(res), Err(ErrorKind::Resolve(box mut kind)) => { // We only looked in one namespace. Try to give a better error if possible. @@ -1350,12 +1345,9 @@ impl LinkCollector<'_, '_> { // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator` // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach for &new_ns in &[other_ns, MacroNS] { - if let Some(res) = self.check_full_res( - new_ns, - path_str, - base_node.expect_real(), - extra_fragment, - ) { + if let Some(res) = + self.check_full_res(new_ns, path_str, base_node, extra_fragment) + { kind = ResolutionFailure::WrongNamespace { res, expected_ns }; break; } @@ -1377,14 +1369,9 @@ impl LinkCollector<'_, '_> { // Try everything! let mut candidates = PerNS { macro_ns: self - .resolve_macro(path_str, base_node.expect_real()) + .resolve_macro(path_str, base_node) .map(|res| (res, extra_fragment.clone())), - type_ns: match self.resolve( - path_str, - TypeNS, - base_node.expect_real(), - extra_fragment, - ) { + type_ns: match self.resolve(path_str, TypeNS, base_node, extra_fragment) { Ok(res) => { debug!("got res in TypeNS: {:?}", res); Ok(res) @@ -1395,12 +1382,7 @@ impl LinkCollector<'_, '_> { } Err(ErrorKind::Resolve(box kind)) => Err(kind), }, - value_ns: match self.resolve( - path_str, - ValueNS, - base_node.expect_real(), - extra_fragment, - ) { + value_ns: match self.resolve(path_str, ValueNS, base_node, extra_fragment) { Ok(res) => Ok(res), Err(ErrorKind::AnchorFailure(msg)) => { anchor_failure(self.cx, diag, msg); @@ -1456,17 +1438,14 @@ impl LinkCollector<'_, '_> { } } Some(MacroNS) => { - match self.resolve_macro(path_str, base_node.expect_real()) { + match self.resolve_macro(path_str, base_node) { Ok(res) => Some((res, extra_fragment.clone())), Err(mut kind) => { // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible. for &ns in &[TypeNS, ValueNS] { - if let Some(res) = self.check_full_res( - ns, - path_str, - base_node.expect_real(), - extra_fragment, - ) { + if let Some(res) = + self.check_full_res(ns, path_str, base_node, extra_fragment) + { kind = ResolutionFailure::WrongNamespace { res, expected_ns: MacroNS }; break; diff --git a/src/librustdoc/passes/collect_trait_impls.rs b/src/librustdoc/passes/collect_trait_impls.rs index 90b797da24915..9b7e10b2688bb 100644 --- a/src/librustdoc/passes/collect_trait_impls.rs +++ b/src/librustdoc/passes/collect_trait_impls.rs @@ -126,7 +126,7 @@ crate fn collect_trait_impls(krate: Crate, cx: &mut DocContext<'_>) -> Crate { // Since only the `DefId` portion of the `Type` instances is known to be same for both the // `Deref` target type and the impl for type positions, this map of types is keyed by // `DefId` and for convenience uses a special cleaner that accepts `DefId`s directly. - if cleaner.keep_impl_with_def_id(&FakeDefId::new_real(*type_did)) { + if cleaner.keep_impl_with_def_id(FakeDefId::Real(*type_did)) { add_deref_target(&type_did_to_deref_target, &mut cleaner, type_did); } } @@ -206,13 +206,13 @@ impl BadImplStripper { } else if let Some(prim) = ty.primitive_type() { self.prims.contains(&prim) } else if let Some(did) = ty.def_id() { - self.keep_impl_with_def_id(&did.into()) + self.keep_impl_with_def_id(did.into()) } else { false } } - fn keep_impl_with_def_id(&self, did: &FakeDefId) -> bool { - self.items.contains(did) + fn keep_impl_with_def_id(&self, did: FakeDefId) -> bool { + self.items.contains(&did) } } From 89a67051a76f8511372d7b9f14610474b1dba6aa Mon Sep 17 00:00:00 2001 From: Charles Lew Date: Sat, 24 Apr 2021 13:16:34 +0800 Subject: [PATCH 4/7] Add primary marker on codegen unit to take charge of main_wrapper for non-local cases. --- compiler/rustc_codegen_ssa/src/base.rs | 17 +++-------------- compiler/rustc_middle/src/mir/mono.rs | 12 +++++++++++- .../src/monomorphize/partitioning/mod.rs | 6 ++++-- .../imported_main_from_extern_crate.rs | 6 ++---- .../imported_main_from_extern_crate.stderr | 10 ---------- 5 files changed, 20 insertions(+), 31 deletions(-) delete mode 100644 src/test/ui/entry-point/imported_main_from_extern_crate.stderr diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index e045a23eb0ce3..7a19b0e4d5ac3 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -357,20 +357,9 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) { return None; } - } else { - // FIXME: Add support for non-local main fn codegen - let span = cx.tcx().main_def.unwrap().span; - let n = 28937; - cx.sess() - .struct_span_err(span, "entry symbol `main` from foreign crate is not yet supported.") - .note(&format!( - "see issue #{} \ - for more information", - n, n, - )) - .emit(); - cx.sess().abort_if_errors(); - bug!(); + } else if !cx.codegen_unit().is_primary() { + // We want to create the wrapper only when the codegen unit is the primary one + return None; } let main_llfn = cx.get_fn_addr(instance); diff --git a/compiler/rustc_middle/src/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index 77f38e52ad2e4..67440e6e0edf0 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -229,6 +229,7 @@ pub struct CodegenUnit<'tcx> { name: Symbol, items: FxHashMap, (Linkage, Visibility)>, size_estimate: Option, + primary: bool, } /// Specifies the linkage type for a `MonoItem`. @@ -258,7 +259,7 @@ pub enum Visibility { impl<'tcx> CodegenUnit<'tcx> { pub fn new(name: Symbol) -> CodegenUnit<'tcx> { - CodegenUnit { name, items: Default::default(), size_estimate: None } + CodegenUnit { name, items: Default::default(), size_estimate: None, primary: false } } pub fn name(&self) -> Symbol { @@ -269,6 +270,14 @@ impl<'tcx> CodegenUnit<'tcx> { self.name = name; } + pub fn is_primary(&self) -> bool { + self.primary + } + + pub fn make_primary(&mut self) { + self.primary = true; + } + pub fn items(&self) -> &FxHashMap, (Linkage, Visibility)> { &self.items } @@ -378,6 +387,7 @@ impl<'a, 'tcx> HashStable> for CodegenUnit<'tcx> { name, // The size estimate is not relevant to the hash size_estimate: _, + primary: _, } = *self; name.hash_stable(hcx, hasher); diff --git a/compiler/rustc_mir/src/monomorphize/partitioning/mod.rs b/compiler/rustc_mir/src/monomorphize/partitioning/mod.rs index dc2379fd92b83..333cb30159093 100644 --- a/compiler/rustc_mir/src/monomorphize/partitioning/mod.rs +++ b/compiler/rustc_mir/src/monomorphize/partitioning/mod.rs @@ -350,12 +350,14 @@ fn collect_and_partition_mono_items<'tcx>( let (codegen_units, _) = tcx.sess.time("partition_and_assert_distinct_symbols", || { sync::join( || { - &*tcx.arena.alloc_from_iter(partition( + let mut codegen_units = partition( tcx, &mut items.iter().cloned(), tcx.sess.codegen_units(), &inlining_map, - )) + ); + codegen_units[0].make_primary(); + &*tcx.arena.alloc_from_iter(codegen_units) }, || assert_symbols_are_distinct(tcx, items.iter()), ) diff --git a/src/test/ui/entry-point/imported_main_from_extern_crate.rs b/src/test/ui/entry-point/imported_main_from_extern_crate.rs index 6bbf67fa5408d..4fddfc44ac60a 100644 --- a/src/test/ui/entry-point/imported_main_from_extern_crate.rs +++ b/src/test/ui/entry-point/imported_main_from_extern_crate.rs @@ -1,9 +1,7 @@ -// build-fail +// run-pass // aux-build:main_functions.rs #![feature(imported_main)] extern crate main_functions; -pub use main_functions::boilerplate as main; //~ ERROR entry symbol `main` from foreign crate - -// FIXME: Should be run-pass +pub use main_functions::boilerplate as main; diff --git a/src/test/ui/entry-point/imported_main_from_extern_crate.stderr b/src/test/ui/entry-point/imported_main_from_extern_crate.stderr deleted file mode 100644 index 8792e1e414244..0000000000000 --- a/src/test/ui/entry-point/imported_main_from_extern_crate.stderr +++ /dev/null @@ -1,10 +0,0 @@ -error: entry symbol `main` from foreign crate is not yet supported. - --> $DIR/imported_main_from_extern_crate.rs:7:9 - | -LL | pub use main_functions::boilerplate as main; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #28937 for more information - -error: aborting due to previous error - From fc544abe03f168c5fe26656aaa9bddaf5ac235e3 Mon Sep 17 00:00:00 2001 From: hi-rustin Date: Sun, 9 May 2021 12:24:58 +0800 Subject: [PATCH 5/7] Fix typo --- compiler/rustc_parse/src/parser/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index 74481e236f31c..0c0c3d0f47520 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -1077,7 +1077,7 @@ impl<'a> Parser<'a> { let span = expr.span; match &expr.kind { - // Not gated to supporte things like `doc = $expr` that work on stable. + // Not gated to support things like `doc = $expr` that work on stable. _ if is_interpolated_expr => {} ExprKind::Lit(lit) if lit.kind.is_unsuffixed() => {} _ => self.sess.gated_spans.gate(sym::extended_key_value_attributes, span), From bafc51e01aea45da746afaf51d5783f0409d605b Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Fri, 7 May 2021 18:56:16 +0200 Subject: [PATCH 6/7] remove const_fn feature gate --- compiler/rustc_feature/src/active.rs | 3 -- compiler/rustc_feature/src/removed.rs | 3 ++ library/std/src/lib.rs | 1 - .../src/language-features/const-fn.md | 10 ----- .../ui/feature-gates/feature-gate-const_fn.rs | 35 ---------------- .../feature-gate-const_fn.stderr | 21 ---------- .../feature-gate-rustc_const_unstable.rs | 2 - .../feature-gate-rustc_const_unstable.stderr | 2 +- .../ui/internal/internal-unstable-const.rs | 2 +- src/test/ui/issues/issue-54954.rs | 2 - src/test/ui/issues/issue-54954.stderr | 4 +- .../ui/mismatched_types/const-fn-in-trait.rs | 2 - .../mismatched_types/const-fn-in-trait.stderr | 4 +- src/test/ui/parser/fn-header-semantic-fail.rs | 1 - .../ui/parser/fn-header-semantic-fail.stderr | 40 +++++++++---------- .../caller-location-fnptr-rt-ctfe-equiv.rs | 2 +- .../const-caller-location.rs | 2 +- src/test/ui/rustc-args-required-const2.rs | 2 +- .../stability-attribute-sanity.rs | 2 +- src/test/ui/static/static-drop-scope.rs | 2 - src/test/ui/static/static-drop-scope.stderr | 20 +++++----- src/test/ui/thread-local-in-ctfe.rs | 2 +- .../auxiliary/thread-local-extern-static.rs | 2 +- src/test/ui/threads-sendsync/issue-43733.rs | 1 - .../ui/threads-sendsync/issue-43733.stderr | 4 +- src/test/ui/union/union-const-eval-field.rs | 2 - .../ui/unsafe/unsafe-unstable-const-fn.rs | 1 - .../ui/unsafe/unsafe-unstable-const-fn.stderr | 2 +- 28 files changed, 48 insertions(+), 128 deletions(-) delete mode 100644 src/doc/unstable-book/src/language-features/const-fn.md delete mode 100644 src/test/ui/feature-gates/feature-gate-const_fn.rs delete mode 100644 src/test/ui/feature-gates/feature-gate-const_fn.stderr diff --git a/compiler/rustc_feature/src/active.rs b/compiler/rustc_feature/src/active.rs index f747f8545145e..535cb13276646 100644 --- a/compiler/rustc_feature/src/active.rs +++ b/compiler/rustc_feature/src/active.rs @@ -274,9 +274,6 @@ declare_features! ( /// Allows using non lexical lifetimes (RFC 2094). (active, nll, "1.0.0", Some(43234), None), - /// Allows the definition of `const` functions with some advanced features. - (active, const_fn, "1.2.0", Some(57563), None), - /// Allows associated type defaults. (active, associated_type_defaults, "1.2.0", Some(29661), None), diff --git a/compiler/rustc_feature/src/removed.rs b/compiler/rustc_feature/src/removed.rs index fa8ef182aeddf..138398825af58 100644 --- a/compiler/rustc_feature/src/removed.rs +++ b/compiler/rustc_feature/src/removed.rs @@ -136,6 +136,9 @@ declare_features! ( (removed, main, "1.53.0", Some(29634), None, None), (removed, pub_macro_rules, "1.53.0", Some(78855), None, Some("removed due to being incomplete, in particular it does not work across crates")), + /// Allows the definition of `const` functions with some advanced features. + (removed, const_fn, "1.54.0", Some(57563), None, + Some("split into finer-grained feature gates")), // ------------------------------------------------------------------------- // feature-group-end: removed features diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 0ab9f490fd420..5f89ac059fd2d 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -246,7 +246,6 @@ #![feature(const_cstr_unchecked)] #![feature(const_fn_floating_point_arithmetic)] #![feature(const_fn_transmute)] -#![feature(const_fn)] #![feature(const_fn_fn_ptr_basics)] #![feature(const_io_structs)] #![feature(const_ip)] diff --git a/src/doc/unstable-book/src/language-features/const-fn.md b/src/doc/unstable-book/src/language-features/const-fn.md deleted file mode 100644 index bcf7f78b8fe0d..0000000000000 --- a/src/doc/unstable-book/src/language-features/const-fn.md +++ /dev/null @@ -1,10 +0,0 @@ -# `const_fn` - -The tracking issue for this feature is: [#57563] - -[#57563]: https://github.com/rust-lang/rust/issues/57563 - ------------------------- - -The `const_fn` feature enables additional functionality not stabilized in the -[minimal subset of `const_fn`](https://github.com/rust-lang/rust/issues/53555) diff --git a/src/test/ui/feature-gates/feature-gate-const_fn.rs b/src/test/ui/feature-gates/feature-gate-const_fn.rs deleted file mode 100644 index b97aa214f843a..0000000000000 --- a/src/test/ui/feature-gates/feature-gate-const_fn.rs +++ /dev/null @@ -1,35 +0,0 @@ -// Test use of advanced const fn without the `const_fn` feature gate. - -const fn foo() -> usize { 0 } // ok - -trait Foo { - const fn foo() -> u32; //~ ERROR functions in traits cannot be declared const - const fn bar() -> u32 { 0 } //~ ERROR functions in traits cannot be declared const -} - -impl Foo for u32 { - const fn foo() -> u32 { 0 } //~ ERROR functions in traits cannot be declared const -} - -trait Bar {} - -impl dyn Bar { - const fn baz() -> u32 { 0 } // ok -} - -static FOO: usize = foo(); -const BAR: usize = foo(); - -macro_rules! constant { - ($n:ident: $t:ty = $v:expr) => { - const $n: $t = $v; - } -} - -constant! { - BAZ: usize = foo() -} - -fn main() { - let x: [usize; foo()] = []; -} diff --git a/src/test/ui/feature-gates/feature-gate-const_fn.stderr b/src/test/ui/feature-gates/feature-gate-const_fn.stderr deleted file mode 100644 index 1e7fd669b1d48..0000000000000 --- a/src/test/ui/feature-gates/feature-gate-const_fn.stderr +++ /dev/null @@ -1,21 +0,0 @@ -error[E0379]: functions in traits cannot be declared const - --> $DIR/feature-gate-const_fn.rs:6:5 - | -LL | const fn foo() -> u32; - | ^^^^^ functions in traits cannot be const - -error[E0379]: functions in traits cannot be declared const - --> $DIR/feature-gate-const_fn.rs:7:5 - | -LL | const fn bar() -> u32 { 0 } - | ^^^^^ functions in traits cannot be const - -error[E0379]: functions in traits cannot be declared const - --> $DIR/feature-gate-const_fn.rs:11:5 - | -LL | const fn foo() -> u32 { 0 } - | ^^^^^ functions in traits cannot be const - -error: aborting due to 3 previous errors - -For more information about this error, try `rustc --explain E0379`. diff --git a/src/test/ui/feature-gates/feature-gate-rustc_const_unstable.rs b/src/test/ui/feature-gates/feature-gate-rustc_const_unstable.rs index 3296a17a0b7ef..d7daaaaa101e7 100644 --- a/src/test/ui/feature-gates/feature-gate-rustc_const_unstable.rs +++ b/src/test/ui/feature-gates/feature-gate-rustc_const_unstable.rs @@ -1,7 +1,5 @@ // Test internal const fn feature gate. -#![feature(const_fn)] - #[rustc_const_unstable(feature="fzzzzzt")] //~ stability attributes may not be used outside pub const fn bazinga() {} diff --git a/src/test/ui/feature-gates/feature-gate-rustc_const_unstable.stderr b/src/test/ui/feature-gates/feature-gate-rustc_const_unstable.stderr index 9df926dcf90f5..48493b786d649 100644 --- a/src/test/ui/feature-gates/feature-gate-rustc_const_unstable.stderr +++ b/src/test/ui/feature-gates/feature-gate-rustc_const_unstable.stderr @@ -1,5 +1,5 @@ error[E0734]: stability attributes may not be used outside of the standard library - --> $DIR/feature-gate-rustc_const_unstable.rs:5:1 + --> $DIR/feature-gate-rustc_const_unstable.rs:3:1 | LL | #[rustc_const_unstable(feature="fzzzzzt")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/test/ui/internal/internal-unstable-const.rs b/src/test/ui/internal/internal-unstable-const.rs index 554c67be4e0b0..470262a15ba0d 100644 --- a/src/test/ui/internal/internal-unstable-const.rs +++ b/src/test/ui/internal/internal-unstable-const.rs @@ -3,7 +3,7 @@ #![stable(feature = "rust1", since = "1.0.0")] #![feature(staged_api)] -#![feature(const_transmute, const_fn)] +#![feature(const_transmute)] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "rust1", since = "1.0.0")] diff --git a/src/test/ui/issues/issue-54954.rs b/src/test/ui/issues/issue-54954.rs index 00805eb5dc90d..42a4d5b674b22 100644 --- a/src/test/ui/issues/issue-54954.rs +++ b/src/test/ui/issues/issue-54954.rs @@ -1,5 +1,3 @@ -#![feature(const_fn)] - const ARR_LEN: usize = Tt::const_val::<[i8; 123]>(); //~^ ERROR type annotations needed diff --git a/src/test/ui/issues/issue-54954.stderr b/src/test/ui/issues/issue-54954.stderr index 29d439b457ff6..9de58d83c8b07 100644 --- a/src/test/ui/issues/issue-54954.stderr +++ b/src/test/ui/issues/issue-54954.stderr @@ -1,11 +1,11 @@ error[E0379]: functions in traits cannot be declared const - --> $DIR/issue-54954.rs:7:5 + --> $DIR/issue-54954.rs:5:5 | LL | const fn const_val() -> usize { | ^^^^^ functions in traits cannot be const error[E0283]: type annotations needed - --> $DIR/issue-54954.rs:3:24 + --> $DIR/issue-54954.rs:1:24 | LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type diff --git a/src/test/ui/mismatched_types/const-fn-in-trait.rs b/src/test/ui/mismatched_types/const-fn-in-trait.rs index 3b1992d90b7c5..e04d59c58c22b 100644 --- a/src/test/ui/mismatched_types/const-fn-in-trait.rs +++ b/src/test/ui/mismatched_types/const-fn-in-trait.rs @@ -1,5 +1,3 @@ -#![feature(const_fn)] - trait Foo { fn f() -> u32; const fn g(); //~ ERROR cannot be declared const diff --git a/src/test/ui/mismatched_types/const-fn-in-trait.stderr b/src/test/ui/mismatched_types/const-fn-in-trait.stderr index 450981a9183a2..7d1fbe45c5302 100644 --- a/src/test/ui/mismatched_types/const-fn-in-trait.stderr +++ b/src/test/ui/mismatched_types/const-fn-in-trait.stderr @@ -1,11 +1,11 @@ error[E0379]: functions in traits cannot be declared const - --> $DIR/const-fn-in-trait.rs:5:5 + --> $DIR/const-fn-in-trait.rs:3:5 | LL | const fn g(); | ^^^^^ functions in traits cannot be const error[E0379]: functions in traits cannot be declared const - --> $DIR/const-fn-in-trait.rs:9:5 + --> $DIR/const-fn-in-trait.rs:7:5 | LL | const fn f() -> u32 { 22 } | ^^^^^ functions in traits cannot be const diff --git a/src/test/ui/parser/fn-header-semantic-fail.rs b/src/test/ui/parser/fn-header-semantic-fail.rs index 0bbaeec0c7fec..91a63bafd99a9 100644 --- a/src/test/ui/parser/fn-header-semantic-fail.rs +++ b/src/test/ui/parser/fn-header-semantic-fail.rs @@ -3,7 +3,6 @@ // edition:2018 #![feature(const_extern_fn)] -#![feature(const_fn)] fn main() { async fn ff1() {} // OK. diff --git a/src/test/ui/parser/fn-header-semantic-fail.stderr b/src/test/ui/parser/fn-header-semantic-fail.stderr index 2e513415e6c64..b3f60b13b0f74 100644 --- a/src/test/ui/parser/fn-header-semantic-fail.stderr +++ b/src/test/ui/parser/fn-header-semantic-fail.stderr @@ -1,5 +1,5 @@ error: functions cannot be both `const` and `async` - --> $DIR/fn-header-semantic-fail.rs:13:5 + --> $DIR/fn-header-semantic-fail.rs:12:5 | LL | const async unsafe extern "C" fn ff5() {} // OK. | ^^^^^-^^^^^------------------------------ @@ -8,7 +8,7 @@ LL | const async unsafe extern "C" fn ff5() {} // OK. | `const` because of this error[E0706]: functions in traits cannot be declared `async` - --> $DIR/fn-header-semantic-fail.rs:17:9 + --> $DIR/fn-header-semantic-fail.rs:16:9 | LL | async fn ft1(); | -----^^^^^^^^^^ @@ -19,19 +19,19 @@ LL | async fn ft1(); = note: consider using the `async-trait` crate: https://crates.io/crates/async-trait error[E0379]: functions in traits cannot be declared const - --> $DIR/fn-header-semantic-fail.rs:19:9 + --> $DIR/fn-header-semantic-fail.rs:18:9 | LL | const fn ft3(); | ^^^^^ functions in traits cannot be const error[E0379]: functions in traits cannot be declared const - --> $DIR/fn-header-semantic-fail.rs:21:9 + --> $DIR/fn-header-semantic-fail.rs:20:9 | LL | const async unsafe extern "C" fn ft5(); | ^^^^^ functions in traits cannot be const error[E0706]: functions in traits cannot be declared `async` - --> $DIR/fn-header-semantic-fail.rs:21:9 + --> $DIR/fn-header-semantic-fail.rs:20:9 | LL | const async unsafe extern "C" fn ft5(); | ^^^^^^-----^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -42,7 +42,7 @@ LL | const async unsafe extern "C" fn ft5(); = note: consider using the `async-trait` crate: https://crates.io/crates/async-trait error: functions cannot be both `const` and `async` - --> $DIR/fn-header-semantic-fail.rs:21:9 + --> $DIR/fn-header-semantic-fail.rs:20:9 | LL | const async unsafe extern "C" fn ft5(); | ^^^^^-^^^^^---------------------------- @@ -51,7 +51,7 @@ LL | const async unsafe extern "C" fn ft5(); | `const` because of this error[E0706]: functions in traits cannot be declared `async` - --> $DIR/fn-header-semantic-fail.rs:29:9 + --> $DIR/fn-header-semantic-fail.rs:28:9 | LL | async fn ft1() {} | -----^^^^^^^^^^^^ @@ -62,19 +62,19 @@ LL | async fn ft1() {} = note: consider using the `async-trait` crate: https://crates.io/crates/async-trait error[E0379]: functions in traits cannot be declared const - --> $DIR/fn-header-semantic-fail.rs:32:9 + --> $DIR/fn-header-semantic-fail.rs:31:9 | LL | const fn ft3() {} | ^^^^^ functions in traits cannot be const error[E0379]: functions in traits cannot be declared const - --> $DIR/fn-header-semantic-fail.rs:34:9 + --> $DIR/fn-header-semantic-fail.rs:33:9 | LL | const async unsafe extern "C" fn ft5() {} | ^^^^^ functions in traits cannot be const error[E0706]: functions in traits cannot be declared `async` - --> $DIR/fn-header-semantic-fail.rs:34:9 + --> $DIR/fn-header-semantic-fail.rs:33:9 | LL | const async unsafe extern "C" fn ft5() {} | ^^^^^^-----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -85,7 +85,7 @@ LL | const async unsafe extern "C" fn ft5() {} = note: consider using the `async-trait` crate: https://crates.io/crates/async-trait error: functions cannot be both `const` and `async` - --> $DIR/fn-header-semantic-fail.rs:34:9 + --> $DIR/fn-header-semantic-fail.rs:33:9 | LL | const async unsafe extern "C" fn ft5() {} | ^^^^^-^^^^^------------------------------ @@ -94,7 +94,7 @@ LL | const async unsafe extern "C" fn ft5() {} | `const` because of this error: functions cannot be both `const` and `async` - --> $DIR/fn-header-semantic-fail.rs:46:9 + --> $DIR/fn-header-semantic-fail.rs:45:9 | LL | const async unsafe extern "C" fn fi5() {} | ^^^^^-^^^^^------------------------------ @@ -103,7 +103,7 @@ LL | const async unsafe extern "C" fn fi5() {} | `const` because of this error: functions in `extern` blocks cannot have qualifiers - --> $DIR/fn-header-semantic-fail.rs:51:18 + --> $DIR/fn-header-semantic-fail.rs:50:18 | LL | extern "C" { | ---------- in this `extern` block @@ -116,7 +116,7 @@ LL | fn fe1(); | ^^ error: functions in `extern` blocks cannot have qualifiers - --> $DIR/fn-header-semantic-fail.rs:52:19 + --> $DIR/fn-header-semantic-fail.rs:51:19 | LL | extern "C" { | ---------- in this `extern` block @@ -130,7 +130,7 @@ LL | fn fe2(); | ^^ error: functions in `extern` blocks cannot have qualifiers - --> $DIR/fn-header-semantic-fail.rs:53:18 + --> $DIR/fn-header-semantic-fail.rs:52:18 | LL | extern "C" { | ---------- in this `extern` block @@ -144,7 +144,7 @@ LL | fn fe3(); | ^^ error: functions in `extern` blocks cannot have qualifiers - --> $DIR/fn-header-semantic-fail.rs:54:23 + --> $DIR/fn-header-semantic-fail.rs:53:23 | LL | extern "C" { | ---------- in this `extern` block @@ -158,7 +158,7 @@ LL | fn fe4(); | ^^ error: functions in `extern` blocks cannot have qualifiers - --> $DIR/fn-header-semantic-fail.rs:55:42 + --> $DIR/fn-header-semantic-fail.rs:54:42 | LL | extern "C" { | ---------- in this `extern` block @@ -172,7 +172,7 @@ LL | fn fe5(); | ^^ error: functions cannot be both `const` and `async` - --> $DIR/fn-header-semantic-fail.rs:55:9 + --> $DIR/fn-header-semantic-fail.rs:54:9 | LL | const async unsafe extern "C" fn fe5(); | ^^^^^-^^^^^---------------------------- @@ -181,7 +181,7 @@ LL | const async unsafe extern "C" fn fe5(); | `const` because of this error[E0053]: method `ft1` has an incompatible type for trait - --> $DIR/fn-header-semantic-fail.rs:29:24 + --> $DIR/fn-header-semantic-fail.rs:28:24 | LL | async fn ft1(); | - type in trait @@ -197,7 +197,7 @@ LL | async fn ft1() {} found fn pointer `fn() -> impl Future` error[E0053]: method `ft5` has an incompatible type for trait - --> $DIR/fn-header-semantic-fail.rs:34:48 + --> $DIR/fn-header-semantic-fail.rs:33:48 | LL | const async unsafe extern "C" fn ft5(); | - type in trait diff --git a/src/test/ui/rfc-2091-track-caller/caller-location-fnptr-rt-ctfe-equiv.rs b/src/test/ui/rfc-2091-track-caller/caller-location-fnptr-rt-ctfe-equiv.rs index 05240908917bc..a3bed707eccda 100644 --- a/src/test/ui/rfc-2091-track-caller/caller-location-fnptr-rt-ctfe-equiv.rs +++ b/src/test/ui/rfc-2091-track-caller/caller-location-fnptr-rt-ctfe-equiv.rs @@ -6,7 +6,7 @@ // run-pass // compile-flags: -Z unleash-the-miri-inside-of-you -#![feature(core_intrinsics, const_caller_location, const_fn)] +#![feature(core_intrinsics, const_caller_location)] type L = &'static std::panic::Location<'static>; diff --git a/src/test/ui/rfc-2091-track-caller/const-caller-location.rs b/src/test/ui/rfc-2091-track-caller/const-caller-location.rs index 89b0b69f38dc0..6e15cf3fe8ad3 100644 --- a/src/test/ui/rfc-2091-track-caller/const-caller-location.rs +++ b/src/test/ui/rfc-2091-track-caller/const-caller-location.rs @@ -2,7 +2,7 @@ // revisions: default mir-opt //[mir-opt] compile-flags: -Zmir-opt-level=4 -#![feature(const_caller_location, const_fn)] +#![feature(const_caller_location)] use std::panic::Location; diff --git a/src/test/ui/rustc-args-required-const2.rs b/src/test/ui/rustc-args-required-const2.rs index 5feeca6f530e8..06457bc5ca65a 100644 --- a/src/test/ui/rustc-args-required-const2.rs +++ b/src/test/ui/rustc-args-required-const2.rs @@ -1,4 +1,4 @@ -#![feature(rustc_attrs, const_fn)] +#![feature(rustc_attrs)] #[rustc_args_required_const(0)] fn foo(_a: i32) { diff --git a/src/test/ui/stability-attribute/stability-attribute-sanity.rs b/src/test/ui/stability-attribute/stability-attribute-sanity.rs index 9f8ecc2628126..d7cb66d9c84ec 100644 --- a/src/test/ui/stability-attribute/stability-attribute-sanity.rs +++ b/src/test/ui/stability-attribute/stability-attribute-sanity.rs @@ -1,6 +1,6 @@ // Various checks that stability attributes are used correctly, per RFC 507 -#![feature(const_fn, staged_api)] +#![feature(staged_api)] #![stable(feature = "rust1", since = "1.0.0")] diff --git a/src/test/ui/static/static-drop-scope.rs b/src/test/ui/static/static-drop-scope.rs index 0de28d5469b38..e7ea8663d5af8 100644 --- a/src/test/ui/static/static-drop-scope.rs +++ b/src/test/ui/static/static-drop-scope.rs @@ -1,5 +1,3 @@ -#![feature(const_fn)] - struct WithDtor; impl Drop for WithDtor { diff --git a/src/test/ui/static/static-drop-scope.stderr b/src/test/ui/static/static-drop-scope.stderr index ed81734f6ebd7..ac32f217fd769 100644 --- a/src/test/ui/static/static-drop-scope.stderr +++ b/src/test/ui/static/static-drop-scope.stderr @@ -1,5 +1,5 @@ error[E0493]: destructors cannot be evaluated at compile-time - --> $DIR/static-drop-scope.rs:9:60 + --> $DIR/static-drop-scope.rs:7:60 | LL | static PROMOTION_FAIL_S: Option<&'static WithDtor> = Some(&WithDtor); | ^^^^^^^^- value is dropped here @@ -7,7 +7,7 @@ LL | static PROMOTION_FAIL_S: Option<&'static WithDtor> = Some(&WithDtor); | statics cannot evaluate destructors error[E0716]: temporary value dropped while borrowed - --> $DIR/static-drop-scope.rs:9:60 + --> $DIR/static-drop-scope.rs:7:60 | LL | static PROMOTION_FAIL_S: Option<&'static WithDtor> = Some(&WithDtor); | ------^^^^^^^^- @@ -17,7 +17,7 @@ LL | static PROMOTION_FAIL_S: Option<&'static WithDtor> = Some(&WithDtor); | using this value as a static requires that borrow lasts for `'static` error[E0493]: destructors cannot be evaluated at compile-time - --> $DIR/static-drop-scope.rs:13:59 + --> $DIR/static-drop-scope.rs:11:59 | LL | const PROMOTION_FAIL_C: Option<&'static WithDtor> = Some(&WithDtor); | ^^^^^^^^- value is dropped here @@ -25,7 +25,7 @@ LL | const PROMOTION_FAIL_C: Option<&'static WithDtor> = Some(&WithDtor); | constants cannot evaluate destructors error[E0716]: temporary value dropped while borrowed - --> $DIR/static-drop-scope.rs:13:59 + --> $DIR/static-drop-scope.rs:11:59 | LL | const PROMOTION_FAIL_C: Option<&'static WithDtor> = Some(&WithDtor); | ------^^^^^^^^- @@ -35,7 +35,7 @@ LL | const PROMOTION_FAIL_C: Option<&'static WithDtor> = Some(&WithDtor); | using this value as a constant requires that borrow lasts for `'static` error[E0493]: destructors cannot be evaluated at compile-time - --> $DIR/static-drop-scope.rs:17:28 + --> $DIR/static-drop-scope.rs:15:28 | LL | static EARLY_DROP_S: i32 = (WithDtor, 0).1; | ^^^^^^^^^^^^^ - value is dropped here @@ -43,7 +43,7 @@ LL | static EARLY_DROP_S: i32 = (WithDtor, 0).1; | statics cannot evaluate destructors error[E0493]: destructors cannot be evaluated at compile-time - --> $DIR/static-drop-scope.rs:20:27 + --> $DIR/static-drop-scope.rs:18:27 | LL | const EARLY_DROP_C: i32 = (WithDtor, 0).1; | ^^^^^^^^^^^^^ - value is dropped here @@ -51,7 +51,7 @@ LL | const EARLY_DROP_C: i32 = (WithDtor, 0).1; | constants cannot evaluate destructors error[E0493]: destructors cannot be evaluated at compile-time - --> $DIR/static-drop-scope.rs:23:24 + --> $DIR/static-drop-scope.rs:21:24 | LL | const fn const_drop(_: T) {} | ^ - value is dropped here @@ -59,7 +59,7 @@ LL | const fn const_drop(_: T) {} | constant functions cannot evaluate destructors error[E0493]: destructors cannot be evaluated at compile-time - --> $DIR/static-drop-scope.rs:27:5 + --> $DIR/static-drop-scope.rs:25:5 | LL | (x, ()).1 | ^^^^^^^ constant functions cannot evaluate destructors @@ -68,7 +68,7 @@ LL | } | - value is dropped here error[E0493]: destructors cannot be evaluated at compile-time - --> $DIR/static-drop-scope.rs:31:34 + --> $DIR/static-drop-scope.rs:29:34 | LL | const EARLY_DROP_C_OPTION: i32 = (Some(WithDtor), 0).1; | ^^^^^^^^^^^^^^^^^^^ - value is dropped here @@ -76,7 +76,7 @@ LL | const EARLY_DROP_C_OPTION: i32 = (Some(WithDtor), 0).1; | constants cannot evaluate destructors error[E0493]: destructors cannot be evaluated at compile-time - --> $DIR/static-drop-scope.rs:36:43 + --> $DIR/static-drop-scope.rs:34:43 | LL | const EARLY_DROP_C_OPTION_CONSTANT: i32 = (HELPER, 0).1; | ^^^^^^^^^^^ - value is dropped here diff --git a/src/test/ui/thread-local-in-ctfe.rs b/src/test/ui/thread-local-in-ctfe.rs index 313d39de36b6a..547e5445aa1b6 100644 --- a/src/test/ui/thread-local-in-ctfe.rs +++ b/src/test/ui/thread-local-in-ctfe.rs @@ -1,4 +1,4 @@ -#![feature(const_fn, thread_local)] +#![feature(thread_local)] #[thread_local] static A: u32 = 1; diff --git a/src/test/ui/threads-sendsync/auxiliary/thread-local-extern-static.rs b/src/test/ui/threads-sendsync/auxiliary/thread-local-extern-static.rs index b237b1c480e3a..4d3c4e8accd88 100644 --- a/src/test/ui/threads-sendsync/auxiliary/thread-local-extern-static.rs +++ b/src/test/ui/threads-sendsync/auxiliary/thread-local-extern-static.rs @@ -1,4 +1,4 @@ -#![feature(cfg_target_thread_local, const_fn, thread_local)] +#![feature(cfg_target_thread_local, thread_local)] #![crate_type = "lib"] #[cfg(target_thread_local)] diff --git a/src/test/ui/threads-sendsync/issue-43733.rs b/src/test/ui/threads-sendsync/issue-43733.rs index a602d7667c48d..4d81d0a5d2093 100644 --- a/src/test/ui/threads-sendsync/issue-43733.rs +++ b/src/test/ui/threads-sendsync/issue-43733.rs @@ -1,4 +1,3 @@ -#![feature(const_fn)] #![feature(thread_local)] #![feature(cfg_target_thread_local, thread_local_internals)] diff --git a/src/test/ui/threads-sendsync/issue-43733.stderr b/src/test/ui/threads-sendsync/issue-43733.stderr index ee6a3b065d6ee..c7b12a395a253 100644 --- a/src/test/ui/threads-sendsync/issue-43733.stderr +++ b/src/test/ui/threads-sendsync/issue-43733.stderr @@ -1,5 +1,5 @@ error[E0133]: call to unsafe function is unsafe and requires unsafe function or block - --> $DIR/issue-43733.rs:18:5 + --> $DIR/issue-43733.rs:17:5 | LL | __KEY.get(Default::default) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ call to unsafe function @@ -7,7 +7,7 @@ LL | __KEY.get(Default::default) = note: consult the function's documentation for information on how to avoid undefined behavior error[E0133]: call to unsafe function is unsafe and requires unsafe function or block - --> $DIR/issue-43733.rs:22:5 + --> $DIR/issue-43733.rs:21:5 | LL | std::thread::LocalKey::new(__getit); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ call to unsafe function diff --git a/src/test/ui/union/union-const-eval-field.rs b/src/test/ui/union/union-const-eval-field.rs index 3b40a21d80d48..15a20899a78d1 100644 --- a/src/test/ui/union/union-const-eval-field.rs +++ b/src/test/ui/union/union-const-eval-field.rs @@ -1,7 +1,5 @@ // run-pass -#![feature(const_fn)] - type Field1 = (i32, u32); type Field2 = f32; type Field3 = i64; diff --git a/src/test/ui/unsafe/unsafe-unstable-const-fn.rs b/src/test/ui/unsafe/unsafe-unstable-const-fn.rs index 963d892931a75..c7120e0500725 100644 --- a/src/test/ui/unsafe/unsafe-unstable-const-fn.rs +++ b/src/test/ui/unsafe/unsafe-unstable-const-fn.rs @@ -1,7 +1,6 @@ #![stable(feature = "foo", since = "1.33.0")] #![feature(staged_api)] #![feature(const_raw_ptr_deref)] -#![feature(const_fn)] #[stable(feature = "foo", since = "1.33.0")] #[rustc_const_unstable(feature = "const_foo", issue = "none")] diff --git a/src/test/ui/unsafe/unsafe-unstable-const-fn.stderr b/src/test/ui/unsafe/unsafe-unstable-const-fn.stderr index 98d7ae9f85434..410d8d3fb4024 100644 --- a/src/test/ui/unsafe/unsafe-unstable-const-fn.stderr +++ b/src/test/ui/unsafe/unsafe-unstable-const-fn.stderr @@ -1,5 +1,5 @@ error[E0133]: dereference of raw pointer is unsafe and requires unsafe function or block - --> $DIR/unsafe-unstable-const-fn.rs:9:5 + --> $DIR/unsafe-unstable-const-fn.rs:8:5 | LL | *a == b | ^^ dereference of raw pointer From 8f14592aa268a2712f7e229a792c92efcf5b1a85 Mon Sep 17 00:00:00 2001 From: Paul Trojahn Date: Fri, 7 May 2021 19:09:15 +0200 Subject: [PATCH 7/7] Improve "panic message is not a string literal" warning This warning always referenced panic! even in case of an assert. Related to #84656 --- compiler/rustc_lint/src/non_fmt_panic.rs | 17 ++++++++----- src/test/ui/non-fmt-panic.rs | 2 ++ src/test/ui/non-fmt-panic.stderr | 32 +++++++++++++++++++++--- 3 files changed, 42 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_lint/src/non_fmt_panic.rs b/compiler/rustc_lint/src/non_fmt_panic.rs index 5a27135581747..070bc3522a453 100644 --- a/compiler/rustc_lint/src/non_fmt_panic.rs +++ b/compiler/rustc_lint/src/non_fmt_panic.rs @@ -4,7 +4,7 @@ use rustc_errors::{pluralize, Applicability}; use rustc_hir as hir; use rustc_middle::ty; use rustc_parse_format::{ParseMode, Parser, Piece}; -use rustc_span::{sym, symbol::kw, InnerSpan, Span, Symbol}; +use rustc_span::{hygiene, sym, symbol::kw, symbol::SymbolStr, InnerSpan, Span, Symbol}; declare_lint! { /// The `non_fmt_panic` lint detects `panic!(..)` invocations where the first @@ -67,7 +67,7 @@ fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tc // The argument is *not* a string literal. - let (span, panic) = panic_call(cx, f); + let (span, panic, symbol_str) = panic_call(cx, f); // Find the span of the argument to `panic!()`, before expansion in the // case of `panic!(some_macro!())`. @@ -95,7 +95,7 @@ fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tc } if arg_macro.map_or(false, |id| cx.tcx.is_diagnostic_item(sym::format_macro, id)) { // A case of `panic!(format!(..))`. - l.note("the panic!() macro supports formatting, so there's no need for the format!() macro here"); + l.note(format!("the {}!() macro supports formatting, so there's no need for the format!() macro here", symbol_str).as_str()); if let Some((open, close, _)) = find_delimiters(cx, arg_span) { l.multipart_suggestion( "remove the `format!(..)` macro call", @@ -160,7 +160,7 @@ fn check_panic_str<'tcx>( Parser::new(fmt.as_ref(), style, snippet.clone(), false, ParseMode::Format); let n_arguments = (&mut fmt_parser).filter(|a| matches!(a, Piece::NextArgument(_))).count(); - let (span, _) = panic_call(cx, f); + let (span, _, _) = panic_call(cx, f); if n_arguments > 0 && fmt_parser.errors.is_empty() { let arg_spans: Vec<_> = match &fmt_parser.arg_places[..] { @@ -230,7 +230,7 @@ fn find_delimiters<'tcx>(cx: &LateContext<'tcx>, span: Span) -> Option<(Span, Sp )) } -fn panic_call<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>) -> (Span, Symbol) { +fn panic_call<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>) -> (Span, Symbol, SymbolStr) { let mut expn = f.span.ctxt().outer_expn_data(); let mut panic_macro = kw::Empty; @@ -248,5 +248,10 @@ fn panic_call<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>) -> (Span, } } - (expn.call_site, panic_macro) + let macro_symbol = if let hygiene::ExpnKind::Macro(_, symbol) = expn.kind { + symbol + } else { + Symbol::intern("panic") + }; + (expn.call_site, panic_macro, macro_symbol.as_str()) } diff --git a/src/test/ui/non-fmt-panic.rs b/src/test/ui/non-fmt-panic.rs index c80a90b3eaaac..77390aae2d688 100644 --- a/src/test/ui/non-fmt-panic.rs +++ b/src/test/ui/non-fmt-panic.rs @@ -36,6 +36,8 @@ fn main() { panic!(a!()); //~ WARN panic message is not a string literal panic!(format!("{}", 1)); //~ WARN panic message is not a string literal + assert!(false, format!("{}", 1)); //~ WARN panic message is not a string literal + debug_assert!(false, format!("{}", 1)); //~ WARN panic message is not a string literal panic![123]; //~ WARN panic message is not a string literal panic!{123}; //~ WARN panic message is not a string literal diff --git a/src/test/ui/non-fmt-panic.stderr b/src/test/ui/non-fmt-panic.stderr index 7a333b3e76abe..3278eb5f0238e 100644 --- a/src/test/ui/non-fmt-panic.stderr +++ b/src/test/ui/non-fmt-panic.stderr @@ -213,7 +213,33 @@ LL | panic!("{}", 1); | -- -- warning: panic message is not a string literal - --> $DIR/non-fmt-panic.rs:40:12 + --> $DIR/non-fmt-panic.rs:39:20 + | +LL | assert!(false, format!("{}", 1)); + | ^^^^^^^^^^^^^^^^ + | + = note: this is no longer accepted in Rust 2021 + = note: the assert!() macro supports formatting, so there's no need for the format!() macro here +help: remove the `format!(..)` macro call + | +LL | assert!(false, "{}", 1); + | -- -- + +warning: panic message is not a string literal + --> $DIR/non-fmt-panic.rs:40:26 + | +LL | debug_assert!(false, format!("{}", 1)); + | ^^^^^^^^^^^^^^^^ + | + = note: this is no longer accepted in Rust 2021 + = note: the debug_assert!() macro supports formatting, so there's no need for the format!() macro here +help: remove the `format!(..)` macro call + | +LL | debug_assert!(false, "{}", 1); + | -- -- + +warning: panic message is not a string literal + --> $DIR/non-fmt-panic.rs:42:12 | LL | panic![123]; | ^^^ @@ -229,7 +255,7 @@ LL | std::panic::panic_any(123); | ^^^^^^^^^^^^^^^^^^^^^^ ^ warning: panic message is not a string literal - --> $DIR/non-fmt-panic.rs:41:12 + --> $DIR/non-fmt-panic.rs:43:12 | LL | panic!{123}; | ^^^ @@ -244,5 +270,5 @@ help: or use std::panic::panic_any instead LL | std::panic::panic_any(123); | ^^^^^^^^^^^^^^^^^^^^^^ ^ -warning: 18 warnings emitted +warning: 20 warnings emitted