From 50e2509a6c97c338919625aebf365473fcc84738 Mon Sep 17 00:00:00 2001 From: Jon Gjengset Date: Fri, 3 Feb 2023 17:59:48 -0800 Subject: [PATCH 1/9] Bump rust-installer Makes generation of `manifest.in` deterministic: https://github.com/rust-lang/rust-installer/pull/120 --- src/tools/rust-installer | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rust-installer b/src/tools/rust-installer index 5b2eee7eed72b..9981e4d1ea6ac 160000 --- a/src/tools/rust-installer +++ b/src/tools/rust-installer @@ -1 +1 @@ -Subproject commit 5b2eee7eed72b4894909c5eecbf014ea0b5ad995 +Subproject commit 9981e4d1ea6ac0992ff21be5514d4230dc77548b From 94f67e0c868967c920a31d95d7a17b3eff58285b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20K=C3=A5re=20Alsaker?= Date: Tue, 7 Feb 2023 12:23:31 +0100 Subject: [PATCH 2/9] Change `arena_cache` to not alter the declared query result --- compiler/rustc_middle/src/query/mod.rs | 111 +++++++++++++------------ compiler/rustc_middle/src/ty/query.rs | 39 +++++---- 2 files changed, 79 insertions(+), 71 deletions(-) diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 4cebe416354a9..0848bc6b6a7ce 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -54,14 +54,14 @@ rustc_queries! { /// This is because the `hir_crate` query gives you access to all other items. /// To avoid this fate, do not call `tcx.hir().krate()`; instead, /// prefer wrappers like `tcx.visit_all_items_in_krate()`. - query hir_crate(key: ()) -> Crate<'tcx> { + query hir_crate(key: ()) -> &'tcx Crate<'tcx> { arena_cache eval_always desc { "getting the crate HIR" } } /// All items in the crate. - query hir_crate_items(_: ()) -> rustc_middle::hir::ModuleItems { + query hir_crate_items(_: ()) -> &'tcx rustc_middle::hir::ModuleItems { arena_cache eval_always desc { "getting HIR crate items" } @@ -71,7 +71,7 @@ rustc_queries! { /// /// This can be conveniently accessed by `tcx.hir().visit_item_likes_in_module`. /// Avoid calling this query directly. - query hir_module_items(key: LocalDefId) -> rustc_middle::hir::ModuleItems { + query hir_module_items(key: LocalDefId) -> &'tcx rustc_middle::hir::ModuleItems { arena_cache desc { |tcx| "getting HIR module items in `{}`", tcx.def_path_str(key.to_def_id()) } cache_on_disk_if { true } @@ -183,7 +183,7 @@ rustc_queries! { separate_provide_extern } - query unsizing_params_for_adt(key: DefId) -> rustc_index::bit_set::BitSet + query unsizing_params_for_adt(key: DefId) -> &'tcx rustc_index::bit_set::BitSet { arena_cache desc { |tcx| @@ -218,7 +218,7 @@ rustc_queries! { /// Maps from the `DefId` of an item (trait/struct/enum/fn) to its /// associated generics. - query generics_of(key: DefId) -> ty::Generics { + query generics_of(key: DefId) -> &'tcx ty::Generics { desc { |tcx| "computing generics of `{}`", tcx.def_path_str(key) } arena_cache cache_on_disk_if { key.is_local() } @@ -295,19 +295,19 @@ rustc_queries! { /// These are assembled from the following places: /// - `extern` blocks (depending on their `link` attributes) /// - the `libs` (`-l`) option - query native_libraries(_: CrateNum) -> Vec { + query native_libraries(_: CrateNum) -> &'tcx Vec { arena_cache desc { "looking up the native libraries of a linked crate" } separate_provide_extern } - query shallow_lint_levels_on(key: hir::OwnerId) -> rustc_middle::lint::ShallowLintLevelMap { + query shallow_lint_levels_on(key: hir::OwnerId) -> &'tcx rustc_middle::lint::ShallowLintLevelMap { eval_always // fetches `resolutions` arena_cache desc { |tcx| "looking up lint levels for `{}`", tcx.def_path_str(key.to_def_id()) } } - query lint_expectations(_: ()) -> Vec<(LintExpectationId, LintExpectation)> { + query lint_expectations(_: ()) -> &'tcx Vec<(LintExpectationId, LintExpectation)> { arena_cache desc { "computing `#[expect]`ed lints in this crate" } } @@ -347,7 +347,7 @@ rustc_queries! { } /// Set of param indexes for type params that are in the type's representation - query params_in_repr(key: DefId) -> rustc_index::bit_set::BitSet { + query params_in_repr(key: DefId) -> &'tcx rustc_index::bit_set::BitSet { desc { "finding type parameters in the representation" } arena_cache no_hash @@ -364,14 +364,14 @@ rustc_queries! { } /// Create a THIR tree for debugging. - query thir_tree(key: ty::WithOptConstParam) -> String { + query thir_tree(key: ty::WithOptConstParam) -> &'tcx String { no_hash arena_cache desc { |tcx| "constructing THIR tree for `{}`", tcx.def_path_str(key.did.to_def_id()) } } /// Create a list-like THIR representation for debugging. - query thir_flat(key: ty::WithOptConstParam) -> String { + query thir_flat(key: ty::WithOptConstParam) -> &'tcx String { no_hash arena_cache desc { |tcx| "constructing flat THIR representation for `{}`", tcx.def_path_str(key.did.to_def_id()) } @@ -380,7 +380,7 @@ rustc_queries! { /// Set of all the `DefId`s in this crate that have MIR associated with /// them. This includes all the body owners, but also things like struct /// constructors. - query mir_keys(_: ()) -> rustc_data_structures::fx::FxIndexSet { + query mir_keys(_: ()) -> &'tcx rustc_data_structures::fx::FxIndexSet { arena_cache desc { "getting a list of all mir_keys" } } @@ -478,7 +478,7 @@ rustc_queries! { query symbols_for_closure_captures( key: (LocalDefId, LocalDefId) - ) -> Vec { + ) -> &'tcx Vec { arena_cache desc { |tcx| "finding symbols for captures of closure `{}` in `{}`", @@ -487,7 +487,7 @@ rustc_queries! { } } - query mir_generator_witnesses(key: DefId) -> mir::GeneratorLayout<'tcx> { + query mir_generator_witnesses(key: DefId) -> &'tcx mir::GeneratorLayout<'tcx> { arena_cache desc { |tcx| "generator witness types for `{}`", tcx.def_path_str(key) } cache_on_disk_if { key.is_local() } @@ -508,14 +508,14 @@ rustc_queries! { /// Returns coverage summary info for a function, after executing the `InstrumentCoverage` /// MIR pass (assuming the -Cinstrument-coverage option is enabled). - query coverageinfo(key: ty::InstanceDef<'tcx>) -> mir::CoverageInfo { + query coverageinfo(key: ty::InstanceDef<'tcx>) -> &'tcx mir::CoverageInfo { desc { |tcx| "retrieving coverage info from MIR for `{}`", tcx.def_path_str(key.def_id()) } arena_cache } /// Returns the `CodeRegions` for a function that has instrumented coverage, in case the /// function was optimized out before codegen, and before being added to the Coverage Map. - query covered_code_regions(key: DefId) -> Vec<&'tcx mir::coverage::CodeRegion> { + query covered_code_regions(key: DefId) -> &'tcx Vec<&'tcx mir::coverage::CodeRegion> { desc { |tcx| "retrieving the covered `CodeRegion`s, if instrumented, for `{}`", tcx.def_path_str(key) @@ -557,7 +557,7 @@ rustc_queries! { desc { "erasing regions from `{}`", ty } } - query wasm_import_module_map(_: CrateNum) -> FxHashMap { + query wasm_import_module_map(_: CrateNum) -> &'tcx FxHashMap { arena_cache desc { "getting wasm import module map" } } @@ -632,7 +632,7 @@ rustc_queries! { desc { |tcx| "computing the bounds for type parameter `{}`", tcx.hir().ty_param_name(key.1) } } - query trait_def(key: DefId) -> ty::TraitDef { + query trait_def(key: DefId) -> &'tcx ty::TraitDef { desc { |tcx| "computing trait definition for `{}`", tcx.def_path_str(key) } arena_cache cache_on_disk_if { key.is_local() } @@ -703,7 +703,7 @@ rustc_queries! { } /// Gets a map with the variance of every item; use `item_variance` instead. - query crate_variances(_: ()) -> ty::CrateVariancesMap<'tcx> { + query crate_variances(_: ()) -> &'tcx ty::CrateVariancesMap<'tcx> { arena_cache desc { "computing the variances for items in this crate" } } @@ -716,7 +716,7 @@ rustc_queries! { } /// Maps from thee `DefId` of a type to its (inferred) outlives. - query inferred_outlives_crate(_: ()) -> ty::CratePredicatesMap<'tcx> { + query inferred_outlives_crate(_: ()) -> &'tcx ty::CratePredicatesMap<'tcx> { arena_cache desc { "computing the inferred outlives predicates for items in this crate" } } @@ -729,7 +729,7 @@ rustc_queries! { } /// Maps from a trait item to the trait item "descriptor". - query associated_item(key: DefId) -> ty::AssocItem { + query associated_item(key: DefId) -> &'tcx ty::AssocItem { desc { |tcx| "computing associated item data for `{}`", tcx.def_path_str(key) } arena_cache cache_on_disk_if { key.is_local() } @@ -737,7 +737,7 @@ rustc_queries! { } /// Collects the associated items defined on a trait or impl. - query associated_items(key: DefId) -> ty::AssocItems<'tcx> { + query associated_items(key: DefId) -> &'tcx ty::AssocItems<'tcx> { arena_cache desc { |tcx| "collecting associated items of `{}`", tcx.def_path_str(key) } } @@ -763,7 +763,7 @@ rustc_queries! { /// /// The map returned for `tcx.impl_item_implementor_ids(impl_id)` would be ///`{ trait_f: impl_f, trait_g: impl_g }` - query impl_item_implementor_ids(impl_id: DefId) -> FxHashMap { + query impl_item_implementor_ids(impl_id: DefId) -> &'tcx FxHashMap { arena_cache desc { |tcx| "comparing impl items against trait for `{}`", tcx.def_path_str(impl_id) } } @@ -884,7 +884,7 @@ rustc_queries! { /// /// The second return value maps from ADTs to ignored derived traits (e.g. Debug and Clone) and /// their respective impl (i.e., part of the derive macro) - query live_symbols_and_ignored_derived_traits(_: ()) -> ( + query live_symbols_and_ignored_derived_traits(_: ()) -> &'tcx ( FxHashSet, FxHashMap> ) { @@ -964,7 +964,7 @@ rustc_queries! { /// Gets a complete map from all types to their inherent impls. /// Not meant to be used directly outside of coherence. - query crate_inherent_impls(k: ()) -> CrateInherentImpls { + query crate_inherent_impls(k: ()) -> &'tcx CrateInherentImpls { arena_cache desc { "finding all inherent impls defined in crate" } } @@ -1099,7 +1099,7 @@ rustc_queries! { desc { "checking for private elements in public interfaces" } } - query reachable_set(_: ()) -> FxHashSet { + query reachable_set(_: ()) -> &'tcx FxHashSet { arena_cache desc { "reachability" } } @@ -1111,7 +1111,7 @@ rustc_queries! { } /// Generates a MIR body for the shim. - query mir_shims(key: ty::InstanceDef<'tcx>) -> mir::Body<'tcx> { + query mir_shims(key: ty::InstanceDef<'tcx>) -> &'tcx mir::Body<'tcx> { arena_cache desc { |tcx| "generating MIR shim for `{}`", tcx.def_path_str(key.def_id()) } } @@ -1191,7 +1191,7 @@ rustc_queries! { separate_provide_extern } - query codegen_fn_attrs(def_id: DefId) -> CodegenFnAttrs { + query codegen_fn_attrs(def_id: DefId) -> &'tcx CodegenFnAttrs { desc { |tcx| "computing codegen attributes of `{}`", tcx.def_path_str(def_id) } arena_cache cache_on_disk_if { def_id.is_local() } @@ -1209,7 +1209,7 @@ rustc_queries! { } /// Gets the rendered value of the specified constant or associated constant. /// Used by rustdoc. - query rendered_const(def_id: DefId) -> String { + query rendered_const(def_id: DefId) -> &'tcx String { arena_cache desc { |tcx| "rendering constant initializer of `{}`", tcx.def_path_str(def_id) } cache_on_disk_if { def_id.is_local() } @@ -1268,12 +1268,12 @@ rustc_queries! { } /// Given a trait `trait_id`, return all known `impl` blocks. - query trait_impls_of(trait_id: DefId) -> ty::trait_def::TraitImpls { + query trait_impls_of(trait_id: DefId) -> &'tcx ty::trait_def::TraitImpls { arena_cache desc { |tcx| "finding trait impls of `{}`", tcx.def_path_str(trait_id) } } - query specialization_graph_of(trait_id: DefId) -> specialization_graph::Graph { + query specialization_graph_of(trait_id: DefId) -> &'tcx specialization_graph::Graph { arena_cache desc { |tcx| "building specialization graph of trait `{}`", tcx.def_path_str(trait_id) } cache_on_disk_if { true } @@ -1403,7 +1403,7 @@ rustc_queries! { separate_provide_extern } - query dependency_formats(_: ()) -> Lrc { + query dependency_formats(_: ()) -> &'tcx Lrc { arena_cache desc { "getting the linkage format of all dependencies" } } @@ -1503,7 +1503,7 @@ rustc_queries! { // Does not include external symbols that don't have a corresponding DefId, // like the compiler-generated `main` function and so on. query reachable_non_generics(_: CrateNum) - -> DefIdMap { + -> &'tcx DefIdMap { arena_cache desc { "looking up the exported symbols of a crate" } separate_provide_extern @@ -1526,7 +1526,7 @@ rustc_queries! { /// added or removed in any upstream crate. Instead use the narrower /// `upstream_monomorphizations_for`, `upstream_drop_glue_for`, or, even /// better, `Instance::upstream_monomorphization()`. - query upstream_monomorphizations(_: ()) -> DefIdMap, CrateNum>> { + query upstream_monomorphizations(_: ()) -> &'tcx DefIdMap, CrateNum>> { arena_cache desc { "collecting available upstream monomorphizations" } } @@ -1539,7 +1539,7 @@ rustc_queries! { /// You likely want to call `Instance::upstream_monomorphization()` /// instead of invoking this query directly. query upstream_monomorphizations_for(def_id: DefId) - -> Option<&'tcx FxHashMap, CrateNum>> + -> &'tcx Option<&'tcx FxHashMap, CrateNum>> { arena_cache desc { |tcx| @@ -1569,7 +1569,7 @@ rustc_queries! { } /// Returns a list of all `extern` blocks of a crate. - query foreign_modules(_: CrateNum) -> FxHashMap { + query foreign_modules(_: CrateNum) -> &'tcx FxHashMap { arena_cache desc { "looking up the foreign modules of a linked crate" } separate_provide_extern @@ -1603,7 +1603,7 @@ rustc_queries! { /// Gets the extra data to put in each output filename for a crate. /// For example, compiling the `foo` crate with `extra-filename=-a` creates a `libfoo-b.rlib` file. - query extra_filename(_: CrateNum) -> String { + query extra_filename(_: CrateNum) -> &'tcx String { arena_cache eval_always desc { "looking up the extra filename for a crate" } @@ -1611,7 +1611,7 @@ rustc_queries! { } /// Gets the paths where the crate came from in the file system. - query crate_extern_paths(_: CrateNum) -> Vec { + query crate_extern_paths(_: CrateNum) -> &'tcx Vec { arena_cache eval_always desc { "looking up the paths for extern crates" } @@ -1642,7 +1642,7 @@ rustc_queries! { /// Does lifetime resolution on items. Importantly, we can't resolve /// lifetimes directly on things like trait methods, because of trait params. /// See `rustc_resolve::late::lifetimes for details. - query resolve_lifetimes(_: hir::OwnerId) -> ResolveLifetimes { + query resolve_lifetimes(_: hir::OwnerId) -> &'tcx ResolveLifetimes { arena_cache desc { "resolving lifetimes" } } @@ -1713,7 +1713,7 @@ rustc_queries! { desc { |tcx| "computing crate imported by `{}`", tcx.def_path_str(def_id.to_def_id()) } } - query lib_features(_: ()) -> LibFeatures { + query lib_features(_: ()) -> &'tcx LibFeatures { arena_cache desc { "calculating the lib features map" } } @@ -1721,7 +1721,7 @@ rustc_queries! { desc { "calculating the lib features defined in a crate" } separate_provide_extern } - query stability_implications(_: CrateNum) -> FxHashMap { + query stability_implications(_: CrateNum) -> &'tcx FxHashMap { arena_cache desc { "calculating the implications between `#[unstable]` features defined in a crate" } separate_provide_extern @@ -1732,14 +1732,14 @@ rustc_queries! { separate_provide_extern } /// Returns the lang items defined in another crate by loading it from metadata. - query get_lang_items(_: ()) -> LanguageItems { + query get_lang_items(_: ()) -> &'tcx LanguageItems { arena_cache eval_always desc { "calculating the lang items map" } } /// Returns all diagnostic items defined in all crates. - query all_diagnostic_items(_: ()) -> rustc_hir::diagnostic_items::DiagnosticItems { + query all_diagnostic_items(_: ()) -> &'tcx rustc_hir::diagnostic_items::DiagnosticItems { arena_cache eval_always desc { "calculating the diagnostic items map" } @@ -1752,7 +1752,7 @@ rustc_queries! { } /// Returns the diagnostic items defined in a crate. - query diagnostic_items(_: CrateNum) -> rustc_hir::diagnostic_items::DiagnosticItems { + query diagnostic_items(_: CrateNum) -> &'tcx rustc_hir::diagnostic_items::DiagnosticItems { arena_cache desc { "calculating the diagnostic items map in a crate" } separate_provide_extern @@ -1762,11 +1762,11 @@ rustc_queries! { desc { "calculating the missing lang items in a crate" } separate_provide_extern } - query visible_parent_map(_: ()) -> DefIdMap { + query visible_parent_map(_: ()) -> &'tcx DefIdMap { arena_cache desc { "calculating the visible parent map" } } - query trimmed_def_paths(_: ()) -> FxHashMap { + query trimmed_def_paths(_: ()) -> &'tcx FxHashMap { arena_cache desc { "calculating trimmed def paths" } } @@ -1775,14 +1775,14 @@ rustc_queries! { desc { "seeing if we're missing an `extern crate` item for this crate" } separate_provide_extern } - query used_crate_source(_: CrateNum) -> Lrc { + query used_crate_source(_: CrateNum) -> &'tcx Lrc { arena_cache eval_always desc { "looking at the source for a crate" } separate_provide_extern } /// Returns the debugger visualizers defined for this crate. - query debugger_visualizers(_: CrateNum) -> Vec { + query debugger_visualizers(_: CrateNum) -> &'tcx Vec { arena_cache desc { "looking up the debugger visualizers for this crate" } separate_provide_extern @@ -1820,7 +1820,7 @@ rustc_queries! { desc { |tcx| "finding names imported by glob use for `{}`", tcx.def_path_str(def_id.to_def_id()) } } - query stability_index(_: ()) -> stability::Index { + query stability_index(_: ()) -> &'tcx stability::Index { arena_cache eval_always desc { "calculating the stability index for the local crate" } @@ -1884,7 +1884,7 @@ rustc_queries! { /// /// This query returns an `&Arc` because codegen backends need the value even after the `TyCtxt` /// has been destroyed. - query output_filenames(_: ()) -> Arc { + query output_filenames(_: ()) -> &'tcx Arc { feedable desc { "getting output filenames" } arena_cache @@ -2057,7 +2057,7 @@ rustc_queries! { remap_env_constness } - query supported_target_features(_: CrateNum) -> FxHashMap> { + query supported_target_features(_: CrateNum) -> &'tcx FxHashMap> { arena_cache eval_always desc { "looking up supported target features" } @@ -2116,23 +2116,24 @@ rustc_queries! { /// span) for an *existing* error. Therefore, it is best-effort, and may never handle /// all of the cases that the normal `ty::Ty`-based wfcheck does. This is fine, /// because the `ty::Ty`-based wfcheck is always run. - query diagnostic_hir_wf_check(key: (ty::Predicate<'tcx>, traits::WellFormedLoc)) -> Option> { + query diagnostic_hir_wf_check( + key: (ty::Predicate<'tcx>, traits::WellFormedLoc) + ) -> &'tcx Option> { arena_cache eval_always no_hash desc { "performing HIR wf-checking for predicate `{:?}` at item `{:?}`", key.0, key.1 } } - /// The list of backend features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`, /// `--target` and similar). - query global_backend_features(_: ()) -> Vec { + query global_backend_features(_: ()) -> &'tcx Vec { arena_cache eval_always desc { "computing the backend features for CLI flags" } } - query generator_diagnostic_data(key: DefId) -> Option> { + query generator_diagnostic_data(key: DefId) -> &'tcx Option> { arena_cache desc { |tcx| "looking up generator diagnostic data of `{}`", tcx.def_path_str(key) } separate_provide_extern diff --git a/compiler/rustc_middle/src/ty/query.rs b/compiler/rustc_middle/src/ty/query.rs index 7151b79c5ab63..933aaadd62e1d 100644 --- a/compiler/rustc_middle/src/ty/query.rs +++ b/compiler/rustc_middle/src/ty/query.rs @@ -112,15 +112,15 @@ macro_rules! query_helper_param_ty { ($K:ty) => { $K }; } -macro_rules! query_storage { - ([][$K:ty, $V:ty]) => { - <<$K as Key>::CacheSelector as CacheSelector<'tcx, $V>>::Cache +macro_rules! query_if_arena { + ([] $arena:ty, $no_arena:ty) => { + $no_arena }; - ([(arena_cache) $($rest:tt)*][$K:ty, $V:ty]) => { - <<$K as Key>::CacheSelector as CacheSelector<'tcx, $V>>::ArenaCache + ([(arena_cache) $($rest:tt)*] $arena:ty, $no_arena:ty) => { + $arena }; - ([$other:tt $($modifiers:tt)*][$($args:tt)*]) => { - query_storage!([$($modifiers)*][$($args)*]) + ([$other:tt $($modifiers:tt)*]$($args:tt)*) => { + query_if_arena!([$($modifiers)*]$($args)*) }; } @@ -184,23 +184,30 @@ macro_rules! define_callbacks { $(pub type $name<'tcx> = $($K)*;)* } - #[allow(nonstandard_style, unused_lifetimes)] + #[allow(nonstandard_style, unused_lifetimes, unused_parens)] pub mod query_values { use super::*; - $(pub type $name<'tcx> = $V;)* + $(pub type $name<'tcx> = query_if_arena!([$($modifiers)*] <$V as Deref>::Target, $V);)* } - #[allow(nonstandard_style, unused_lifetimes)] + #[allow(nonstandard_style, unused_lifetimes, unused_parens)] pub mod query_storage { use super::*; - $(pub type $name<'tcx> = query_storage!([$($modifiers)*][$($K)*, $V]);)* + $( + pub type $name<'tcx> = query_if_arena!([$($modifiers)*] + <<$($K)* as Key>::CacheSelector + as CacheSelector<'tcx, <$V as Deref>::Target>>::ArenaCache, + <<$($K)* as Key>::CacheSelector as CacheSelector<'tcx, $V>>::Cache + ); + )* } + #[allow(nonstandard_style, unused_lifetimes)] pub mod query_stored { use super::*; - $(pub type $name<'tcx> = as QueryStorage>::Stored;)* + $(pub type $name<'tcx> = $V;)* } #[derive(Default)] @@ -226,7 +233,7 @@ macro_rules! define_callbacks { $($(#[$attr])* #[inline(always)] #[must_use] - pub fn $name(self, key: query_helper_param_ty!($($K)*)) -> query_stored::$name<'tcx> + pub fn $name(self, key: query_helper_param_ty!($($K)*)) -> $V { self.at(DUMMY_SP).$name(key) })* @@ -235,7 +242,7 @@ macro_rules! define_callbacks { impl<'tcx> TyCtxtAt<'tcx> { $($(#[$attr])* #[inline(always)] - pub fn $name(self, key: query_helper_param_ty!($($K)*)) -> query_stored::$name<'tcx> + pub fn $name(self, key: query_helper_param_ty!($($K)*)) -> $V { let key = key.into_query_param(); opt_remap_env_constness!([$($modifiers)*][key]); @@ -306,7 +313,7 @@ macro_rules! define_callbacks { span: Span, key: query_keys::$name<'tcx>, mode: QueryMode, - ) -> Option>;)* + ) -> Option<$V>;)* } }; } @@ -328,7 +335,7 @@ macro_rules! define_feedable { $(impl<'tcx, K: IntoQueryParam<$($K)*> + Copy> TyCtxtFeed<'tcx, K> { $(#[$attr])* #[inline(always)] - pub fn $name(self, value: $V) -> query_stored::$name<'tcx> { + pub fn $name(self, value: query_values::$name<'tcx>) -> $V { let key = self.key().into_query_param(); opt_remap_env_constness!([$($modifiers)*][key]); From eb18293cec81d3e717f5287f305f7f3c596eb5d6 Mon Sep 17 00:00:00 2001 From: clubby789 Date: Tue, 7 Feb 2023 11:40:55 +0000 Subject: [PATCH 3/9] Allow automatically creating vscode `settings.json` from bootstrap --- src/bootstrap/setup.rs | 147 ++++++++++++++++++++++++++++------- src/bootstrap/setup/tests.rs | 14 ++++ src/etc/vscode_settings.json | 26 +++++++ 3 files changed, 161 insertions(+), 26 deletions(-) create mode 100644 src/bootstrap/setup/tests.rs create mode 100644 src/etc/vscode_settings.json diff --git a/src/bootstrap/setup.rs b/src/bootstrap/setup.rs index 004601cb68b10..c98a52450849e 100644 --- a/src/bootstrap/setup.rs +++ b/src/bootstrap/setup.rs @@ -1,6 +1,7 @@ use crate::builder::{Builder, RunConfig, ShouldRun, Step}; use crate::Config; use crate::{t, VERSION}; +use sha2::Digest; use std::env::consts::EXE_SUFFIX; use std::fmt::Write as _; use std::fs::File; @@ -10,6 +11,9 @@ use std::process::Command; use std::str::FromStr; use std::{fmt, fs, io}; +#[cfg(test)] +mod tests; + #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] pub enum Profile { Compiler, @@ -19,6 +23,13 @@ pub enum Profile { User, } +/// A list of historical hashes of `src/etc/vscode_settings.json`. +/// New entries should be appended whenever this is updated so we can detected +/// outdated vs. user-modified settings files. +static SETTINGS_HASHES: &[&str] = + &["ea67e259dedf60d4429b6c349a564ffcd1563cf41c920a856d1f5b16b4701ac8"]; +static VSCODE_SETTINGS: &str = include_str!("../etc/vscode_settings.json"); + impl Profile { fn include_path(&self, src_path: &Path) -> PathBuf { PathBuf::from(format!("{}/src/bootstrap/defaults/config.{}.toml", src_path.display(), self)) @@ -155,6 +166,7 @@ pub fn setup(config: &Config, profile: Profile) { if !config.dry_run() { t!(install_git_hook_maybe(&config)); + t!(create_vscode_settings_maybe(&config)); } println!(); @@ -351,6 +363,34 @@ pub fn interactive_path() -> io::Result { Ok(template) } +#[derive(PartialEq)] +enum PromptResult { + Yes, // y/Y/yes + No, // n/N/no + Print, // p/P/print +} + +/// Prompt a user for a answer, looping until they enter an accepted input or nothing +fn prompt_user(prompt: &str) -> io::Result> { + let mut input = String::new(); + loop { + print!("{prompt} "); + io::stdout().flush()?; + input.clear(); + io::stdin().read_line(&mut input)?; + match input.trim().to_lowercase().as_str() { + "y" | "yes" => return Ok(Some(PromptResult::Yes)), + "n" | "no" => return Ok(Some(PromptResult::No)), + "p" | "print" => return Ok(Some(PromptResult::Print)), + "" => return Ok(None), + _ => { + eprintln!("error: unrecognized option '{}'", input.trim()); + eprintln!("note: press Ctrl+C to exit"); + } + }; + } +} + // install a git hook to automatically run tidy, if they want fn install_git_hook_maybe(config: &Config) -> io::Result<()> { let git = t!(config.git().args(&["rev-parse", "--git-common-dir"]).output().map(|output| { @@ -363,43 +403,98 @@ fn install_git_hook_maybe(config: &Config) -> io::Result<()> { return Ok(()); } - let mut input = String::new(); - println!(); println!( - "Rust's CI will automatically fail if it doesn't pass `tidy`, the internal tool for ensuring code quality. + "\nRust's CI will automatically fail if it doesn't pass `tidy`, the internal tool for ensuring code quality. If you'd like, x.py can install a git hook for you that will automatically run `test tidy` before pushing your code to ensure your code is up to par. If you decide later that this behavior is undesirable, simply delete the `pre-push` file from .git/hooks." ); - let should_install = loop { - print!("Would you like to install the git hook?: [y/N] "); - io::stdout().flush()?; - input.clear(); - io::stdin().read_line(&mut input)?; - break match input.trim().to_lowercase().as_str() { - "y" | "yes" => true, - "n" | "no" | "" => false, - _ => { - eprintln!("error: unrecognized option '{}'", input.trim()); - eprintln!("note: press Ctrl+C to exit"); - continue; - } - }; - }; - - if should_install { - let src = config.src.join("src").join("etc").join("pre-push.sh"); - match fs::hard_link(src, &dst) { - Err(e) => eprintln!( + if prompt_user("Would you like to install the git hook?: [y/N]")? != Some(PromptResult::Yes) { + println!("Ok, skipping installation!"); + return Ok(()); + } + let src = config.src.join("src").join("etc").join("pre-push.sh"); + match fs::hard_link(src, &dst) { + Err(e) => { + eprintln!( "error: could not create hook {}: do you already have the git hook installed?\n{}", dst.display(), e - ), - Ok(_) => println!("Linked `src/etc/pre-push.sh` to `.git/hooks/pre-push`"), + ); + return Err(e); + } + Ok(_) => println!("Linked `src/etc/pre-push.sh` to `.git/hooks/pre-push`"), + }; + Ok(()) +} + +/// Create a `.vscode/settings.json` file for rustc development, or just print it +fn create_vscode_settings_maybe(config: &Config) -> io::Result<()> { + let (current_hash, historical_hashes) = SETTINGS_HASHES.split_last().unwrap(); + let vscode_settings = config.src.join(".vscode").join("settings.json"); + // If None, no settings.json exists + // If Some(true), is a previous version of settings.json + // If Some(false), is not a previous version (i.e. user modified) + // If it's up to date we can just skip this + let mut mismatched_settings = None; + if let Ok(current) = fs::read_to_string(&vscode_settings) { + let mut hasher = sha2::Sha256::new(); + hasher.update(¤t); + let hash = hex::encode(hasher.finalize().as_slice()); + if hash == *current_hash { + return Ok(()); + } else if historical_hashes.contains(&hash.as_str()) { + mismatched_settings = Some(true); + } else { + mismatched_settings = Some(false); + } + } + println!( + "\nx.py can automatically install the recommended `.vscode/settings.json` file for rustc development" + ); + match mismatched_settings { + Some(true) => eprintln!( + "warning: existing `.vscode/settings.json` is out of date, x.py will update it" + ), + Some(false) => eprintln!( + "warning: existing `.vscode/settings.json` has been modified by user, x.py will back it up and replace it" + ), + _ => (), + } + let should_create = match prompt_user( + "Would you like to create/update `settings.json`, or only print suggested settings?: [y/p/N]", + )? { + Some(PromptResult::Yes) => true, + Some(PromptResult::Print) => false, + _ => { + println!("Ok, skipping settings!"); + return Ok(()); + } + }; + if should_create { + let path = config.src.join(".vscode"); + if !path.exists() { + fs::create_dir(&path)?; + } + let verb = match mismatched_settings { + // exists but outdated, we can replace this + Some(true) => "Updated", + // exists but user modified, back it up + Some(false) => { + // exists and is not current version or outdated, so back it up + let mut backup = vscode_settings.clone(); + backup.set_extension("bak"); + eprintln!("warning: copying `settings.json` to `settings.json.bak`"); + fs::copy(&vscode_settings, &backup)?; + "Updated" + } + _ => "Created", }; + fs::write(&vscode_settings, &VSCODE_SETTINGS)?; + println!("{verb} `.vscode/settings.json`"); } else { - println!("Ok, skipping installation!"); + println!("\n{VSCODE_SETTINGS}"); } Ok(()) } diff --git a/src/bootstrap/setup/tests.rs b/src/bootstrap/setup/tests.rs new file mode 100644 index 0000000000000..dcf9d18e63210 --- /dev/null +++ b/src/bootstrap/setup/tests.rs @@ -0,0 +1,14 @@ +use super::{SETTINGS_HASHES, VSCODE_SETTINGS}; +use sha2::Digest; + +#[test] +fn check_matching_settings_hash() { + let mut hasher = sha2::Sha256::new(); + hasher.update(&VSCODE_SETTINGS); + let hash = hex::encode(hasher.finalize().as_slice()); + assert_eq!( + &hash, + SETTINGS_HASHES.last().unwrap(), + "Update `SETTINGS_HASHES` with the new hash of `src/etc/vscode_settings.json`" + ); +} diff --git a/src/etc/vscode_settings.json b/src/etc/vscode_settings.json new file mode 100644 index 0000000000000..cd61a38c5da98 --- /dev/null +++ b/src/etc/vscode_settings.json @@ -0,0 +1,26 @@ +{ + "rust-analyzer.checkOnSave.overrideCommand": [ + "python3", + "x.py", + "check", + "--json-output" + ], + "rust-analyzer.linkedProjects": ["src/bootstrap/Cargo.toml", "Cargo.toml"], + "rust-analyzer.rustfmt.overrideCommand": [ + "./build/host/rustfmt/bin/rustfmt", + "--edition=2021" + ], + "rust-analyzer.procMacro.server": "./build/host/stage0/libexec/rust-analyzer-proc-macro-srv", + "rust-analyzer.procMacro.enable": true, + "rust-analyzer.cargo.buildScripts.enable": true, + "rust-analyzer.cargo.buildScripts.invocationLocation": "root", + "rust-analyzer.cargo.buildScripts.invocationStrategy": "once", + "rust-analyzer.cargo.buildScripts.overrideCommand": [ + "python3", + "x.py", + "check", + "--json-output" + ], + "rust-analyzer.cargo.sysroot": "./build/host/stage0-sysroot", + "rust-analyzer.rustc.source": "./Cargo.toml" +} From 8307fd7901c9832e7b22ee5139efe6f7f2d291b3 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Tue, 7 Feb 2023 11:23:25 -0700 Subject: [PATCH 4/9] rustdoc: use a newline instead of `
` to format code headers Since these elements now use `white-space: pre-wrap` since 784665d4ce59c5239791f1f96fa2137e47ca1817, it's fine to use newlines for formatting, which is smaller and a bit less complicated. --- src/librustdoc/html/format.rs | 31 +++++++++---------- tests/rustdoc/async-fn.rs | 2 +- .../const-generics/const-generics-docs.rs | 2 +- .../decl-trailing-whitespace.declaration.html | 24 +++++++++++--- .../rustdoc/generic-associated-types/gats.rs | 4 +-- tests/rustdoc/inline_cross/impl_trait.rs | 2 +- tests/rustdoc/issue-34928.rs | 2 +- tests/rustdoc/reexports-priv.rs | 2 +- .../rustdoc/where.SWhere_Simd_item-decl.html | 4 ++- .../where.SWhere_TraitWhere_item-decl.html | 13 +++++--- tests/rustdoc/where.rs | 2 +- .../whitespace-after-where-clause.enum.html | 3 +- .../whitespace-after-where-clause.struct.html | 3 +- .../whitespace-after-where-clause.trait.html | 3 +- .../whitespace-after-where-clause.union.html | 3 +- 15 files changed, 61 insertions(+), 39 deletions(-) diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index a59cfbea8853e..8a7a8ea5fd1f2 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -289,7 +289,7 @@ pub(crate) fn print_where_clause<'a, 'tcx: 'a>( if f.alternate() { f.write_str(" ")?; } else { - f.write_str("
")?; + f.write_str("\n")?; } match pred { @@ -352,7 +352,7 @@ pub(crate) fn print_where_clause<'a, 'tcx: 'a>( } } else { let mut br_with_padding = String::with_capacity(6 * indent + 28); - br_with_padding.push_str("
"); + br_with_padding.push_str("\n"); let padding_amout = if ending == Ending::Newline { indent + 4 } else { indent + "fn where ".len() }; @@ -360,16 +360,16 @@ pub(crate) fn print_where_clause<'a, 'tcx: 'a>( for _ in 0..padding_amout { br_with_padding.push_str(" "); } - let where_preds = where_preds.to_string().replace("
", &br_with_padding); + let where_preds = where_preds.to_string().replace("\n", &br_with_padding); if ending == Ending::Newline { let mut clause = " ".repeat(indent.saturating_sub(1)); write!(clause, "where{where_preds},")?; clause } else { - // insert a
tag after a single space but before multiple spaces at the start + // insert a newline after a single space but before multiple spaces at the start if indent == 0 { - format!("
where{where_preds}") + format!("\nwhere{where_preds}") } else { // put the first one on the same line as the 'where' keyword let where_preds = where_preds.replacen(&br_with_padding, " ", 1); @@ -1315,7 +1315,8 @@ impl clean::FnDecl { /// * `header_len`: The length of the function header and name. In other words, the number of /// characters in the function declaration up to but not including the parentheses. - ///
Used to determine line-wrapping. + /// This is expected to go into a `
`/`code-header` block, so indentation and newlines
+    ///   are preserved.
     /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
     ///   necessary.
     pub(crate) fn full_print<'a, 'tcx: 'a>(
@@ -1363,7 +1364,7 @@ impl clean::FnDecl {
                 }
             } else {
                 if i > 0 {
-                    args.push_str("
"); + args.push_str("\n"); } if input.is_const { args.push_str("const "); @@ -1389,7 +1390,7 @@ impl clean::FnDecl { let mut args = args.into_inner(); if self.c_variadic { - args.push_str(",
..."); + args.push_str(",\n ..."); args_plain.push_str(", ..."); } @@ -1399,24 +1400,20 @@ impl clean::FnDecl { let declaration_len = header_len + args_plain.len() + arrow_plain.len(); let output = if declaration_len > 80 { - let full_pad = format!("
{}", " ".repeat(indent + 4)); - let close_pad = format!("
{}", " ".repeat(indent)); + let full_pad = format!("\n{}", " ".repeat(indent + 4)); + let close_pad = format!("\n{}", " ".repeat(indent)); format!( "({pad}{args}{close}){arrow}", pad = if self.inputs.values.is_empty() { "" } else { &full_pad }, - args = args.replace("
", &full_pad), + args = args.replace("\n", &full_pad), close = close_pad, arrow = arrow ) } else { - format!("({args}){arrow}", args = args.replace("
", " "), arrow = arrow) + format!("({args}){arrow}", args = args.replace("\n", " "), arrow = arrow) }; - if f.alternate() { - write!(f, "{}", output.replace("
", "\n")) - } else { - write!(f, "{}", output) - } + write!(f, "{}", output) } } diff --git a/tests/rustdoc/async-fn.rs b/tests/rustdoc/async-fn.rs index 3db344af67439..70bcbcb6ff44a 100644 --- a/tests/rustdoc/async-fn.rs +++ b/tests/rustdoc/async-fn.rs @@ -77,7 +77,7 @@ struct AsyncFdReadyGuard<'a, T> { x: &'a T } impl Foo { // @has async_fn/struct.Foo.html - // @has - '//*[@class="method"]' 'pub async fn complicated_lifetimes( &self, context: &impl Bar) -> impl Iterator' + // @has - '//*[@class="method"]' 'pub async fn complicated_lifetimes( &self, context: &impl Bar ) -> impl Iterator' pub async fn complicated_lifetimes(&self, context: &impl Bar) -> impl Iterator {} // taken from `tokio` as an example of a method that was particularly bad before // @has - '//*[@class="method"]' "pub async fn readable(&self) -> Result, ()>" diff --git a/tests/rustdoc/const-generics/const-generics-docs.rs b/tests/rustdoc/const-generics/const-generics-docs.rs index ade70bbe80d92..cbda095424b7d 100644 --- a/tests/rustdoc/const-generics/const-generics-docs.rs +++ b/tests/rustdoc/const-generics/const-generics-docs.rs @@ -31,7 +31,7 @@ impl Trait<{1 + 2}> for u8 {} impl Trait for [u8; N] {} // @has foo/struct.Foo.html '//pre[@class="rust item-decl"]' \ -// 'pub struct Foowhere u8: Trait' +// 'pub struct Foo where u8: Trait' pub struct Foo where u8: Trait; // @has foo/struct.Bar.html '//pre[@class="rust item-decl"]' 'pub struct Bar(_)' pub struct Bar([T; N]); diff --git a/tests/rustdoc/decl-trailing-whitespace.declaration.html b/tests/rustdoc/decl-trailing-whitespace.declaration.html index a2500de79a096..d73393633f3b8 100644 --- a/tests/rustdoc/decl-trailing-whitespace.declaration.html +++ b/tests/rustdoc/decl-trailing-whitespace.declaration.html @@ -1,9 +1,23 @@ pub trait Write { // Required methods - fn poll_write(
        self: Option<String>,
        cx: &mut Option<String>,
        buf: &mut [usize]
    ) -> Option<Result<usize, Error>>; - fn poll_flush(
        self: Option<String>,
        cx: &mut Option<String>
    ) -> Option<Result<(), Error>>; - fn poll_close(
        self: Option<String>,
        cx: &mut Option<String>
    ) -> Option<Result<(), Error>>; + fn poll_write( + self: Option<String>, + cx: &mut Option<String>, + buf: &mut [usize] + ) -> Option<Result<usize, Error>>; + fn poll_flush( + self: Option<String>, + cx: &mut Option<String> + ) -> Option<Result<(), Error>>; + fn poll_close( + self: Option<String>, + cx: &mut Option<String> + ) -> Option<Result<(), Error>>; // Provided method - fn poll_write_vectored(
        self: Option<String>,
        cx: &mut Option<String>,
        bufs: &[usize]
    ) -> Option<Result<usize, Error>> { ... } -}
+ fn poll_write_vectored( + self: Option<String>, + cx: &mut Option<String>, + bufs: &[usize] + ) -> Option<Result<usize, Error>> { ... } +} \ No newline at end of file diff --git a/tests/rustdoc/generic-associated-types/gats.rs b/tests/rustdoc/generic-associated-types/gats.rs index bcead3115fef4..7ab82bb582965 100644 --- a/tests/rustdoc/generic-associated-types/gats.rs +++ b/tests/rustdoc/generic-associated-types/gats.rs @@ -2,7 +2,7 @@ // @has foo/trait.LendingIterator.html pub trait LendingIterator { - // @has - '//*[@id="associatedtype.Item"]//h4[@class="code-header"]' "type Item<'a>where Self: 'a" + // @has - '//*[@id="associatedtype.Item"]//h4[@class="code-header"]' "type Item<'a> where Self: 'a" type Item<'a> where Self: 'a; // @has - '//*[@id="tymethod.next"]//h4[@class="code-header"]' \ @@ -23,7 +23,7 @@ impl LendingIterator for () { pub struct Infinite(T); // @has foo/trait.LendingIterator.html -// @has - '//*[@id="associatedtype.Item-2"]//h4[@class="code-header"]' "type Item<'a>where Self: 'a = &'a T" +// @has - '//*[@id="associatedtype.Item-2"]//h4[@class="code-header"]' "type Item<'a> where Self: 'a = &'a T" impl LendingIterator for Infinite { type Item<'a> where Self: 'a = &'a T; diff --git a/tests/rustdoc/inline_cross/impl_trait.rs b/tests/rustdoc/inline_cross/impl_trait.rs index 7d810ab481372..b6a1552bc00ca 100644 --- a/tests/rustdoc/inline_cross/impl_trait.rs +++ b/tests/rustdoc/inline_cross/impl_trait.rs @@ -11,7 +11,7 @@ pub use impl_trait_aux::func; // @has impl_trait/fn.func2.html // @has - '//pre[@class="rust item-decl"]' "func2(" // @has - '//pre[@class="rust item-decl"]' "_x: impl Deref> + Iterator," -// @has - '//pre[@class="rust item-decl"]' "_y: impl Iterator)" +// @has - '//pre[@class="rust item-decl"]' "_y: impl Iterator )" // @!has - '//pre[@class="rust item-decl"]' 'where' pub use impl_trait_aux::func2; diff --git a/tests/rustdoc/issue-34928.rs b/tests/rustdoc/issue-34928.rs index 91b67757453d2..4184086f622ab 100644 --- a/tests/rustdoc/issue-34928.rs +++ b/tests/rustdoc/issue-34928.rs @@ -2,5 +2,5 @@ pub trait Bar {} -// @has foo/struct.Foo.html '//pre' 'pub struct Foo(pub T)where T: Bar;' +// @has foo/struct.Foo.html '//pre' 'pub struct Foo(pub T) where T: Bar;' pub struct Foo(pub T) where T: Bar; diff --git a/tests/rustdoc/reexports-priv.rs b/tests/rustdoc/reexports-priv.rs index 84ea4ad2c9ef3..571d7f06fdc62 100644 --- a/tests/rustdoc/reexports-priv.rs +++ b/tests/rustdoc/reexports-priv.rs @@ -98,7 +98,7 @@ pub mod outer { pub use reexports::foo; // @has 'foo/outer/inner/fn.foo_crate.html' '//pre[@class="rust item-decl"]' 'pub(crate) fn foo_crate()' pub(crate) use reexports::foo_crate; - // @has 'foo/outer/inner/fn.foo_super.html' '//pre[@class="rust item-decl"]' 'pub(in outer) fn foo_super()' + // @has 'foo/outer/inner/fn.foo_super.html' '//pre[@class="rust item-decl"]' 'pub(in outer) fn foo_super( )' pub(super) use::reexports::foo_super; // @!has 'foo/outer/inner/fn.foo_self.html' pub(self) use reexports::foo_self; diff --git a/tests/rustdoc/where.SWhere_Simd_item-decl.html b/tests/rustdoc/where.SWhere_Simd_item-decl.html index 6f151f2328e4f..ef4294c8f76d3 100644 --- a/tests/rustdoc/where.SWhere_Simd_item-decl.html +++ b/tests/rustdoc/where.SWhere_Simd_item-decl.html @@ -1 +1,3 @@ -
pub struct Simd<T>(_)
where
    T: MyTrait
;
\ No newline at end of file +
pub struct Simd<T>(_)
+where
+         T: MyTrait;
\ No newline at end of file diff --git a/tests/rustdoc/where.SWhere_TraitWhere_item-decl.html b/tests/rustdoc/where.SWhere_TraitWhere_item-decl.html index 858bc142f66e1..e8ab061e679dd 100644 --- a/tests/rustdoc/where.SWhere_TraitWhere_item-decl.html +++ b/tests/rustdoc/where.SWhere_TraitWhere_item-decl.html @@ -1,8 +1,13 @@
pub trait TraitWhere {
-    type Item<'a>
       where Self: 'a; + type Item<'a> + where Self: 'a; // Provided methods - fn func(self)
       where Self: Sized { ... } - fn lines(self) -> Lines<Self>
       where Self: Sized { ... } - fn merge<T>(self, a: T)
       where Self: Sized,
             T: Sized
{ ... } + fn func(self) + where Self: Sized { ... } + fn lines(self) -> Lines<Self> + where Self: Sized { ... } + fn merge<T>(self, a: T) + where Self: Sized, + T: Sized { ... } }
\ No newline at end of file diff --git a/tests/rustdoc/where.rs b/tests/rustdoc/where.rs index af3239b69470c..8b8a126e89dd5 100644 --- a/tests/rustdoc/where.rs +++ b/tests/rustdoc/where.rs @@ -4,7 +4,7 @@ use std::io::Lines; pub trait MyTrait { fn dummy(&self) { } } -// @has foo/struct.Alpha.html '//pre' "pub struct Alpha(_)where A: MyTrait" +// @has foo/struct.Alpha.html '//pre' "pub struct Alpha(_) where A: MyTrait" pub struct Alpha(A) where A: MyTrait; // @has foo/trait.Bravo.html '//pre' "pub trait Bravowhere B: MyTrait" pub trait Bravo where B: MyTrait { fn get(&self, B: B); } diff --git a/tests/rustdoc/whitespace-after-where-clause.enum.html b/tests/rustdoc/whitespace-after-where-clause.enum.html index 904d461103617..20b60b68e88cf 100644 --- a/tests/rustdoc/whitespace-after-where-clause.enum.html +++ b/tests/rustdoc/whitespace-after-where-clause.enum.html @@ -1,4 +1,5 @@ -
pub enum Cow<'a, B>where
    B:
ToOwned<dyn Clone> + ?Sized + 'a,{ +
pub enum Cow<'a, B>where
+    B: ToOwned<dyn Clone> + ?Sized + 'a,{
     Borrowed(&'a B),
     Whatever(u32),
 }
\ No newline at end of file diff --git a/tests/rustdoc/whitespace-after-where-clause.struct.html b/tests/rustdoc/whitespace-after-where-clause.struct.html index 54faee9e4052b..948ddc499da8a 100644 --- a/tests/rustdoc/whitespace-after-where-clause.struct.html +++ b/tests/rustdoc/whitespace-after-where-clause.struct.html @@ -1,4 +1,5 @@ -
pub struct Struct<'a, B>where
    B: ToOwned<dyn Clone> + ?Sized + 'a,
{ +
pub struct Struct<'a, B>where
+    B: ToOwned<dyn Clone> + ?Sized + 'a,{
     pub a: &'a B,
     pub b: u32,
 }
\ No newline at end of file diff --git a/tests/rustdoc/whitespace-after-where-clause.trait.html b/tests/rustdoc/whitespace-after-where-clause.trait.html index 8a78e82dc71dc..0928b48e6b64c 100644 --- a/tests/rustdoc/whitespace-after-where-clause.trait.html +++ b/tests/rustdoc/whitespace-after-where-clause.trait.html @@ -1,4 +1,5 @@ -
pub trait ToOwned<T>where
    T: Clone,
{ +
pub trait ToOwned<T>where
+    T: Clone,{
     type Owned;
 
     // Required methods
diff --git a/tests/rustdoc/whitespace-after-where-clause.union.html b/tests/rustdoc/whitespace-after-where-clause.union.html
index 03a26280ba2cf..38b6cb8b5c613 100644
--- a/tests/rustdoc/whitespace-after-where-clause.union.html
+++ b/tests/rustdoc/whitespace-after-where-clause.union.html
@@ -1,3 +1,4 @@
-
pub union Union<'a, B>where
    B: ToOwned<dyn Clone> + ?Sized + 'a,
{ +
pub union Union<'a, B>where
+    B: ToOwned<dyn Clone> + ?Sized + 'a,{
     /* private fields */
 }
\ No newline at end of file From 2b70cbb8a5935a8fbc8d52d7e8304f8eefeb2d21 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 7 Feb 2023 18:02:20 +0000 Subject: [PATCH 5/9] Rename PointerSized to PointerLike --- .../rustc_const_eval/src/interpret/cast.rs | 2 +- compiler/rustc_hir/src/lang_items.rs | 2 +- compiler/rustc_hir_typeck/src/coercion.rs | 2 +- compiler/rustc_span/src/symbol.rs | 2 +- .../src/solve/assembly.rs | 8 +++---- .../src/solve/project_goals.rs | 4 ++-- .../src/solve/trait_goals.rs | 2 +- .../src/traits/select/candidate_assembly.rs | 2 +- library/core/src/marker.rs | 11 +++++---- tests/ui/dyn-star/align.over_aligned.stderr | 6 ++--- tests/ui/dyn-star/align.rs | 2 +- .../check-size-at-cast-polymorphic-bad.rs | 2 +- .../check-size-at-cast-polymorphic-bad.stderr | 10 ++++---- tests/ui/dyn-star/check-size-at-cast.rs | 2 +- tests/ui/dyn-star/check-size-at-cast.stderr | 6 ++--- tests/ui/dyn-star/upcast.stderr | 6 ++--- tests/ui/traits/new-solver/pointer-like.rs | 14 +++++++++++ .../ui/traits/new-solver/pointer-like.stderr | 24 +++++++++++++++++++ tests/ui/traits/new-solver/pointer-sized.rs | 12 ---------- .../ui/traits/new-solver/pointer-sized.stderr | 24 ------------------- 20 files changed, 73 insertions(+), 70 deletions(-) create mode 100644 tests/ui/traits/new-solver/pointer-like.rs create mode 100644 tests/ui/traits/new-solver/pointer-like.stderr delete mode 100644 tests/ui/traits/new-solver/pointer-sized.rs delete mode 100644 tests/ui/traits/new-solver/pointer-sized.stderr diff --git a/compiler/rustc_const_eval/src/interpret/cast.rs b/compiler/rustc_const_eval/src/interpret/cast.rs index b2c847d3fd8dd..fc8e0c67ae09a 100644 --- a/compiler/rustc_const_eval/src/interpret/cast.rs +++ b/compiler/rustc_const_eval/src/interpret/cast.rs @@ -126,7 +126,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let vtable = self.get_vtable_ptr(src.layout.ty, data.principal())?; let vtable = Scalar::from_maybe_pointer(vtable, self); let data = self.read_immediate(src)?.to_scalar(); - let _assert_pointer_sized = data.to_pointer(self)?; + let _assert_pointer_like = data.to_pointer(self)?; let val = Immediate::ScalarPair(data, vtable); self.write_immediate(val, dest)?; } else { diff --git a/compiler/rustc_hir/src/lang_items.rs b/compiler/rustc_hir/src/lang_items.rs index 9158fc082471f..0454633091568 100644 --- a/compiler/rustc_hir/src/lang_items.rs +++ b/compiler/rustc_hir/src/lang_items.rs @@ -287,7 +287,7 @@ language_item_table! { TryTraitBranch, sym::branch, branch_fn, Target::Method(MethodKind::Trait { body: false }), GenericRequirement::None; TryTraitFromYeet, sym::from_yeet, from_yeet_fn, Target::Fn, GenericRequirement::None; - PointerSized, sym::pointer_sized, pointer_sized, Target::Trait, GenericRequirement::Exact(0); + PointerLike, sym::pointer_like, pointer_like, Target::Trait, GenericRequirement::Exact(0); Poll, sym::Poll, poll, Target::Enum, GenericRequirement::None; PollReady, sym::Ready, poll_ready_variant, Target::Variant, GenericRequirement::None; diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index ade9c037c5194..7173239ba619a 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -765,7 +765,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { self.cause.clone(), self.param_env, ty::Binder::dummy( - self.tcx.at(self.cause.span).mk_trait_ref(hir::LangItem::PointerSized, [a]), + self.tcx.at(self.cause.span).mk_trait_ref(hir::LangItem::PointerLike, [a]), ), )); diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index f1119214be44d..1ced75cccbb30 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1084,7 +1084,7 @@ symbols! { plugins, pointee_trait, pointer, - pointer_sized, + pointer_like, poll, position, post_dash_lto: "post-lto", diff --git a/compiler/rustc_trait_selection/src/solve/assembly.rs b/compiler/rustc_trait_selection/src/solve/assembly.rs index ccdf6246083cc..8525b96c0c21f 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly.rs @@ -128,9 +128,9 @@ pub(super) trait GoalKind<'tcx>: TypeFoldable<'tcx> + Copy + Eq { goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx>; - // A type is `PointerSized` if we can compute its layout, and that layout + // A type is `PointerLike` if we can compute its layout, and that layout // matches the layout of `usize`. - fn consider_builtin_pointer_sized_candidate( + fn consider_builtin_pointer_like_candidate( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx>; @@ -312,8 +312,8 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { || lang_items.clone_trait() == Some(trait_def_id) { G::consider_builtin_copy_clone_candidate(self, goal) - } else if lang_items.pointer_sized() == Some(trait_def_id) { - G::consider_builtin_pointer_sized_candidate(self, goal) + } else if lang_items.pointer_like() == Some(trait_def_id) { + G::consider_builtin_pointer_like_candidate(self, goal) } else if let Some(kind) = self.tcx().fn_trait_kind_from_def_id(trait_def_id) { G::consider_builtin_fn_trait_candidates(self, goal, kind) } else if lang_items.tuple_trait() == Some(trait_def_id) { diff --git a/compiler/rustc_trait_selection/src/solve/project_goals.rs b/compiler/rustc_trait_selection/src/solve/project_goals.rs index 9f62f686af647..f9acf7a53eee5 100644 --- a/compiler/rustc_trait_selection/src/solve/project_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/project_goals.rs @@ -370,11 +370,11 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { bug!("`Copy`/`Clone` does not have an associated type: {:?}", goal); } - fn consider_builtin_pointer_sized_candidate( + fn consider_builtin_pointer_like_candidate( _ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx> { - bug!("`PointerSized` does not have an associated type: {:?}", goal); + bug!("`PointerLike` does not have an associated type: {:?}", goal); } fn consider_builtin_fn_trait_candidates( diff --git a/compiler/rustc_trait_selection/src/solve/trait_goals.rs b/compiler/rustc_trait_selection/src/solve/trait_goals.rs index 0003dfeaee781..1cf1efc97049b 100644 --- a/compiler/rustc_trait_selection/src/solve/trait_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/trait_goals.rs @@ -131,7 +131,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { ) } - fn consider_builtin_pointer_sized_candidate( + fn consider_builtin_pointer_like_candidate( ecx: &mut EvalCtxt<'_, 'tcx>, goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx> { diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index 7b7abcf552ab7..bba07ed965b21 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -94,7 +94,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { self.assemble_candidates_for_transmutability(obligation, &mut candidates); } else if lang_items.tuple_trait() == Some(def_id) { self.assemble_candidate_for_tuple(obligation, &mut candidates); - } else if lang_items.pointer_sized() == Some(def_id) { + } else if lang_items.pointer_like() == Some(def_id) { self.assemble_candidate_for_ptr_sized(obligation, &mut candidates); } else { if lang_items.clone_trait() == Some(def_id) { diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index 74055602ec2e6..e11bca5962a15 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -872,13 +872,14 @@ pub trait Destruct {} pub trait Tuple {} /// A marker for things -#[unstable(feature = "pointer_sized_trait", issue = "none")] -#[lang = "pointer_sized"] +#[unstable(feature = "pointer_like_trait", issue = "none")] +#[cfg_attr(bootstrap, lang = "pointer_sized")] +#[cfg_attr(not(bootstrap), lang = "pointer_like")] #[rustc_on_unimplemented( - message = "`{Self}` needs to be a pointer-sized type", - label = "`{Self}` needs to be a pointer-sized type" + message = "`{Self}` needs to have the same alignment and size as a pointer", + label = "`{Self}` needs to be a pointer-like type" )] -pub trait PointerSized {} +pub trait PointerLike {} /// Implementations of `Copy` for primitive types. /// diff --git a/tests/ui/dyn-star/align.over_aligned.stderr b/tests/ui/dyn-star/align.over_aligned.stderr index 62e28efab5820..0365d87a6f82a 100644 --- a/tests/ui/dyn-star/align.over_aligned.stderr +++ b/tests/ui/dyn-star/align.over_aligned.stderr @@ -7,13 +7,13 @@ LL | #![feature(dyn_star)] = note: see issue #102425 for more information = note: `#[warn(incomplete_features)]` on by default -error[E0277]: `AlignedUsize` needs to be a pointer-sized type +error[E0277]: `AlignedUsize` needs to have the same alignment and size as a pointer --> $DIR/align.rs:15:13 | LL | let x = AlignedUsize(12) as dyn* Debug; - | ^^^^^^^^^^^^^^^^ `AlignedUsize` needs to be a pointer-sized type + | ^^^^^^^^^^^^^^^^ `AlignedUsize` needs to be a pointer-like type | - = help: the trait `PointerSized` is not implemented for `AlignedUsize` + = help: the trait `PointerLike` is not implemented for `AlignedUsize` error: aborting due to previous error; 1 warning emitted diff --git a/tests/ui/dyn-star/align.rs b/tests/ui/dyn-star/align.rs index fb41a05a0660b..6679997a94029 100644 --- a/tests/ui/dyn-star/align.rs +++ b/tests/ui/dyn-star/align.rs @@ -13,5 +13,5 @@ struct AlignedUsize(usize); fn main() { let x = AlignedUsize(12) as dyn* Debug; - //[over_aligned]~^ ERROR `AlignedUsize` needs to be a pointer-sized type + //[over_aligned]~^ ERROR `AlignedUsize` needs to have the same alignment and size as a pointer } diff --git a/tests/ui/dyn-star/check-size-at-cast-polymorphic-bad.rs b/tests/ui/dyn-star/check-size-at-cast-polymorphic-bad.rs index e19e36cc7d7b5..85749aa7b00e2 100644 --- a/tests/ui/dyn-star/check-size-at-cast-polymorphic-bad.rs +++ b/tests/ui/dyn-star/check-size-at-cast-polymorphic-bad.rs @@ -9,7 +9,7 @@ fn dyn_debug(_: (dyn* Debug + '_)) { fn polymorphic(t: &T) { dyn_debug(t); - //~^ ERROR `&T` needs to be a pointer-sized type + //~^ ERROR `&T` needs to have the same alignment and size as a pointer } fn main() {} diff --git a/tests/ui/dyn-star/check-size-at-cast-polymorphic-bad.stderr b/tests/ui/dyn-star/check-size-at-cast-polymorphic-bad.stderr index 53ccbe43dcc9e..350630f794138 100644 --- a/tests/ui/dyn-star/check-size-at-cast-polymorphic-bad.stderr +++ b/tests/ui/dyn-star/check-size-at-cast-polymorphic-bad.stderr @@ -1,14 +1,14 @@ -error[E0277]: `&T` needs to be a pointer-sized type +error[E0277]: `&T` needs to have the same alignment and size as a pointer --> $DIR/check-size-at-cast-polymorphic-bad.rs:11:15 | LL | dyn_debug(t); - | ^ `&T` needs to be a pointer-sized type + | ^ `&T` needs to be a pointer-like type | - = help: the trait `PointerSized` is not implemented for `&T` + = help: the trait `PointerLike` is not implemented for `&T` help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement | -LL | fn polymorphic(t: &T) where &T: PointerSized { - | ++++++++++++++++++++++ +LL | fn polymorphic(t: &T) where &T: PointerLike { + | +++++++++++++++++++++ error: aborting due to previous error diff --git a/tests/ui/dyn-star/check-size-at-cast.rs b/tests/ui/dyn-star/check-size-at-cast.rs index 1f22f79836154..17bc4f303bffa 100644 --- a/tests/ui/dyn-star/check-size-at-cast.rs +++ b/tests/ui/dyn-star/check-size-at-cast.rs @@ -5,6 +5,6 @@ use std::fmt::Debug; fn main() { let i = [1, 2, 3, 4] as dyn* Debug; - //~^ ERROR `[i32; 4]` needs to be a pointer-sized type + //~^ ERROR `[i32; 4]` needs to have the same alignment and size as a pointer dbg!(i); } diff --git a/tests/ui/dyn-star/check-size-at-cast.stderr b/tests/ui/dyn-star/check-size-at-cast.stderr index af2a1ccf71c6d..19700b4064400 100644 --- a/tests/ui/dyn-star/check-size-at-cast.stderr +++ b/tests/ui/dyn-star/check-size-at-cast.stderr @@ -1,10 +1,10 @@ -error[E0277]: `[i32; 4]` needs to be a pointer-sized type +error[E0277]: `[i32; 4]` needs to have the same alignment and size as a pointer --> $DIR/check-size-at-cast.rs:7:13 | LL | let i = [1, 2, 3, 4] as dyn* Debug; - | ^^^^^^^^^^^^ `[i32; 4]` needs to be a pointer-sized type + | ^^^^^^^^^^^^ `[i32; 4]` needs to be a pointer-like type | - = help: the trait `PointerSized` is not implemented for `[i32; 4]` + = help: the trait `PointerLike` is not implemented for `[i32; 4]` error: aborting due to previous error diff --git a/tests/ui/dyn-star/upcast.stderr b/tests/ui/dyn-star/upcast.stderr index 74ccd6a1889cd..e60144fea74c3 100644 --- a/tests/ui/dyn-star/upcast.stderr +++ b/tests/ui/dyn-star/upcast.stderr @@ -7,13 +7,13 @@ LL | #![feature(dyn_star, trait_upcasting)] = note: see issue #102425 for more information = note: `#[warn(incomplete_features)]` on by default -error[E0277]: `dyn* Foo` needs to be a pointer-sized type +error[E0277]: `dyn* Foo` needs to have the same alignment and size as a pointer --> $DIR/upcast.rs:30:23 | LL | let w: dyn* Bar = w; - | ^ `dyn* Foo` needs to be a pointer-sized type + | ^ `dyn* Foo` needs to be a pointer-like type | - = help: the trait `PointerSized` is not implemented for `dyn* Foo` + = help: the trait `PointerLike` is not implemented for `dyn* Foo` error: aborting due to previous error; 1 warning emitted diff --git a/tests/ui/traits/new-solver/pointer-like.rs b/tests/ui/traits/new-solver/pointer-like.rs new file mode 100644 index 0000000000000..3745a075e6a44 --- /dev/null +++ b/tests/ui/traits/new-solver/pointer-like.rs @@ -0,0 +1,14 @@ +// compile-flags: -Ztrait-solver=next + +#![feature(pointer_like_trait)] + +use std::marker::PointerLike; + +fn require_(_: impl PointerLike) {} + +fn main() { + require_(1usize); + require_(1u16); + //~^ ERROR `u16` needs to have the same alignment and size as a pointer + require_(&1i16); +} diff --git a/tests/ui/traits/new-solver/pointer-like.stderr b/tests/ui/traits/new-solver/pointer-like.stderr new file mode 100644 index 0000000000000..f695e64187d44 --- /dev/null +++ b/tests/ui/traits/new-solver/pointer-like.stderr @@ -0,0 +1,24 @@ +error[E0277]: `u16` needs to have the same alignment and size as a pointer + --> $DIR/pointer-like.rs:11:14 + | +LL | require_(1u16); + | -------- ^^^^ the trait `PointerLike` is not implemented for `u16` + | | + | required by a bound introduced by this call + | + = note: the trait bound `u16: PointerLike` is not satisfied +note: required by a bound in `require_` + --> $DIR/pointer-like.rs:7:21 + | +LL | fn require_(_: impl PointerLike) {} + | ^^^^^^^^^^^ required by this bound in `require_` +help: consider borrowing here + | +LL | require_(&1u16); + | + +LL | require_(&mut 1u16); + | ++++ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/new-solver/pointer-sized.rs b/tests/ui/traits/new-solver/pointer-sized.rs deleted file mode 100644 index 15681cd132ec6..0000000000000 --- a/tests/ui/traits/new-solver/pointer-sized.rs +++ /dev/null @@ -1,12 +0,0 @@ -#![feature(pointer_sized_trait)] - -use std::marker::PointerSized; - -fn require_pointer_sized(_: impl PointerSized) {} - -fn main() { - require_pointer_sized(1usize); - require_pointer_sized(1u16); - //~^ ERROR `u16` needs to be a pointer-sized type - require_pointer_sized(&1i16); -} diff --git a/tests/ui/traits/new-solver/pointer-sized.stderr b/tests/ui/traits/new-solver/pointer-sized.stderr deleted file mode 100644 index b250b1331bbf9..0000000000000 --- a/tests/ui/traits/new-solver/pointer-sized.stderr +++ /dev/null @@ -1,24 +0,0 @@ -error[E0277]: `u16` needs to be a pointer-sized type - --> $DIR/pointer-sized.rs:9:27 - | -LL | require_pointer_sized(1u16); - | --------------------- ^^^^ the trait `PointerSized` is not implemented for `u16` - | | - | required by a bound introduced by this call - | - = note: the trait bound `u16: PointerSized` is not satisfied -note: required by a bound in `require_pointer_sized` - --> $DIR/pointer-sized.rs:5:34 - | -LL | fn require_pointer_sized(_: impl PointerSized) {} - | ^^^^^^^^^^^^ required by this bound in `require_pointer_sized` -help: consider borrowing here - | -LL | require_pointer_sized(&1u16); - | + -LL | require_pointer_sized(&mut 1u16); - | ++++ - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0277`. From a7597a15265df589b29ed3c61a3047994fc45d0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Tue, 7 Feb 2023 19:17:24 +0000 Subject: [PATCH 6/9] Tweak ICE message Modify main message to be more conversational and emit one fewer note. --- compiler/rustc_driver_impl/src/lib.rs | 4 +--- tests/ui/consts/const-eval/const-eval-query-stack.rs | 3 +-- tests/ui/consts/const-eval/const-eval-query-stack.stderr | 2 +- tests/ui/fmt/respanned-literal-issue-106191.rs | 2 +- tests/ui/impl-trait/issues/issue-86800.stderr | 4 +--- tests/ui/layout/valid_range_oob.stderr | 2 +- tests/ui/panics/default-backtrace-ice.stderr | 4 +--- tests/ui/treat-err-as-bug/delay_span_bug.stderr | 2 +- tests/ui/treat-err-as-bug/err.stderr | 2 +- 9 files changed, 9 insertions(+), 16 deletions(-) diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index 02e0b042ad263..66ed9ffe91824 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -1200,11 +1200,9 @@ pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) { if !info.payload().is::() && !info.payload().is::() { - let mut d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic"); - handler.emit_diagnostic(&mut d); + handler.emit_err(session_diagnostics::Ice); } - handler.emit_note(session_diagnostics::Ice); handler.emit_note(session_diagnostics::IceBugReport { bug_report_url }); handler.emit_note(session_diagnostics::IceVersion { version: util::version_str!().unwrap_or("unknown_version"), diff --git a/tests/ui/consts/const-eval/const-eval-query-stack.rs b/tests/ui/consts/const-eval/const-eval-query-stack.rs index 8f8a8cee3a0cc..81f28c1755deb 100644 --- a/tests/ui/consts/const-eval/const-eval-query-stack.rs +++ b/tests/ui/consts/const-eval/const-eval-query-stack.rs @@ -1,8 +1,7 @@ // compile-flags: -Ztreat-err-as-bug=1 // failure-status: 101 // rustc-env:RUST_BACKTRACE=1 -// normalize-stderr-test "\nerror: internal compiler error.*\n\n" -> "" -// normalize-stderr-test "note:.*unexpectedly panicked.*\n\n" -> "" +// normalize-stderr-test "\nerror: .*unexpectedly panicked.*\n\n" -> "" // normalize-stderr-test "note: we would appreciate a bug report.*\n\n" -> "" // normalize-stderr-test "note: compiler flags.*\n\n" -> "" // normalize-stderr-test "note: rustc.*running on.*\n\n" -> "" diff --git a/tests/ui/consts/const-eval/const-eval-query-stack.stderr b/tests/ui/consts/const-eval/const-eval-query-stack.stderr index b97975c4cd9e5..01fb8153cf384 100644 --- a/tests/ui/consts/const-eval/const-eval-query-stack.stderr +++ b/tests/ui/consts/const-eval/const-eval-query-stack.stderr @@ -1,5 +1,5 @@ error[E0080]: evaluation of constant value failed - --> $DIR/const-eval-query-stack.rs:17:16 + --> $DIR/const-eval-query-stack.rs:16:16 | LL | const X: i32 = 1 / 0; | ^^^^^ attempt to divide `1_i32` by zero diff --git a/tests/ui/fmt/respanned-literal-issue-106191.rs b/tests/ui/fmt/respanned-literal-issue-106191.rs index bb741c0ef93fa..5a18983a3fa70 100644 --- a/tests/ui/fmt/respanned-literal-issue-106191.rs +++ b/tests/ui/fmt/respanned-literal-issue-106191.rs @@ -3,7 +3,7 @@ // known-bug: #106191 // unset-rustc-env:RUST_BACKTRACE // had to be reverted -// error-pattern:internal compiler error +// error-pattern:unexpectedly panicked // failure-status:101 // dont-check-compiler-stderr diff --git a/tests/ui/impl-trait/issues/issue-86800.stderr b/tests/ui/impl-trait/issues/issue-86800.stderr index 6c4aa35679d5b..f3a773837785e 100644 --- a/tests/ui/impl-trait/issues/issue-86800.stderr +++ b/tests/ui/impl-trait/issues/issue-86800.stderr @@ -9,9 +9,7 @@ LL | type TransactionFuture<'__, O> = impl '__ + Future Date: Tue, 7 Feb 2023 14:31:38 -0500 Subject: [PATCH 7/9] Clearly signal purpose of the yaml template --- .github/ISSUE_TEMPLATE/ice.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/ice.yaml b/.github/ISSUE_TEMPLATE/ice.yaml index 8d25bb41c0806..7bec05cc575a8 100644 --- a/.github/ISSUE_TEMPLATE/ice.yaml +++ b/.github/ISSUE_TEMPLATE/ice.yaml @@ -1,4 +1,4 @@ -name: Internal Compiler Error (Structured form) +name: Internal Compiler Error (for use by automated tooling) description: For now, you'll want to use the other ICE template, as GitHub forms have strict limits on the size of fields so backtraces cannot be pasted directly. labels: ["C-bug", "I-ICE", "T-compiler"] title: "[ICE]: " From 4f36673e152170951f8b01bcdd6c2da953a65ccc Mon Sep 17 00:00:00 2001 From: Danilo Bargen Date: Tue, 7 Feb 2023 21:32:11 +0100 Subject: [PATCH 8/9] Docs: Fix format of headings in String::reserve --- library/alloc/src/string.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index ca182c8109ec9..7565918851554 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -928,12 +928,12 @@ impl String { /// Copies elements from `src` range to the end of the string. /// - /// ## Panics + /// # Panics /// /// Panics if the starting point or end point do not lie on a [`char`] /// boundary, or if they're out of bounds. /// - /// ## Examples + /// # Examples /// /// ``` /// #![feature(string_extend_from_within)] From 6fdfdea8b11bd1c6b66d03869e7ec0bee0b94b4d Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 7 Feb 2023 23:08:25 +0000 Subject: [PATCH 9/9] Remove astconv usage in diagnostic --- .../src/fn_ctxt/suggestions.rs | 21 +++++----- tests/ui/typeck/issue-107775.rs | 40 +++++++++++++++++++ tests/ui/typeck/issue-107775.stderr | 16 ++++++++ 3 files changed, 67 insertions(+), 10 deletions(-) create mode 100644 tests/ui/typeck/issue-107775.rs create mode 100644 tests/ui/typeck/issue-107775.stderr diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 51e3e3ec73db9..4e3c20196945a 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -1336,16 +1336,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir::Path { segments: [segment], .. }, )) | hir::ExprKind::Path(QPath::TypeRelative(ty, segment)) => { - let self_ty = self.astconv().ast_ty_to_ty(ty); - if let Ok(pick) = self.probe_for_name( - Mode::Path, - Ident::new(capitalized_name, segment.ident.span), - Some(expected_ty), - IsSuggestion(true), - self_ty, - expr.hir_id, - ProbeScope::TraitsInScope, - ) { + if let Some(self_ty) = self.typeck_results.borrow().node_type_opt(ty.hir_id) + && let Ok(pick) = self.probe_for_name( + Mode::Path, + Ident::new(capitalized_name, segment.ident.span), + Some(expected_ty), + IsSuggestion(true), + self_ty, + expr.hir_id, + ProbeScope::TraitsInScope, + ) + { (pick.item, segment) } else { return false; diff --git a/tests/ui/typeck/issue-107775.rs b/tests/ui/typeck/issue-107775.rs new file mode 100644 index 0000000000000..6fbac2ee9758e --- /dev/null +++ b/tests/ui/typeck/issue-107775.rs @@ -0,0 +1,40 @@ +// edition: 2021 + +use std::collections::HashMap; +use std::future::Future; +use std::pin::Pin; + +pub trait Trait { + fn do_something<'async_trait>(byte: u8) + -> + Pin + + Send + 'async_trait>>; +} + +pub struct Struct; + +impl Trait for Struct { + fn do_something<'async_trait>(byte: u8) + -> + Pin + + Send + 'async_trait>> { + Box::pin( + + async move { let byte = byte; let _: () = {}; }) + } +} + +pub struct Map { + map: HashMap Pin + Send>>>, +} + +impl Map { + pub fn new() -> Self { + let mut map = HashMap::new(); + map.insert(1, Struct::do_something); + Self { map } + //~^ ERROR mismatched types + } +} + +fn main() {} diff --git a/tests/ui/typeck/issue-107775.stderr b/tests/ui/typeck/issue-107775.stderr new file mode 100644 index 0000000000000..9ee9c022c6e8c --- /dev/null +++ b/tests/ui/typeck/issue-107775.stderr @@ -0,0 +1,16 @@ +error[E0308]: mismatched types + --> $DIR/issue-107775.rs:35:16 + | +LL | map.insert(1, Struct::do_something); + | - -------------------- this is of type `fn(u8) -> Pin + Send>> {::do_something::<'_>}`, which causes `map` to be inferred as `HashMap<{integer}, fn(u8) -> Pin + Send>> {::do_something::<'_>}>` + | | + | this is of type `{integer}`, which causes `map` to be inferred as `HashMap<{integer}, fn(u8) -> Pin + Send>> {::do_something::<'_>}>` +LL | Self { map } + | ^^^ expected `HashMap Pin<...>>`, found `HashMap<{integer}, ...>` + | + = note: expected struct `HashMap Pin + Send + 'static)>>>` + found struct `HashMap<{integer}, fn(_) -> Pin + Send>> {::do_something::<'_>}>` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`.